我对 request.user.is_authenticated() 这个视图有疑问。
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.template import RequestContext
from forms import RegistrationForm
def ContributorRegistration(request):
if request.user.is_authenticated():
'''if user is logged in -> show profile'''
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
'''if post, check the data'''
form = ContributorRegistration(request.POST)
if form.is_valid():
''' if form is valid, save the data'''
user = User.objects.create_user(username=form.cleaned_data['username'],email = form.cleaned_data['email'], password= form.cleaned_data['password'])
user.save()
contributor = user.get_profile()
contributor.location = form.cleaned_data['location']
contributor.save()
return HttpResponseRedirect('profile.html')
else:
'''form not valid-> errors'''
return render_to_response('register.html',{'form':form},context_instance=RequestContext(request))
else:
'''method is not a post and user is not logged, show the registration form'''
form = RegistrationForm()
context={'form':form}
return render_to_response('register.html',context,context_instance=RequestContext(request))
基本上,如果用户已登录,则显示 profile.html:好的 ,如果用户未登录且他没有发布数据,则显示表单:好的 ,当我从表单提交数据时,我收到此错误:
Request Method: POST
Request URL: http://localhost:8000/register/
Django Version: 1.4.1
Exception Type: AttributeError
Exception Value:
'QueryDict' object has no attribute 'user'
Exception Location: /Users/me/sw/DjangoProjects/earth/views.py in ContributorRegistration, line 9
第 9 行if request.user.is_authenticated():
似乎在提交表单数据时request
没有对象。user
我该如何解决?谢谢