Django,在模板中显示ValidationError [英] Django, show ValidationError in template

查看:235
本文介绍了Django,在模板中显示ValidationError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



查看

$ b从django.shortcuts导入render
从django.shortcuts导入render_to_response
从django.http导入HttpResponseRedirect
从django
$ b

 .core.context_processors import csrf 

从表单导入RegistrationForm

#在这里创建您的意见。
def register_user(request):
如果request.method =='POST':
form = RegistrationForm(request.POST)
如果form.is_valid():
form.save()
return HttpResponseRedirect('../../ membership / register_success')
else:
返回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
来自django.contrib.auth.forms从django.utils.translation import ugettext_lazy导入UserCreationForm
$ _

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

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

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

如果电子邮件和User.objects.filter(email = email).exclude(username = username).count():
raise forms.ValidationError(_(此电子邮件地址已被使用。请提供不同的电子邮件地址。)
返回电子邮件

def save(self,commit = True):
user = super(RegistrationForm,self).save = False)
user.email = self.cleaned_data ['email']
如果提交:
user.save()
返回用户



registration.html



  {%extends base.html%} 
{%block title%}注册{%endblock%}

{%block content%}

< h1>注册< ; / h1>

{%if form.errors%}
< h1> ERRORRRRRR同样的电子邮件再次< / h1>
{%endif%}

{%如果注册%}
< strong>感谢您注册!< / strong>
< a href =../../>返回首页。< / a>< br />
{%else%}
< stron g>在这里注册!< / strong>< br />

< form method =postaction =/ membership / register /> {%csrf_token%}
{{form}}
< input type = submitname =submitvalue =注册/>
< / form>
{%endif%}

{%endblock%}


解决方案

您正在模板上显示 {{form}} 的表单。这本身应该默认显示所有的验证错误,但在你的情况下,如果表单无效,您将重定向到其他页面。因此,除非您使用GET参数传递错误,否则无法显示错误。您可以将自己的观点更改为在注册页面上获取错误 -

  def register_user(request):
args = {}
如果request.method =='POST':
form = RegistrationForm(request.POST)
如果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 / p>

如果请求方法不是POST,那么没有数据的表单对象被实例化并传递给 render()



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


I create a registation app, where users can register providing a username, email and a password. What I did is make sure that the email field is unique(as you can see in the code below). But I can't figure out how I can show the error in case the a user enters an email address that is already in use.

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')

Form

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 %}

解决方案

You're showing the form with {{ form }} on the template. That itself should show all the validation errors by default, but in your case, you're redirecting to some other page if the form is invalid. So you can never show the errors unless you pass the errors with the GET parameters. You could change your view to this to get the errors on the signup page itself -

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)

How this works is, if the request method is POST, the form gets initiated with the POST data, then it's validated with the is_valid() call, so the form object now has the validation error messages if it's invalid. If it's valid, it's saved and redirected. If not valid, it comes to the args['form'] = form part where the form object with the error messages is set to the context and then passed to render.

If the request method is not POST, then a form object with no data is instantiated and passed to render().

Now your template should show all the error messages just below each field if there is any error.

这篇关于Django,在模板中显示ValidationError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆