Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除时django动态表单集问题_Python_Django_Formset - Fatal编程技术网

Python 删除时django动态表单集问题

Python 删除时django动态表单集问题,python,django,formset,Python,Django,Formset,当我试图删除一行时,表单集向我发送以下错误[{},{},{},{id':['此字段是必需的']}]。 如果我在modelformset_工厂内更改以下参数can_delete=True,我可以删除对象,但即使在按下“删除”按钮后,行仍保持显示。 我试图在模板中添加{%if-form.instance.pk%}{{form.DELETE}{%endif%},但没有改变任何内容 我使用的是django 2.2,它来自哪个国家 视图 @login_required def view_countries

当我试图删除一行时,表单集向我发送以下错误
[{},{},{},{id':['此字段是必需的']}]
。 如果我在modelformset_工厂内更改以下参数
can_delete=True
,我可以删除对象,但即使在按下“删除”按钮后,行仍保持显示。 我试图在模板中添加
{%if-form.instance.pk%}{{form.DELETE}{%endif%}
,但没有改变任何内容

我使用的是django 2.2,它来自哪个国家

视图

@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)
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)
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>
型号

@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)
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)

所以问题来自引导,表单集的每个表单的
d-flex
都包含属性
!重要提示
wich覆盖
显示:无


我创建了自己的css类来替换
d-flex
。我保留了
can_delete=True
,它显然很有用;我删除了
{%if-form.instance.pk%}{form.DELETE}{%endif%}

所以问题来自引导,表单集的每个表单的
d-flex
都包含属性
!重要提示
wich覆盖
显示:无

我创建了自己的css类来替换
d-flex
。我保留了
can_delete=True
,它显然很有用;我删除了
{%if-form.instance.pk%}{{form.DELETE}{%endif%}