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!
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"),
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With