gpt4 book ai didi

django - Django,在模板中显示ValidationError

转载 作者:行者123 更新时间:2023-12-03 12:40:01 26 4
gpt4 key购买 nike

我创建了一个注册应用程序,用户可以在其中注册,提供用户名,电子邮件和密码。我所做的是确保电子邮件字段是唯一的(如下面的代码所示)。但是,如果用户输入已经使用的电子邮件地址,我无法弄清楚如何显示错误。

View

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf

from forms import RegistrationForm

# Create your views here.
def register_user(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('../../membership/register_success')
else:
return HttpResponseRedirect('../../membership/register_failed')

args = {}
args.update(csrf(request))

args['form'] = RegistrationForm()

return render(request,'registration/registration_form.html', args)

def register_success(request):
return render_to_response('registration/registration_success.html')

def register_failed(request):
return render_to_response('registration/registration_failed.html')

形成
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import ugettext_lazy as _

# forms.py
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)

class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')

def clean_email(self):
email = self.cleaned_data.get('email')
username = self.cleaned_data.get('username')

if email and User.objects.filter(email=email).exclude(username=username).count():
raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
return email

def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user

registration.html
    {% extends "base.html" %}
{% block title %}Registration{% endblock %}

{% block content %}

<h1>Registration</h1>

{% if form.errors %}
<h1>ERRORRRRRR same email again???</h1>
{% endif %}

{% if registered %}
<strong>thank you for registering!</strong>
<a href="../../">Return to the homepage.</a><br />
{% else %}
<strong>register here!</strong><br />

<form method="post" action="/membership/register/">{% csrf_token %}
{{ form }}
<input type="submit" name="submit" value="Register" />
</form>
{% endif %}

{% endblock %}

最佳答案

您正在模板上显示带有{{ form }}的表单。默认情况下,它本身应该显示所有验证错误,但是对于您而言,如果表单无效,您将重定向到其他页面。因此,除非您通过GET参数传递错误,否则您将永远无法显示错误。您可以将 View 更改为此,以在注册页面本身上获取错误-

def register_user(request):
args = {}
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('../../membership/register_success')
else:
form = RegistrationForm()
args['form'] = form

return render(request,'registration/registration_form.html', args)

这是如何工作的,如果请求方法是POST,则使用POST数据启动表单,然后通过 is_valid()调用对其进行验证,因此,如果表单对象无效,则该表单对象现在具有验证错误消息。如果有效,则将其保存并重定向。如果无效,它将进入 args['form'] = form部分,其中将带有错误消息的表单对象设置为上下文,然后传递给渲染。

如果请求方法不是POST,则实例化一个没有数据的表单对象并将其传递给 render()

现在,如果有任何错误,您的模板应在每个字段正下方显示所有错误消息。

关于django - Django,在模板中显示ValidationError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22470637/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com