什么是django formsets用于?

时间:2013-12-16 01:37:43

标签: python django web

我在django的文档中发现了一些奇怪的东西,叫做formset,see it here。我想知道如何使用它的formset是什么?

2 个答案:

答案 0 :(得分:0)

它曾用于例如一张记录表。这是一种创建数据网格功能的方法,Django可以完成所有繁重工作(所有记录的所有数据都在同一个POST中发回)。

答案 1 :(得分:0)

Formset是datagrid的一个例子 如果要在一个页面上使用多种形式的相同类型。您可以使用Formset 示例:

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ["username", "email"]

现在,如果您想在一个页面上多次使用UserForm,则需要使用Formset。

from django.forms.formsets import formset_factory
Uforms = formset_factory(UserForm, extra = 4)  #extra used to define how many empty forms will display

进入您的views.py

def submit(request):
    if request.POST:
        #code to manage post request
        # validation to formset you can follow django docs
    else:
        address_formSet = Uforms(instance=UserForm())
    # render response

模板代码

      {{ address_formset.as_table }}

您可以按照步骤django formset来学习。

示例代码

class Address(models.Model):
    city = models.CharField(max_length=48)
    zipcode = models.IntegerField(max_length=5)  

class Friend(models.Model):
    name = models.CharField(max_length=30)
    address = models.ForeignKey(Address)

forms.py

 
from django import forms
from .models import Address, Friend
from django.forms.models import inlineformset_factory

MAX_ADDRESS = 2   #updated
AddressFormSet = inlineformset_factory(Address, Friend, extra=MAX_ADDRESS)   #updated

class UserAddressForm(forms.ModelForm):
    class Meta:
        model = Address

view.py

from django.shortcuts import render_to_response
from .models import *
from .forms import UserSubmittedAddressForm, AddressFormSet

def submit(request):
    if request.POST:
        #Logic
    else:
        form = UserAddressForm()
        address_formSet = AddressFormSet(instance=Address())
    # render response

模板代码

      {{ form.as_table }}
      {{ address_formset.as_table }}