Как или где обрабатывать ошибки проверки формы для уникального ограничения в наборе форм modelformset_factory - PullRequest
0 голосов
/ 06 марта 2020

Я использую modelformset_factory форму набора, и я не уверен, где и / или как обрабатывать уникальные ошибки ограничения, чтобы я мог изящно отобразить их в своем шаблоне html вместо того, чтобы просто вывести приложение из строя. Кажется, что когда вы создаете набор форм в forms.py , вы не можете создать функцию внизу и начать пытаться очистить данные и / или вызвать ошибки проверки формы. Набор форм отлично работает при добавлении новых данных, но на данный момент я не уверен, как обрабатывать уникальные ошибки ограничения.

Модель

class Disciplines(models.Model):
    class Meta:
        unique_together = (('account','discipline'),)
        verbose_name_plural = ('Disciplines')
    account = models.ForeignKey(Account, on_delete=models.CASCADE)
    discipline = models.CharField(max_length=40,choices=Discipline_Choices)
    rank = models.CharField(max_length=41, choices=Rank_Choices)
    conferred_date = models.DateField(blank=True, null=True)
    expires_date = models.DateField(blank=True, null=True)

    def __str__(self):
        return self.account.first_name + ' ' + self.account.last_name + ' ' + self.discipline + ' ' + self.rank

    def has_module_perms(self, app_label):
        return True

Форма

from django.forms.models import modelformset_factory
from account.models import Disciplines

DisciplineFormSet = modelformset_factory(Disciplines, fields=('id','discipline','rank'), can_delete=True)

Вид

def discipline_update_view(request):
    if not request.user.is_authenticated:
        return redirect('login')

    user = request.user
    account_id = user.id

    if request.POST:

        Disc_Update_Form = DisciplineFormSet(request.POST)
        # import pdb; pdb.set_trace()
        if Disc_Update_Form.is_valid():

            for form in Disc_Update_Form:
                instance = form.save(commit=False)
                if not instance.discipline:
                    continue
                instance.account_id = account_id
                instance.save()
            return redirect('account')
    else:
        Disc_Update_Form = DisciplineFormSet(queryset=Disciplines.objects.filter(account_id=account_id).order_by('rank'))
    return render(request, 'account/discipline_update.html', {'Disc_Update_Form': Disc_Update_Form})

Шаблон html

{% extends 'base.html' %}
{% block content %}
<h2>Edit Discipline Info</h2>
<form method="post">
  {% csrf_token %}

      <table>
        <tr>
          <th>Discipline</th>
          <th>Rank</th>
        </tr>
        {% for field in Disc_Update_Form %}
        <tr>
          <td>{{field.id}}{{field.discipline}}</td>
          <td>{{field.rank}}</td>
          {% if field.help_text %}
            <small style='color: grey;'>{{field.help_text}}</small>
          {% endif %}

          {% for error in field.errors %}
            <p style='color: red;'>{{error}}</p>
          {% endfor %}
        </tr>
        {% endfor %}
      </table>

      {% if field.help_text %}
        <small style='color: grey;'>{{field.help_text}}</small>
      {% endif %}

      {% for error in field.errors %}
        <p style='color: red;'>{{error}}</p>
      {% endfor %}

      {% if Disc_Update_Form.errors %}
        <div style="color: red">
          <p>{{Disc_Update_Form.errors}}</p>
        </div>
      {% endif %}

      {% if Disc_Update_Form.non_form_errors %}
        <div style="color: red">
          <p>{{Disc_Update_Form.non_form_errors}}</p>
        </div>
      {% endif %}

      {% if Disc_Update_Form.non_field_errors %}
        <div style="color: red;">
          <p>{{Disc_Update_Form.non_field_errors}}</p>
        </div>
      {% endif %}
      {{ Disc_Update_Form.management_form }}
  <button type="submit">Save Changes</button>&nbsp&nbsp<button action="{% url 'account' %}">Cancel</button>
</form>
{% endblock content %}
...