Django:从下拉列表中保存输入时,保存选项值而不是实际值

时间:2014-08-07 23:43:04

标签: python django django-forms django-templates

在我的问题前言我想说我对Django很新,所以要温柔。提前谢谢!

我有两个下拉框,All_team_Form和Product_Form(都是ModelChoiceField)。

class All_team_Form(forms.ModelForm):
   teams = forms.ModelChoiceField(queryset= All_teams.objects.all().order_by('team_name'))

   class Meta:
       model = All_teams
       fields = ('team_name', 'team_type')
       widgets = {'team_name': HiddenInput(),'team_type': HiddenInput()}


class Product_Form(forms.ModelForm):
   products = forms.ModelChoiceField(queryset= Product.objects.all().order_by('product'))

   class Meta:
       model = Product
       fields = ('product',)
       widgets = {'product': HiddenInput(),}

我保存POSTED输入的方式是:

if request.method == 'POST':
    pattern = request.POST.get('pattern')
    team = request.POST.get('teams')
    product = request.POST.get('products')
    pub_date = timezone.now()
    team_obj = Sys_team(pattern=pattern, sys_team=team, product=product, pub_date= pub_date, alert= "[CPU]")
    team_obj.save()


context = {

'all_form' : All_team_Form(),
'product_form' : Product_Form()

}

return render(request, 'test4.html', context)

模板:

<td>              
{% for a in all_form %}
   {{a}} 
{% endfor %}
</td>

我遇到的当前问题是,当它保存Sys_team对象时,它会得到我认为是all_form的默认选项值,即数字。当我在python shell中打印出all_form时,它会显示一个格式为的列表:<option value="4">thestuffIwant</option>

我读过的很多文档都说我应该包含<option value = {{ a }}>{{a}}</option>。但是,当我尝试它时,通过在其上方的下拉列表中添加所有选项的正常列表来混淆下拉列表。非常感谢帮助!

2 个答案:

答案 0 :(得分:0)

您必须先验证表单并使用form.cleaned_data而不是request.POST。

if request.method == 'POST':
    all_form = All_team_Form(request.POST)
    product_form = Product_Form(request.POST)
    if all_form.is_valid() and product_form.is_valid():
        pattern = request.POST.get('pattern')
        team = all_form.cleaned_data.get('teams')
        product = product_form.cleaned_data.get('products')
        pub_date = timezone.now()
        team_obj = Sys_team(pattern=pattern, sys_team=team, product=product, pub_date= pub_date, alert= "[CPU]")
        team_obj.save()
else:
    all_form = All_team_Form()
    product_form = Product_Form()

context = {

'all_form' : all_form,
'product_form' : product_form,

}

return render(request, 'test4.html', context)

答案 1 :(得分:0)

解决了我的问题。我刚给我的ModelForm查询集添加了一个额外的参数。

teams = forms.ModelChoiceField(queryset= All_teams.objects.all().order_by('team_name'), to_field_name="team_name")

我只使用表单来加载下拉列表,并决定不使用表单来保存数据,因为我没有将用户输入保存到表单。我有多个下拉列表(所有不同的表单)和其他用户输入,我想保存到我的一个模型。使用request.POST.get('xxxx')比声明每个相应的表单模型更容易,也可能更有效。