0

我对 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我该如何解决?谢谢

4

2 回答 2

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

这应该使它起作用。

于 2012-10-04T17:25:19.160 回答
0

只是我还是您的表单名称与您的视图功能相同ContributorRegistration

也许你打错了。

于 2012-10-04T17:37:59.557 回答