如何循环访问表单域并将其全部存储在数据库中? [英] How to loop through form fields and store them all in the database?

查看:129
本文介绍了如何循环访问表单域并将其全部存储在数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图循环访问表单域并将其存储在数据库中。问题是它总是只存储最后一个字段。以前的跳过。我可以通过以下方式处理Django中的表单吗?



models.py:




name = models.CharField(max_length = 30,unique = True)
user = models.ForeignKey(User,

class Meta:
verbose_name_plural =成分类别

def __unicode __(self):
return self。名字

forms.py



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b b b b b b b b b b b b b b b b b b b b b b b b b b

home.html模板(我手动填入我的表单,因为我想能够通过jQuery动态添加更多输入字段):

 < h3>插入新类别< / h3> 
< form action =/method =postid =ingr-cat-form> {%csrf_token%}
< p>< label for =id_0-name >名称:其中/标签> < input type =textmaxlength =30name =nameid =id_0-name>< / p>
< p>< label for =id_1-name>名称:< / label> < input type =textmaxlength =30name =nameid =id_1-name>< / p>
< p>< label for =id_2-name>名称:< / label> < input type =textmaxlength =30name =nameid =id_2-name>< / p>
< input type =submitname =ingrCatFormvalue =保存/>
< / form>

views.py:

  def home(request):
如果request.method =='POST':
catform = CategoryForm(request.POST,instance = Category ))存储有限形式到catform
catformInstance = catform.save(commit = False)#create instance进一步修改,不要提交
catformNames = request.POST.getlist('name') #获取一个输入值的列表,其名称为name
,用于catformNames中的名称:#loop通过所有名称元素
catformInstance.name = name#modify form instance;插入当前名称
catformInstance.save()#将实例保存到数据库
return HttpResponseRedirect('')
else:
catform = CategoryForm(instance = Category())

context = {'catform':catform}
return render_to_response('home.html',context,context_instance = RequestContext(request))
/ pre>

测试用例步骤


  1. 在3个输入字段中插入以下值:value1,value2,value3

  2. 按提交按钮

预期结果




  • 所有3个值都存储在数据库中



实际结果




  • 只有最后一个值(value3)存储在数据库中


解决方案

code> catformInstance ,然后改变它'每次在循环中的值。您正在更新数据库中的一行,而不是每次创建一个新行。



这样做:

在request.POST.getlist('name')中的名称:
catform = CategoryForm({'name':name},instance = Category())
catform.save()

请注意,我们传递每个名称明确而不是整套 POST 值;在这种情况下,它将从名称列表中获取姓氏,然后在下一次迭代中失败,因为 name 请求中不再可用。


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:

  1. Insert the following values in the 3 input fields: value1, value2, value3
  2. 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:

    for name in request.POST.getlist('name'):
        catform = CategoryForm({'name': name}, instance=Category())
        catform.save()

Note that we pass in each name explicitly instead of the whole set of POST values; in that case it'll just grab the last name from the name list, then fail during the next iteration as name is no longer available from the request.

这篇关于如何循环访问表单域并将其全部存储在数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆