![](/img/trans.png)
[英]Is it possible to get the value from an option in the drop down list in 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.