我想在Django中創建一個簡單的用戶註冊,並且出現此錯誤。我已經在這裏查找它在計算器上:'AnonymousUser' object has no attribute 'backend',Django Register Form 'AnonymousUser' object has no attribute 'backend'並嘗試登錄前調用身份驗證。但我不斷收到這個錯誤。Django 1.6 - 'AnonymousUser'對象沒有屬性'後端'
任何人都可以幫助我嗎?
這裏是回溯
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'^[\[email protected]+-]+$',
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)
你應該顯示確切的回溯,所以我們知道這些許多視圖中哪一個觸發了錯誤。但請注意,您的signup_user視圖似乎缺少一個步驟,即您實際創建用戶的步驟;並且您的login_user也缺少一個步驟,即您在進行身份驗證後實際登錄用戶的步驟。 –
我已經添加了上面的回溯。你能否詳細說明缺失的步驟?謝謝 –