1

I have created a form in Django which has a charfield with max_length=255 as follows:

task = models.CharField(max_length= 255)

Now I want to let the user know how many characters he has typed if he exceeds the 255 characters limit, so I did the following

if form.is_valid():
    #some code
else:
    messages.info(request,(form.errors.get("task").as_text()))

now suppose if I type 445 characters in the form field and submit then by default I am getting the following error message:

* Ensure this value has at most 255 characters (it has 445).

but instead, I want to change this message to:

Error: maximum length limit is 255 characters (it has 445).

So I tried the following:

class ListForm(ModelForm):
    class Meta:
        model = ListModel
        fields = ["task", "status"]

        error_messages = {
            'task': {
                'max_length': ("Error: maximum length limit is 255 characters"),
                
            },
        }

Now the message has been changed to:

* Error: maximum length limit is 255 characters.

My Problem:

  1. I don't want the * which is being displayed in front of the messages
  2. I was not able to capture the number of characters the user has typed, which was being displayed in the default message i.e. (it has 445)

What can I do to print Error: maximum length limit is 255 characters (it has 445). instead of * Error: maximum length limit is 255 characters.?

yogeshiitm
  • 179
  • 1
  • 17
  • I have used the [Django form class](https://docs.djangoproject.com/en/3.1/topics/forms/#building-a-form-in-django) to generate the form, so I've not defined any HTML exclusively for the form. – yogeshiitm Jan 09 '21 at 19:14
  • Sure, but the problem is how you are acessing the `messages.info` in your template. For me `messages.info` does not contain an asterisk if I access it without any HTML tags. The standard `django.forms.Form` class does not render any HTML for the `messages.info`, you have to access it by yourself. – Countour-Integral Jan 09 '21 at 19:34
  • Okay now I got your point, to access the message in HTML I am doing the following: `{% if messages %}{% for message in messages %}

    {{ message }}

    {% endfor %}{% endif %}`, so I don't think I am using any
  • class in my HTML
  • – yogeshiitm Jan 09 '21 at 19:45
  • Strange. Maybe you could try putting `messages.info(request, "some test string")` and tell us if there is still the same issue. You could also try `print(form.errors.get("task").as_text())` to see if there is an asterisk there or if it is an HTML issue. Also the parentheses is redundant – Countour-Integral Jan 09 '21 at 19:49
  • `messages.info(request, "string")` simply displays the string without any `*` but yeah the `* ` appears even on `print(form.errors.get("task").as_text())`. Actually if I do `print(form.errors.get("task"))` then it prints `
    • "some_string"
    ` so the
  • class is within the `form.errors`
  • – yogeshiitm Jan 09 '21 at 20:04