扩展 UserCreationForm 以包含电子邮件、名字和姓氏 [英] Extending UserCreationForm to include email, first name, and last name
问题描述
我已经被这个问题困住了一段时间,似乎无法弄清楚发生了什么.我刚刚开始学习 Django,我已经设置了登录名,现在想要实现一个注册页面.
I've been stuck on this for a while now and can't seem to figure out what's going on. I'm just starting to learn Django and I got my login set up and now want to implement a registration page.
我一开始使用 UserCreationForm 表单,效果很好,但我想为电子邮件、名字和姓氏添加字段.我想我可以子类化 UserCreationForm 并添加字段,但这似乎不起作用.我也尝试覆盖 save 方法,但它仍然不起作用.
I used the UserCreationForm form at first and that worked fine, but I want to add fields for Email, First name, and Last name. I figured I could just subclass UserCreationForm and add the fields but that doesn't seem to work. Also I tried overriding the save method, but it still doesn't work.
我的自定义表单如下所示:
My custom form looks like this:
class RegistrationForm(UserCreationForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.EmailField(max_length=75)
class Meta:
model = User
fields = ("first_name", "last_name", "email",)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
处理此问题的视图如下:
The view to handle this is the following:
def Register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
new_user = form.save();
new_user = authenticate(username=request.POST['username'], password=request.POST['password1'])
login(request, new_user)
return HttpResponseRedirect('/members/home')
else:
form = RegistrationForm()
return render_to_response('register.html', {'form' : form}, context_instance=RequestContext(request))
表单可以很好地加载新字段和所有内容,但是当我提交时出现错误:
The form loads just fine with the new fields and everything, but when I submit I get the error:
AttributeError at /register/
'AnonymousUser' object has no attribute 'backend'
哦,我也在使用 Django 1.3.
Oh, and also I'm using Django 1.3.
知道我做错了什么吗?
推荐答案
我猜你的元类 fields
不包括 username
.
My guess is that your meta class fields
doesn't include username
.
您正在从 UserCreationForm
继承表单字段,但它没有保存到 User
模型,因此 authenticate
失败,并在 authenticate
上崩溃代码>登录()代码>
You are inheriting the form field from UserCreationForm
but it's not saving to the User
model and therefore authenticate
is failing, and crashing on login()
文档建议您在使用 login()
这篇关于扩展 UserCreationForm 以包含电子邮件、名字和姓氏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!