我正在或多或少地测试Django Doc中的“写作验证器”。所以我写了我自己的验证器,它似乎可以工作。
例如: 当我创建一个重量更高的新动物时,我的表格没有保存,则为100。这就是我要测试的。
但是我不知道如何在模板中显示错误消息。
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 %}
所以我想我的模板中需要一个错误字段,而视图中可能需要一些错误上下文?
答案 0 :(得分:1)
就像@dirkgroten一样,它所需要的只是模板中的错误字段引用。 就我而言,我只是在表单中引用了它。
create_animal.html
<...>
{{form.errors}}
<...>