【问题标题】:Set custom error messages in Django 3 ModelForm in default pop-out window在默认弹出窗口中设置 Django 3 ModelForm 中的自定义错误消息
【发布时间】:2020-02-17 12:30:09
【问题描述】:

我是 Django3 的新手,现在我的任务是在 ModelForm 的默认弹出窗口中创建自定义错误消息文本。 这个窗口: default pop-out window, when I press submit button

模型.py

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

Forms.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

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

【问题讨论】:

    标签: python django django-models django-forms django-messages


    【解决方案1】:

    这些消息是 HTML5 中元素的默认验证消息。您可以通过调用setCustomValidity 方法来覆盖它。

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

    【讨论】:

    • 太好了,当我以这种方式输入第 5 行时它起作用了:'oninvalid': 'this.setCustomValidity("Application field is required")' 谢谢!
    • 我可以为更多验证器而不是“必需”做这个吗?
    猜你喜欢
    • 1970-01-01
    • 2019-12-16
    • 2011-02-25
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 2013-07-14
    相关资源
    最近更新 更多