2012-10-04 48 views
0

我使用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對象。我如何解決? 謝謝

回答

3

你正在用request.POST數據填充你自己的視圖函數,就好像它是表單一樣。

if request.method == 'POST': 
    '''if post, check the data''' 
    form = ContributorRegistration(request.POST) 
    if form.is_valid(): 

應該

if request.method == 'POST': 
    '''if post, check the data''' 
    form = RegistrationForm(request.POST) 
    if form.is_valid(): 

爲了有request.user對象訪問,你需要安裝在你的應用程序中的用戶身份驗證的中間件。要做到這一點(非常容易),請執行下列操作:

轉到您的settings.py並添加'django.contrib.auth''django.contrib.contenttypes'INSTALLED_APPS元組。

您很可能需要一個syncdb命令才能完全安裝它(您需要一些用於用戶身份驗證的數據庫表)。

python manage.py syncdb 

而這應該使它工作。

+0

等。 request.user在兩種情況下工作(當我檢查用戶是否登錄或如果他做了頁面的GET),但不是當我從表單發佈數據時。 – EsseTi

+0

重點是,當我發佈數據時,請求值更改爲表單數據。所以沒有用戶對象。 是否正確? – EsseTi

+1

是的。讓我想想這個。現在,你仍然有一個錯誤(檢查編輯我要回答) – Mamsaac

0

它只是我或是您的表單名稱與您的查看功能ContributorRegistration相同嗎?

也許你犯了一個錯字。

+0

表單是'類RegistrationForm(BootstrapForm):' 視圖是'def ContributorRegistration(request):' – EsseTi

+0

這不是你的觀點顯示。 –

+0

而且我做的更正。表單(當它不是POST請求時)將顯示使用「RegistrationForm」。 – Mamsaac