UserCreationForm在字段为空时显示错误 [英] UserCreationForm show error when fields are empty
问题描述
我使用的是UserCreationForm中内置的Django。我想在该字段为空并且用户试图提交表单时在该字段下显示消息。不幸的是,我只能看到浏览器的内置行为,例如填写此字段,顺便说一下,在不同的浏览器中行为是不同的。一些浏览器只是用红线将字段框围起来。如何关闭此行为并在字段下显示消息。为什么.error_messages无法正常工作?我还在模板中使用{{form.field_name.errors}}。
I'm using Django built in UserCreationForm. I want to show message under the field when that field is empty and user tring to submit form. Unfortunatly I see only built-in behavior of browsers like "fill out this field", by the way in different browsers that behavior is different. Some browsers just encircle the field box with a red line. How to turn off this behavior and show message under the field. Why .error_messages didnt work?! Also I use {{ form.field_name.errors }} in my template.
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()
推荐答案
您需要通过在表单元素中使用 novalidate
关闭HTML本身的行为。
You need to turn off the behaviour in the HTML itself, by using novalidate
in the form element.
<form action="whatever" method="POST" novalidate>
...
</form>
这篇关于UserCreationForm在字段为空时显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!