我正在使用Django 1.6 auth模块登录用户,我有一个包含两个应用程序的项目,我希望通过在我的第二个应用程序的视图中调用request.user.username来使用同一个用户。也就是说,在第一个应用程序中我的模板login.html中{%if user.is_authenticated%}但{%if user.is_authenticated%}在第二个应用模板中不起作用,我想知道如何获取它在第二个应用程序的功能?我试图用user = request.user.username获取它,但它不起作用。
在我的第一个应用中:
models.py
from django.contrib.auth.models import User
class Userprofile(models.Model):
user = models.OneToOneField(User)
title = models.CharField(max_length = 70)
def __unicode__(self):
return self.title
class OneUser(models.Model):
Firstname = models.CharField(max_length = 35)
Lastname = models.CharField(max_length = 35)
Email = models.EmailField()
belongsTo = models.ForeignKey(Userprofile, related_name='pcslabeler_userprofile')
def __unicode__(self):
return self.Firstname
在views.py中
def LoginIndex(request):
c = {}
c.update(csrf(request))
return render(request,"login.html", c)
#logins = Login.objects.all()
def one_login(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)# user firstname lastname
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/loggedin')# topic
else:
return HttpResponseRedirect('/invalid')
def loggedin(request):
return render(request,"loggedin.html",{'full_name': request.user.username})
def invalid_login(request):
return render(request,"invalid_login.html")
def logout(request):
auth.logout(request)
return render(request,"logout.html")
在第二个应用视图中,我试图在postoneEval函数中使用它:
def EvalIndex(request):
evals = Evaluation.objects.all()
return render_to_response("evaluation_index.html",{"evals":evals})
def one_evaluation(request, postID):
one_eval = Evaluation.objects.get(id=postID)
one_part = Participation.objects.get(id=postID)
if request.method == 'POST':
form = EvalForm(request.POST)
form2 = ParticipationForm(request.POST)
if form.is_valid() and form2.is_valid():
postoneEval(request, one_eval)
postoneParticipant(request, one_part)
else:
form = EvalForm()
form2 = ParticipationForm()
c = {"one_eval":one_eval,"one_part":one_part, "form":form, "form2":form2}
c.update(csrf(request))
return render_to_response("one_evaluation_index.html", c )
def postoneEval(request, one_eval):
title = request.POST["title"]
user = request.user.username
oneEval = OneEvaluation(datetime=datetime.datetime.now(), belongsTo=one_eval, title=title, user=user)
oneEval.save()
答案 0 :(得分:1)
问题出在render_to_reponse()
电话中。您没有传递RequesContext
实例,因此不会为您的模板运行上下文处理器。
此问题的最简单解决方案是将render_to_response()
替换为render()
:
return render(request, "evaluation_index.html", {"evals":evals})
和
return render(request, "one_evaluation_index.html", c)