字段为空时,UserCreationForm显示错误

时间:2017-02-18 09:06:27

标签: python django python-3.x django-forms django-views

我正在使用内置UserCreationForm的Django。我想在该字段为空并且用户提交表单时在该字段下显示消息。不幸的是,我只看到浏览器的内置行为,例如"填写此字段",顺便说一下,在不同的浏览器中,行为是不同的。有些浏览器只用红线环绕字段框。如何关闭此行为并在字段下显示消息。为什么.error_messages没有用?!我也在模板中使用{{form.field_name.errors}}。

forms.py

class RegistrationForm(UserCreationForm):
    required_css_class = 'required'
    email = forms.EmailField()
    first_name = forms.CharField()
    last_name = forms.CharField()

    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name')

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget = TextInput(attrs={'placeholder': _('Username')})
        self.fields['username'].required = True
        self.fields['username'].error_messages = {'required': 'Please enter your username'}

        self.fields['email'].widget = EmailInput(attrs={'placeholder': _('Email address')})
        self.fields['email'].required = True
        self.fields['email'].error_messages = {'required': 'Please enter your email'}

        self.fields['first_name'].widget = TextInput(attrs={'placeholder': _('First name')})
        self.fields['first_name'].required = True
        self.fields['first_name'].error_messages = {'required': 'Please enter your first_name'}

        self.fields['last_name'].widget = TextInput(attrs={'placeholder': _('Last name')})
        self.fields['last_name'].required = True
        self.fields['last_name'].error_messages = {'required': 'Please enter your last_name'}

        self.fields['password1'].widget = PasswordInput(attrs={'placeholder': _('Password')})
        self.fields['password1'].required = True
        self.fields['password1'].error_messages = {'required': 'Please enter your Password'}

        self.fields['password2'].widget = PasswordInput(attrs={'placeholder': _('Confirm password')})
        self.fields['password2'].required = True
        self.fields['password2'].error_messages = {'required': 'Please enter your Confirm Password'}

view.py

class RegistrationView(FormView):
    disallowed_url = 'registration_closed'
    form_class = RegistrationForm
    http_method_names = ['get', 'post', 'head', 'options', 'trace']
    success_url = 'registration_complete'
    template_name = 'account/registration_form.html'
    SEND_ACTIVATION_EMAIL = getattr(settings, 'SEND_ACTIVATION_EMAIL', True)

    registration_profile = RegistrationProfile

    @method_decorator(sensitive_post_parameters('password1', 'password2'))
    def dispatch(self, request, *args, **kwargs):
        if not self.registration_allowed():
            return redirect(self.disallowed_url)
        return super(RegistrationView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        new_user = self.register(form)
        success_url = self.get_success_url(new_user)
        try:
            to, args, kwargs = success_url
        except ValueError:
            return redirect(success_url)
        else:
            return redirect(to, *args, **kwargs)

    def registration_allowed(self):
        return getattr(settings, 'REGISTRATION_OPEN', True)

    def register(self, form):
        site = get_current_site(self.request)

        if hasattr(form, 'save'):
            new_user_instance = form.save()
        else:
            new_user_instance = (UserModel().objects.create_user(**form.cleaned_data))

        new_user = self.registration_profile.objects.create_inactive_user(
            new_user=new_user_instance,
            site=site,
            send_email=self.SEND_ACTIVATION_EMAIL,
            request=self.request,
        )
        signals.user_registered.send(sender=self.__class__, user=new_user, request=self.request)
        return new_user

    def get_success_url(self, user=None):
        return super(RegistrationView, self).get_success_url()

1 个答案:

答案 0 :(得分:1)

您需要在表单元素中使用novalidate来关闭HTML本身的行为。

<form action="whatever" method="POST" novalidate>
    ...
</form>