0

i am testing "Writing validators" from the Django Doc more or less. So i wrote my own validator and it seems to work.

For Example: When i create a new animal with a higher weight then 100 my form did not save. That is what i wanted to test.

But i don´t know how to display the error message in my template.

models.py

<...>

class Animal(models.Model):
    name = models.CharField(max_length=40)
    weight = models.DecimalField(max_digits=5, decimal_places=2)
    species = models.ForeignKey('Species', on_delete=models.CASCADE)
    farmer = models.ForeignKey('Farmer', related_name='farmername', on_delete=models.CASCADE)

    objects = AnimalManager() # --- link to Manager

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("datainput:animal_detail", kwargs={"id": self.id})

forms.py

<...>

from .validator import validate_gtr

<...>

class AnimalForm(forms.ModelForm):
    weight = forms.DecimalField(validators=[validate_gtr])

    class Meta:
        model = Animal
        fields = [
            'name',
            'weight',
            'species',
            'farmer',    
        ]

validator.py

from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _



def validate_gtr(value):
    if value > 100:
        raise ValidationError(
            _('(value) Kg. Animal is too heavy'),
            params={'value': value},
        )

views.py

 class AnimalCreateView(CreateView):
        template_name ="datainput/create_animal.html"
        form_class = AnimalForm
        queryset = Animal.objects.all()

create_animal.html

{% extends 'base.html' %}

{% load static %}

{% block custom_css %}
<link rel="stylesheet" type="text/css" href="{% static 'css/home_styles.css' %}">
{% endblock %}


    {% block content %}

<div class="container-fluid">

    <!-- Row -->
    <div class="row">
        <div class="col-6 offset-md-3">

                <h1>Please insert a new animal</h1>

                {% load widget_tweaks %}

                <form method="post">
                    {% csrf_token %}

                    {% for hidden in form.hidden_fields %}
                    {{ hidden }}
                    {% endfor %}

                    <div class="form-group">
                        <label for="{{ form.name.label }}"> {{ form.name.label }} </label>
                        {% render_field form.name placeholder=form.name.help_text class+="form-control" %}
                    </div>
                    <div class="form-group">
                        <label for="{{ form.weight.label }}"> {{ form.weight.label }} </label>
                        {% render_field form.weight placeholder=form.weight.help_text class+="form-control" %}
                    </div>
                    <div class="form-group">
                        <label for="{{ form.species.label }}"> {{ form.species.label }} </label>
                        {% render_field form.species placeholder=form.species.help_text class+="form-control" %}
                    </div>
                    <div class="form-group">
                        <label for="{{ form.farmer.label }}"> {{ form.farmer.label }} </label>
                        {% render_field form.farmer placeholder=form.farmer.help_text class+="form-control" %}
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-success">
                            <span class="glyphicon glyphicon-ok"></span> Save
                        </button>
                        <a href="{% url 'home' %}" class="btn btn-default">Cancel</a>
                    </div>
                </form>

        </div>
    </div>
        <!-- Row End --> 
</div>
<!-- Container End -->



{% endblock %}

So i guess i need a Error field in my Template and maybe some Error Context in my View?

2
  • 2
    {{form.farmer.errors}} will print errors associated with that field, or be empty if there aren't any. Note it will format itself as a <ul> with <li> items. If that's not what you want, loop through the errors. Commented Aug 15, 2019 at 18:25
  • @dirkgroten {{form.errors}}worked in the Template. Thanks Commented Aug 15, 2019 at 20:55

1 Answer 1

1

Like @dirkgroten mentioned, all it needs is a error field reference in the template. In my case i simply referenced it in my form.

create_animal.html

<...>
  {{form.errors}}
<...>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.