我如何扩展UserCreationForm以包括电子邮件字段

我设法使标准的用户创建表格正常工作.其中仅包含用户名,密码1和密码2字段.但是,当我尝试包含电子邮件字段时,它永远不会显示在我的模板中.我认为我可能正在丢失某些东西.这是我的代码:

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>

该文件中的所有字段都将呈现到视图中,电子邮件字段除外.

谁能找到原因?

最佳答案
您在views.py中导入了错误的UserCreationForm.您应该导入自己的表单而不是Django的表单:

故事/ views.py

from stories.forms import UserCreationForm
...

除此之外,您不必使用< p>< / p>来包装所有字段.单独存在,因为此工作存在form.as_p().

register.html

<form action = "/register/" method = "POST">{% csrf_token %}
    {{ form.as_p }}
</form>

希望这可以帮助.

转载注明原文:我如何扩展UserCreationForm以包括电子邮件字段 - 代码日志