Currently looking at: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/
I'开发者_Python百科m currently trying to create a simple product form, where the author/ user creating the product is added later. My code is as follows:
ProductFormSet = modelformset_factory(Product, exclude=('pub_date', 'author')) #handle categories separately/ via JSON feed
if request.method == 'POST':
formset = ProductFormSet(request.POST, request.FILES)
if formset.is_valid():
new = formset.save(commit=False)
new.author = request.user
new.save()
return HttpResponse("DONE!!")
However I get an attribute error as 'new' seems to be returned as an empty list rather than an instance of the new form object. Where am I going wrong??
Many thanks,
Adam
You seem to be confusing forms and formsets.
A form is for editing a single instance, and form.save()
(in the case of a model form) returns the saved instance.
A formset is for editing multiple instances. formset.save()
returns the list of instances that were saved. Obviously, the list itself doesn't have an author
attribute - it's each instance within that list that does. So you'd need to loop through the list and set author
on each item.
精彩评论