如何将UserCreationForm扩展到包含电子邮件字段 [英] How do I extend UserCreationForm to include email field
问题描述
我设法使股票标准用户创建表单正常工作。其中只包括用户名,密码1和密码2字段。但是,当我尝试添加电子邮件字段时,它不会显示在我的模板中。我想我也许在我看来缺少一些东西。这是我的代码:
I managed to get the stock standard User Creation Form to work. Which included just the username, password1 and password2 field. However, when I try to include the email field it never shows up in my template. I think I'm missing something in my view perhaps. Here is my code:
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class UserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
views.py
from django.contrib.auth.forms import UserCreationForm
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
return render_to_response('stories/register.html', args)
register.html
<form action = "/register/" method = "POST">
{% csrf_token %}
<p>
{{ form.username.label_tag }}
{{ form.username}}
</p>
<p>
{{ form.email.label_tag }}
{{ form.email }}
</p>
<p>
{{ form.password1.label_tag }}
{{ form.password1 }}
</p>
<p>
{{ form.password2.label_tag }}
{{ form.password2 }}
</p>
<input type = "submit" value = "register" />
</form>
此文件中的所有字段正在呈现到视图中,除电子邮件字段。
All of the fields in this file are being rendered into the view, Except the email field.
任何人都可以发现为什么?
Can anyone spot why?!
推荐答案
您正在views.py中导入错误的 UserCreationForm
您应该导入自己的形式而不是Django的表单:
You are importing the wrong UserCreationForm
in views.py. You should import your own form not the Django's one:
stories / views.py
from stories.forms import UserCreationForm
...
除此之外,您不必将< p>< / p>
的所有字段单独包含 form.as_p()
一个>这个工作。
Besides that, you don't have to wrap all your fields with <p></p>
individually as there exists form.as_p()
for this job.
register.html
<form action = "/register/" method = "POST">{% csrf_token %}
{{ form.as_p }}
</form>
希望这有帮助。
这篇关于如何将UserCreationForm扩展到包含电子邮件字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!