我想要完成的是扩展UserCreationForm,以便在每个用户注册时为其添加电子邮件字段。目前我有一个来自UserCreationForm的表格,其中包含用户名和密码,但没有电子邮件。我使用forms.py文件扩展它,并在我的views.py中实现它。但是,当我运行测试并查看注册页面时,找不到电子邮件字段。
views.py:
chrome.webRequest.onBeforeRequest...
forms.py:
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login as auth_login
from .forms import SignUpForm
# Create your views here.
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
auth_login(request, user)
return redirect('index')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
form.html:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
email = forms.CharField(max_length = 254, required = True, widget = forms.EmailInput())
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
现在,当我实际进入登录页面时,它只显示用户名和密码字段。但是,当我刷新页面或发送无效表单时,电子邮件字段会在表单重新加载时显示。它确认当我运行测试并获得断言错误时,该字段没有出现在初始加载中:
{% load widget_tweaks %}
{% for field in form %}
<div class="form-group">
{{ field.label_tag }}
{% if form.is_bound %}
{% if field.errors %}
{% render_field field class="form-control is-invalid" %}
{% for error in field.errors %}
<div class="invalid-feedback">
{{ error }}
</div>
{% endfor %}
{% else %}
{% render_field field class="form-control is-valid" %}
{% endif %}
{% else %}
{% render_field field class="form-control" %}
{% endif %}
{% if field.help_text %}
<small class="form-text text-muted">
{{ field.help_text|safe }}
</small>
{% endif %}
</div>
{% endfor %}