删除时的 django-dynamic-formset 问题

django-dynamic-formset issue when delete

当我尝试删除一行时,表单集向我发送以下错误 [{}, {}, {}, {'id': ['This field is required']}]。 如果我更改 modelformset_factory 内的以下参数 can_delete=True,我可以删除对象,但即使在我按下删除按钮后,行仍然显示。 我试图在模板中添加 {% if form.instance.pk %}{{ form.DELETE }}{% endif %},它没有改变任何东西。

我正在使用 django 2.2 和 django-dynamic-formset, the country_fr/en come from modeltranslation

观看次数

@login_required
def view_countries(request):
    CountryFormSet = modelformset_factory(
        Country,
        fields=('country_fr', 'country_en'),
        formset=BaseCountryFormSet,
        can_delete=True)
    if request.method == 'POST':
        formset = CountryFormSet(request.POST)
        if formset.is_valid():
            formset.save()
    else:
        formset = CountryFormSet()
    context = {
        'formset': formset,
        'menu': 'cards',
        'menu_cards': 'countries',
        'model': _('countries'),
        'fields': [_('countries')+' [fr]', _('countries')+' [en]'],
    }
    return render(request, 'cards/index_formset.html', context)

Html

<form method="post" class="mt-2">
  {% csrf_token %}
  {{ formset.management_form }}

  {% for form in formset %}
  <div id="form" class="row_formset d-flex text-center mb-1">
    {% if form.instance.pk %}{{ form.DELETE }}{% endif %}
    {% for field in form.hidden_fields %}
    <div class="invisible">
      {{ field }}
    </div>
    {% endfor %}
    {% for field in form.visible_fields %}
    <div class="flex-fill field">
      {{ field }}
    </div>
    {% endfor %}
  </div>
  {% endfor %}

  <div class="d-flex mt-2 justify-content-center">
    <input type="submit" value="{% trans 'submit'|capfirst %}" class="btn btn-primary"/>
  </div>
</form>

表格

class BaseCountryFormSet(BaseModelFormSet):
    def clean(self):
        if any(self.errors):
            raise forms.ValidationError(
                _('Errors : ')+f'{self.errors}'+'.',
                code='unknow_error'
            )
        countries_fr = []
        countries_en = []
        duplicates = False
        for form in self.forms:
            if form.cleaned_data:
                country_fr = form.cleaned_data['country_fr']
                country_en = form.cleaned_data['country_en']

                # Check that no row have the same country_fr or country_en
                if country_fr and country_en:
                    if country_fr in countries_fr:
                        duplicates = True
                    countries_fr.append(country_fr)

                    if country_en in countries_en:
                        duplicates = True
                    countries_en.append(country_en)

                if duplicates:
                    raise forms.ValidationError(
                        _('Some entries are duplicated.'),
                        code='duplicate_row'
                    )

                # Check that all row have both country_fr and country_en
                if country_en and not country_fr:
                    raise forms.ValidationError(
                        _('Some french entries are missing.'),
                        code='missing_country_fr'
                    )
                elif country_fr and not country_en:
                    raise forms.ValidationError(
                        _('Some english entries are missing.'),
                        code='missing_country_en'
                    )

型号

class Country(models.Model):
    country = models.CharField(_('country'), max_length=100)
    slug = models.SlugField(editable=False, max_length=100)

    def save(self, *args, **kwargs):
        self.slug_fr = slugify(self.country_fr, allow_unicode=False)
        self.slug_en = slugify(self.country_en, allow_unicode=False)
        super().save(*args, **kwargs)

所以问题来自 bootstrap,表单集的每个表单的 d-flex 包含属性 !important 至极覆盖 django-dynamic- 的 display: none;表单集脚本。

我自己制作了 css class 来替换 d-flex。我保留了can_delete=True,显然有用;我删除了 {% if form.instance.pk %}{{ form.DELETE }}{% endif %}.