I’m trying to loop through form fields and store them in the database. The problem is that it’s always only the last field that gets stored. The previous ones are “skipped”. Can I process the forms in Django in the following way?
models.py:
class Category(models.Model):
name = models.CharField(max_length=30, unique=True)
user = models.ForeignKey(User, blank=True, null=True)
class Meta:
verbose_name_plural = "Ingredience Categories"
def __unicode__(self):
return self.name
forms.py
class CategoryForm(ModelForm):
class Meta:
model = Category
fields = ('name',)
home.html template (I’m buildin my form “manually” because I want to be able to dynamically add more input fields via jQuery):
<h3>Insert New Categories</h3>
<form action="/" method="post" id="ingr-cat-form">{% csrf_token %}
<p><label for="id_0-name">Name:</label> <input type="text" maxlength="30" name="name" id="id_0-name"></p>
<p><label for="id_1-name">Name:</label> <input type="text" maxlength="30" name="name" id="id_1-name"></p>
<p><label for="id_2-name">Name:</label> <input type="text" maxlength="30" name="name" id="id_2-name"></p>
<input type="submit" name="ingrCatForm" value="Save" />
</form>
views.py:
def home(request):
if request.method == 'POST':
catform = CategoryForm(request.POST, instance=Category()) # store bounded form to catform
catformInstance = catform.save(commit = False) # create instance for further modification, don't commit yet
catformNames = request.POST.getlist('name') # get a list of input values whose element name is "name"
for name in catformNames: # loop through all name elements
catformInstance.name = name # modify form instance; insert current name
catformInstance.save() # save the instance to the database
return HttpResponseRedirect('')
else:
catform = CategoryForm(instance=Category())
context = {'catform': catform}
return render_to_response('home.html', context, context_instance=RequestContext(request))
Test Case Steps:
- Insert the following values in the 3 input fields: value1, value2, value3
- Press the submit button
Expected Result:
- all 3 values are stored in the database
Actual Result:
- only the last value (value3) is stored in the database
You create only one instance of
catformInstance, then alter it’s value each time in the loop. You are updating one row in the database instead of creating a new row each time.Do this instead:
Note that we pass in each
nameexplicitly instead of the whole set ofPOSTvalues; in that case it’ll just grab the last name from thenamelist, then fail during the next iteration asnameis no longer available from the request.