Django FormSet显示两个表单集

时间:2019-04-29 10:54:28

标签: django django-models

我尝试做一个表,当我在商店中单击时,向我显示数据,然后让我编辑。但是,当我尝试执行此操作时,请向我显示两个表单集,其中一个包含corect数据,而另一个则为空。

我尝试遵循https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/教程,但我不太了解。 Here is the image of the result

HTML:

{% extends 'layout.html'%}
    {# Load the tag library #}
    {% load bootstrap4 %}

    {# Load CSS and JavaScript #}
    {% bootstrap_css %}
    {% bootstrap_javascript jquery='full' %}

    {# Display django.contrib.messages as Bootstrap alerts #}
    {% bootstrap_messages %}

    {% block content%}
    <form action="/favorita/store/0/" method="POST" class="form">
      {% csrf_token %}
      {% bootstrap_formset formset %}
      {% buttons %}
        <button type="submit" class="btn btn-primary">
          Submit
        </button>
      {% endbuttons %}
    </form>
    {%endblock%}

查看:

def store(request, id):
StoreFormSet = modelformset_factory(Store, exclude=())
if request.method == 'POST':
    formset = StoreFormSet(request.POST, request.FILES)
    if formset.is_valid():
        formset.save()
        return render(request, 'stores/index.html', {'title': 'Favorita Stores'})
else:
    if id == 0:
        formset = formset_factory(StoreForm)
    else:
        stores_search = Store.objects.filter(id = id)
        formset = StoreFormSet(queryset=stores_search)
    return render(request, 'store/details.html', {'formset': formset})

型号:

class Store(models.Model):
city = models.ForeignKey(City, on_delete=models.CASCADE)
store_type = models.ForeignKey(StoreType, on_delete=models.CASCADE)
cluster = models.IntegerField(default=0)
location = models.CharField(max_length=200)

ModelForm:

class StoreForm(ModelForm):
class Meta:
    model = Store
    fields = ['city', 'store_type', 'cluster', 'location']

我只需要带有数据的那个。

1 个答案:

答案 0 :(得分:0)

您需要将extra设置为0,默认情况下django设置为1。

查看modelformset_factory定义:

modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None)

对于您的情况:

StoreFormSet = modelformset_factory(Store, exclude=(),extra=0)

有关额外格式文档的更多信息:https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#limiting-the-number-of-editable-objects

  

限制可编辑对象的数量

     

与常规表单集一样,您可以使用max_num和额外的参数   到modelformset_factory()以限制额外表格的数量   显示。

     

max_num不会阻止显示现有对象。

     

此外,extra = 0并不会阻止您创建新的模型实例   可以使用JavaScript添加其他表单,也可以发送其他POST   数据。表单集尚未提供“仅编辑”视图的功能   阻止创建新实例。

     

如果max_num的值大于现有相关数量   对象,最多可以将额外的空白表格添加到   表单集,只要表单总数不超过max_num:

为您编写一些重新编写的代码使其变得更简单:

def store(request, id):
    #define the modleformset
    StoreFormSet = modelformset_factory(Store, form= StoreForm, extra=0)

    #get the queryset
    stores_search = Store.objects.filter(id = id)

    #Simplify the form logic

    #create the formset
    formset = StoreFormSet(request.POST or None, request.FILES or None, queryset=stores_search)

    #validate the form
    if formset.is_valid():
        formset.save()
        return render(request, 'stores/index.html', {'title': 'Favorita Stores'})

    #if the form is not valid it will simply render the page with your formset again (and errors if the formset contains errors)
    return render(request, 'store/details.html', {'formset': formset})