我使用UserCreationForm
在Django中呈现注册表单。
class RegisterForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields
注册视图定义如下:
def register(request):
form = RegisterForm()
if request.method == 'POST':
form = RegisterForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('/')
else:
context = {'form': form}
return render(request, 'registration/register.html', context)
这个模板:
{% if form.errors %}
<p>Some Errors occured</p>
{% endif %}
<form action="{% url 'register' %}" method="POST">
{% csrf_token %} {{ form.as_p }}
<input type="submit" value="Register">
</form>
当我提交无效数据时,它不显示<p>Some Errors occured</p>
,而是抛出
Exception Type: ValueError
Exception Value:
这意味着我必须在第二个if / else语句中返回HttpResponsein。其他表单工作正常,并显示form.error消息,除了这一个。问题是什么?感谢。
The view myapp.views.register didn't return an HttpResponse object. It returned None instead.
答案 0 :(得分:1)
您需要将最后一行向后移动一个缩进,因此在请求不是POST的情况下以及在POST是但是表单无效的情况下都会运行它。
答案 1 :(得分:1)
form = RegisterForm(request.POST或None,request.FILES或None)
首先,你不想在你的注册表格中找到一个空白的字段,所以你不想要用户或无。第二,当你的表单中没有FileField时,你正在使用request.FILES。我修改了你的表格
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('/')
else:
form = RegisterForm()
return render(request, 'registration/register.html',{'form': form})