0

I'm new in Django3 and now I got a task to create custom error-messages text in default pop-out window of ModelForm. This window: default pop-out window, when I press submit button

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

1 Answers1

0

Those messages are the default validation message of elements in HTML5. You may override it by calling the method setCustomValidity.

widgets = {
            'user_name': TextInput(
                attrs={
                    'placeholder': 'Введіть ім\'я'
                    'oninvalid'="setCustomValidity('Show a custom error message')"
                },
            ),
        }
art
  • 1,358
  • 1
  • 10
  • 24
  • Great, it worked when I typed line 5 in this way: `'oninvalid': 'this.setCustomValidity("Application field is required")'` Thank you! – Valter Artur Feb 17 '20 at 13:51
  • can i make this for more validators not for 'required' only? – Valter Artur Feb 17 '20 at 15:26
  • Unfortunately, this is not working in Django at least 4.x, because of autoescaping quotes in attrs value. Double quotes inside `setCustomValidity("Show a custom error message")` would been automatically converted to `&quote;` in rendered page. And I can't find way to resolve this issue by Django mechanisms. – Andrei Alekseev Aug 26 '23 at 12:29