当我尝试注册新用户时,页面返回一个AttributeError,如下所示:
我正在使用自定义模型,这是我的models.py和forms.py:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class Person(AbstractUser):
pass
和
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import Person
# Create your forms here.
class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = Person
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
最后,这是我对帐户应用的views.py:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from .forms import SignUpForm
# Create your views here.
def signup(request):
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(user)
return redirect('lists:index')
else:
form = SignUpForm()
context = {
"form": form
}
return render(request, 'accounts/signup.html', context)
def login(request):
context = {
}
return render(request, "accounts/login.html", context)
我该如何解决这个问题?似乎错误与我的views.py中的login()函数有关,但我不明白为什么。好的方法,这是我的setting.py中显示我的AUTH_USER_MODEL的部分:
AUTH_USER_MODEL = 'accounts.Person'
答案 0 :(得分:1)
请勿在{{1}}中使用class Meta:
,只包括定义您要使用的字段,如:
SignUpForm
您即将使用class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
password1 = forms.CharField(label="Password", max_length=30,
widget=forms.TextInput(
attrs={'class': 'form-control',
'name': 'password', 'id': 'password',
'type': 'password', 'placeholder': 'Password'}))
# similarly other fields like username, password1 and password2