使用默认弹出窗口显示Django Forms错误 [英] Using default popups to show Django Forms errors

查看:156
本文介绍了使用默认弹出窗口显示Django Forms错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用Django Forms定义表单时,如果我有一个EmailField,我会得到一些整洁的弹出窗口,如我在图片中所示:

When defining a form using Django Forms, if I have an EmailField, I will get some neat popups like I show in the pictures:


但是,如果我引入自定义验证,则无法以相同的方式(带有弹出窗口)向用户显示错误

But if I introduce a custom validation, I am unable to show errors to user in the same way (with a popup)

这是我的form.py:

This is my forms.py:

from django import forms
from launcher.models import InterestedUser
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator

class JoinForm(forms.ModelForm):
# this is the only field that is actually filled by the user
    email = forms.EmailField(max_length=128, help_text="Introduce la cuenta de gmail que tienes asociada a tu"
                                                   "dispositivo Android",
                         widget=forms.EmailInput(attrs={'class': "w-input email_input",
                                                        'placeholder': 'Tu email de Google'}),
                         required=True, validators=[RegexValidator(regex='^([a-zA-Z0-9_\.\-])+\@(gmail.com)+$',
                                                                   message="La dirección de email no es válida",
                                                                   code="invalid_gmail_address")])
print("atributos {0}".format(email.widget.attrs['class']))

# this other fields will have the same value and go hidden in the form
name = forms.CharField(widget=forms.HiddenInput(), initial="(not specified)")
subject = forms.CharField(widget=forms.HiddenInput(), initial="(no subject)")
via = forms.CharField(widget=forms.HiddenInput(), initial="Join")
content = forms.CharField(widget=forms.HiddenInput(), initial="no content")

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

    try:
        beta_tester = InterestedUser.objects.get(email=email)
    # Si el email no existiese entonces salimos del clean_email y devolvemos el valor (aunque no se haya modificado)
    except InterestedUser.DoesNotExist:
        return email
    # Si el email ya existía sacamos un error de Validación:
    raise forms.ValidationError("Ya estabas anotado como Beta Tester, introduce un email diferente!")


class Meta:
    model = InterestedUser
    fields = ('email', 'name', 'subject', 'via', 'content',)

这就是我的方式将其呈现在模板中:

And this is how I render it in the template:

            <div class="w-form formulario" id="formulario">
                <form class="w-clearfix formulario_subscribe" name="email-form" id="join_form" method="post" data-name="Email Form" action="/">
                    {% csrf_token %}
                    {% for hidden in form.hidden_fields %}
                        {{  hidden }}
                    {% endfor %}
                    {% for field in form.visible_fields %}
                        {{ field.errors }}
                        {{ field.help_text }}
                        {{ field }}
                    {% endfor %}
                    <input class="w-button email_submit_button" type="submit" id="btn_send" value="Join" data-wait="Un momento!..."/>
                    {% if messages %}
                        <ul class="messages">
                            {% for message in messages %}
                                <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
                            {% endfor %}
                        </ul>
                    {% endif %}
                </form>
            </div>

我有一个RegexValidator,如果用户输入未通过,我想显示错误消息验证器以与默认验证器相同的方式(弹出窗口)执行!有什么想法吗?

I have a RegexValidator and I would like to show the error message if the user input doesn't pass the validator in the same way (popups) that the default validator does it! Any ideas??

多谢了。

推荐答案

我认为此弹出窗口是由浏览器验证HTML5电子邮件字段(看起来像chrome)创建的,您可以禁用此验证,将 novalidate 属性添加到表单字段。或更有趣的是,您可以使用模式检查gmail.com地址,例如:

I think this popup is created by the browser validating the HTML5 email field(looks like chrome) you can disable this validation adding the novalidate attribute to the form field. Or more interesting you can use pattern to check for gmail.com addresses, something like:

<input type="email" pattern="/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@gmail.com$" />

如果要在客户端进行验证,可以使用 parsley

If you want to validate on the client side you can use something like parsley

此外,您也可以检查< a href = https://github.com/django/django/blob/master/django/core/validators.py#L137 rel = nofollow> EmailValidator 。有一个属性 domain_whitelist 可用于限制gmail.com域。

Also instead of validate emails with a regex you can check EmailValidator. There's a property domain_whitelist that you can use to restrict gmail.com domains.

这篇关于使用默认弹出窗口显示Django Forms错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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