Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override ArrayField default error messages in template?

I am trying to change the default error message Django generates for ArrayField (Specifically too many items entered error message)

If a user enters too many items to my ArrayField the following message generates in the template:

List contains 4 items, it should contain no more than 3.

I want to change this message to

You can't have more than 3 topics.

I have tried adding the following error_messages to my forms.py TopicForm Meta class but had no success

    error_messages = {
        'topic': {
            'invalid': ("You can't have more than 3 topics."),
        },

Here is my models.py file

from django.contrib.postgres.fields import ArrayField
from django.db import models

class Topic(models.Model)
    topic = ArrayField(models.CharField(max_length=20), size=3, blank=True,    null=True)

and my forms.py

from django import forms
from .models import Topic

class TopicForm(forms.ModelForm):
    class Meta:
        model = Topic

        fields = ['topic']

Would apperciate some input on this! Thank you!

like image 530
Lance Avatar asked Nov 06 '22 18:11

Lance


1 Answers

ArrayField has multiple error 'codes' to deal with various types of user inputs.

The error 'code' for an array which is overpopulated with elements is max_length.

Here is the rewritten code with the piece you were missing :)

error_messages = {
    'topic': {
        'max_length': ("You can't have more than 3 topics."),
     },

By the way you may also want to customize your item_invalid error message for when users try to submit incomplete inputs.

For example an attempt to submit string1,string2, (See the extra comma?) will raise:

Item 3 in the array did not validate

You can customize the item_invalid message by adding:

error_messages = {
        'topic': {
            'max_length': ("You can't have more than 3 topics."),
            'item_invalid': ("Your customized message"),
         },
like image 182
danny bee Avatar answered Nov 14 '22 21:11

danny bee