Formsets ******** .. highlight:: python Links ===== - `Django documentation, Formsets`_ Sample ====== - ``forms.py``: :: from django import forms from django.forms.formsets import formset_factory class AdminProductShopForm(forms.Form): sku = forms.CharField( widget=forms.TextInput(attrs={ 'readonly': 'readonly', 'size': 50, }) ) price = forms.DecimalField() sell_in_shop = forms.BooleanField() AdminProductShopFormSet = formset_factory(AdminProductShopForm, extra=0) Note: - In this example, we have requested that the form set doesn't display any ``extra`` forms i.e. 0. - We have made the ``sku`` field read only. - ``views.py``: :: def admin_shop_products_view(request, shop_slug): products = Product.objects.order_by('sku').values('sku') product_forms = AdminProductShopFormSet(initial=products) return render_to_response( 'shop/admin_shop_products.html', { 'formset': product_forms, }, context_instance=RequestContext(request) ) Note: - In this example, the result from the query set is converted to a list of dictionaries by the ``values`` method. This is used to initialise the form set. - The form is initialised with the ``initial`` parameter. - Template: :: {% if formset %} {{ formset.management_form }}
Product | Price | Sell in Shop |
---|---|---|
{{ form.sku.errors }}
{{ form.sku }}
|
{{ form.price.errors }}
{{ form.price }}
|
{{ form.sell_in_shop.errors }}
{{ form.sell_in_shop }}
|