简体   繁体   English

在默认弹出窗口中的 Django 3 ModelForm 中设置自定义错误消息

[英]Set custom error messages in Django 3 ModelForm in default pop-out window

I'm new in Django3 and now I got a task to create custom error-messages text in default pop-out window of ModelForm.我是 Django3 的新手,现在我的任务是在 ModelForm 的默认弹出窗口中创建自定义错误消息文本。 This window: default pop-out window, when I press submit button此窗口:默认弹出窗口,当我按下提交按钮时

Models.py模型.py

class Application_form_model(models.Model):
user_name = models.CharField(
    max_length=30,
    null=True
)

Forms.py表单.py

class ApplicationForm(forms.ModelForm):
    class Meta:
        model = Application_form_model
        fields = (
            'user_name',
        )
        widgets = {
            'user_name': TextInput(
                attrs={
                    'placeholder': 'Введіть ім\'я'
                },
            ),
        }
        error_messages = {
            'user_name': {
                'required': _("Custom error message."),
            },
    }

views.py视图.py

def app_form(request):
    formset = ApplicationForm(request.POST)
    if formset.is_valid():
        save_data = Application_form_model(
            user_name=formset.cleaned_data['user_name'],
        )
        save_data.save()
        return HttpResponseRedirect('')
    return render(
        request,
        'application_form/application_form.html',
        {
            'formset': formset
        }
    )

Those messages are the default validation message of elements in HTML5.这些消息是 HTML5 中元素的默认验证消息。 You may override it by calling the method setCustomValidity .您可以通过调用方法setCustomValidity来覆盖它。

widgets = {
            'user_name': TextInput(
                attrs={
                    'placeholder': 'Введіть ім\'я'
                    'oninvalid'="setCustomValidity('Show a custom error message')"
                },
            ),
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM