Почему field.errors отображает повторяющиеся сообщения об ошибках из метода clean () в форме Django? - PullRequest
0 голосов
/ 14 марта 2020

Использую ли я clean() или clean_initial_ph(), я получаю повторяющиеся сообщения об ошибках.

enter image description here

Также, если я перебираю поля формы:

   {% for field in form %}
        {{ field|as_crispy_field }}
        {% if form.errors %}
            {% for error in field.errors %}
                <div class="alert alert-danger">
                    <strong>{{ error|escape }}</strong>
                </div>
                {% endfor %}
                {% endif%}          
        {% endfor %}  

или перечисляю поля и ошибки вручную:

...
            {{ form.initial_ph|as_crispy_field }}
            {{ form.initial_ph.errors }}
...

Я все еще получаю дубликаты сообщений об ошибках (хотя и другой стиль для более крупного).

enter image description here

Я выполнил проверку рекомендации . Например, в clean_initial_ph() моя проверка выглядит следующим образом:

    def clean_initial_ph(self):
        initial_ph = self.cleaned_data['initial_ph']
        if initial_ph:
            if initial_ph < 0:
                raise forms.ValidationError(_("PH must be above 0."), code = 'negative_intial_ph')
        return initial_ph

У меня есть другая проверка в некоторых временных полях в clean(), которая не отображает повторяющиеся сообщения об ошибках:

# Assuming clean_initial_ph is commented out
    def clean(self):
        cleaned_data = super().clean()
        pump_time = cleaned_data.get("pump_time")
        disposal_time = cleaned_data.get("disposal_time")
        incorptime = cleaned_data.get("incorptime")
        initial_ph = cleaned_data.get("initial_ph")
        disposal_ph = cleaned_data.get("disposal_ph")
        if pump_time and disposal_time: # DOES NOT DISPLAY DUPLICATE ERROR MESSAGES
            if pump_time >= disposal_time:
                self.add_error('pump_time','Pump time must be prior to disposal time.')
                self.add_error('disposal_time','Disposal time must be after to pump time.')
            if incorptime:
                if incorptime <= disposal_time:
                    self.add_error('incorptime','Incorp time must be after to disposal time.')
        if initial_ph: # DOES DISPLAY DUPLICATE ERROR MESSAGES
            if initial_ph < 0:
                self.add_error('initial_ph','PH must be above 0.')
        if disposal_ph: # DOES DISPLAY DUPLICATE ERROR MESSAGES
            if disposal_ph < 0:
                self.add_error('disposal_ph','PH must be above 0.')   

Что тут происходит? Любые идеи приветствуются - спасибо!

1 Ответ

0 голосов
/ 14 марта 2020

Вы должны проверить, есть ли в поле ошибки, а не форма.

{% for field in form %}
    {{ field|as_crispy_field }}
    {% if field.errors %} // not form
        {% for error in field.errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endif%}          
{% endfor %}
...