0

When I use form.is_valid() Django automatically outputs the validation error message shown in the link below (circled in red). But what if I want to customize that message with custom logic but display it in the same way. How do I do that?

The page linked below allows you to register a phone number to a database. I want to add an unsubscribe page where the database is queried and if the phone number exists then delete the number. But if it doesn't exist in database, I want to display the message "Phone number is not currently registered."

https://i.stack.imgur.com/47O9G.jpg (sorry for external link, can't embed images yet)

models.py

class PhoneNumber(models.Model):
    country = models.CharField(max_length = 1)
    area = models.CharField(max_length = 3)
    phone_number = models.CharField(max_length = 7)
    reg_date = models.DateTimeField(default=timezone.now)

    class Meta:
        unique_together = ('country', 'area', 'phone_number')

    def add_to_database(self):
        self.save()

    def __str__(self):
        return str(self.country) + str(self.area) + str(self.phone_number)
Community
  • 1
  • 1
  • Take a look to this answer: https://stackoverflow.com/questions/54491682/check-for-erros-and-other-values-at-the-widget-level-maybe-using-custom-form-f – Raydel Miranda Feb 07 '19 at 04:17

1 Answers1

0

You can access individually to field errors, this is an example:

<form action="." method="get">
    {% csrf_token %}
    <p>{{ form.username.label }}: {{ form.username }}</p>
    <p>{{ form.password.label }}: {{ form.password}}</p>

    <ul>
        {% for error in form.password.errors %}
            <li>{{ error }}</li>    
        {% endfor %}
    </ul>

   <button type="submit">submit</button>
</form>

This code displays the errors related to the password field as an unordered list. You can make a table, some divs, you name it ...

Look this answer for more detail: Check for erros and other values at the widget level - maybe using custom form field

Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60