Django 1.6 - 'AnonymousUser'对象没有属性'后端'

时间:2014-05-19 07:35:29

标签: python django authentication

我正在尝试在Django中创建一个简单的用户注册,我收到此错误。我在stackoverflow上查了一下:'AnonymousUser' object has no attribute 'backend'Django Register Form 'AnonymousUser' object has no attribute 'backend'并尝试在登录前调用身份验证。但我一直收到这个错误。

有人可以帮我解决这个问题吗?

这是追溯

Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  57.         return view_func(*args, **kwargs)
File "/Users/harisaghadi/Dropbox/Senior Project/Django Tutorials/mysite/meddy1/views.py" in signup_user
  51.           login(request, new_user)
File "/Library/Python/2.7/site-packages/django/contrib/auth/__init__.py" in login
  85.     request.session[BACKEND_SESSION_KEY] = user.backend
File "/Library/Python/2.7/site-packages/django/utils/functional.py" in inner
  214.         return func(self._wrapped, *args)

Exception Type: AttributeError at /meddy1/signup/
Exception Value: 'AnonymousUser' object has no attribute 'backend'

这是我的forms.py

class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
    'duplicate_username': _("A user with that username already exists."),
    'password_mismatch': _("The two password fields didn't match."),
}
email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Please enter a valid email address so we can reach you.'}))
username = forms.RegexField(label=_("Username"), max_length=30,
    regex=r'^[\w.@+-]+$',
    help_text=_("Required. 30 characters or fewer. Letters, digits and "
                "@/./+/-/_ only."),
    error_messages={
        'invalid': _("This value may contain only letters, numbers and "
                     "@/./+/-/_ characters.")})
password1 = forms.CharField(label=_("Password"),
    widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
    widget=forms.PasswordInput,
    help_text=_("Enter the same password as above, for verification."))

class Meta:
    model = User
    fields = ("username",)

def clean_username(self):
    # Since User.username is unique, this check is redundant,
    # but it sets a nicer error message than the ORM. See #13147.
    username = self.cleaned_data["username"]
    try:
        User._default_manager.get(username=username)
    except User.DoesNotExist:
        return username
    raise forms.ValidationError(
        self.error_messages['duplicate_username'],
        code='duplicate_username',
    )

def clean_password2(self):
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError(
            self.error_messages['password_mismatch'],
            code='password_mismatch',
        )
    return password2

def save(self, commit=True):
    user = super(UserCreationForm, self).save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()

        userProfile = DoctorSeeker(user=user, name=name, email=email)
        userProfile.save()

    return user

views.py

def index(request):
    return HttpResponse("Welcome to Meddy")

# -------------------- Authentication ----------------------
def signup(request):
    return render(request, 'meddy1/signup.html', {})

@csrf_exempt
def signup_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST,request.FILES)
        if form.is_valid():
            new_user = authenticate(username=request.POST['username'],password=request.POST['password1'])
            login(request, new_user)

            return HttpResponseRedirect(reverse('index'))
    else:
        form = UserCreationForm()
    return render(request, "meddy1/signup.html", {'form': form,'usersignup':True})



def login_user(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username,password=password)
    if user:
        return render(request, 'meddy1/index.html')
    else:
        return HttpResponseRedirect('/')


def logout_user(request):
    logout(request)
    return HttpResponseRedirect('/')

models.py

class DoctorSeeker(models.Model):
    name = models.CharField(max_length=30)
    email = models.EmailField()
    user = models.ForeignKey(User, unique=True)

    def __unicode__(self):
        return u"%s %s" % (self.name, self.email)

1 个答案:

答案 0 :(得分:2)

既然您找到了类似的帖子,我就知道,您的身份验证并不能真正验证任何内容。它出于某种原因失败了。

我理解你向我们展示的观点是试图完成两件事 - 创建用户并将他登录?对?因为它的名字是signup_user。

好。您有UserCreationForm,但您没有保存。因此,您无法真正验证系统中尚不存在的用户。首先保存表单,然后调用身份验证。