繁体   English   中英

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

[英]Django: When saving input from drop down lists, saves option value instead of actual value

提出我的问题,我想说我对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> 但是,当我尝试通过在其上方的下拉列表中添加所有选项的常规列表来弄乱下拉列表时。 非常感谢您的帮助!

您必须先验证表单,然后使用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)

解决了我的问题。 我刚刚在ModelForm查询集中添加了一个附加参数。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM