我使用request.user.is_authenticated() 這個視圖來探查。Django 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所示:OK 如果用戶沒有登錄,他不是發佈的數據則顯示形式:OK 當我從表單提交的數據我收回此錯誤:
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
不甲肝e提交表單數據時的user
對象。我如何解決? 謝謝
等。 request.user在兩種情況下工作(當我檢查用戶是否登錄或如果他做了頁面的GET),但不是當我從表單發佈數據時。 – EsseTi
重點是,當我發佈數據時,請求值更改爲表單數據。所以沒有用戶對象。 是否正確? – EsseTi
是的。讓我想想這個。現在,你仍然有一個錯誤(檢查編輯我要回答) – Mamsaac