Is there a feature for data bound formset?
I have created an editable formset with mutltiple fields of the same type.
开发者_如何学PythonThe data can be edited and submitted.
Is there a way to bind this formset to the data so that updates happen automatically? or
Do I need to iterate over all the editable fields and update them individually?
I'm not 100% what you're asking, but is your data coming from a Model? If so, You can have formsets tied to ModelForms using model formsets
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets
So if you have a model:
class Product(models.Model):
field_1 = models.CharField(...)
field_2 ...
...
and a model form:
class ProductForm(forms.ModelForm):
field_1 = models.TextField(max_length=100)
field_2 ...
...
class Meta:
model = Product
You can create a formset from that model. Something along the lines of this:
in your views.py
ProductFormSet = modelformset_factory(ProductForm)
if request.method=="POST":
formset = ProductFormSet(request.POST)
if formset.is_valid():
formset.save()
...
else:
formset = ProductFormSet()
...
return direct_to_template(request,
template = "foo.html",
extra_context = { 'formset' : formset })
This is useful as the models will automatically get updated when the formset is POST'ed and validated. It also knows when a particular instance has been edited in the formset, so you can do further logic.
精彩评论