我正在Django中編寫一個簡單的表單,其中包含一個ChoiceField,允許用戶從類別列表中進行選擇。當然,我想通過category_id進行處理。這是我的代碼:Django ChoiceField或TypedChoiceField和ID的無效選擇
models.py:
class Category(models.Model):
category = models.CharField(max_length=128)
def __unicode__(self):
return self.category
class Product(models.Model):
code = models.CharField(max_length=75)
name = models.CharField(max_length=128)
price = models.DecimalField(max_digits=7, decimal_places=2)
category = models.ForeignKey(Category)
def __unicode__(self):
return self.name
forms.py
class AddProductForm(forms.Form):
category = forms.ChoiceField(label=_('Category'))
product = forms.CharField(label=_('Product'), widget=forms.TextInput())
code = forms.CharField(label=_('Code'), widget=forms.TextInput())
price = forms.DecimalField(label=_('Price'))
現在在views.py我填寫選擇:
def add_product_form(request):
form = AddProductForm()
form.fields['category'].choices =[(c.id, c.category) for c in Category.objects.all()]
return render_to_response('product-form.html', {'form':form})
現在除了我提交表格時,一切似乎都沒問題。它抱怨該類別的ID。它說: 選擇一個有效的選擇。 1是不是可用選項之一
這是怎麼了處理形式:
def add_product(request):
if request.method == 'POST':
form = AddProductForm(request.POST)
if form.is_valid():
category = request.cleaned_data['category']
product = form.cleaned_data['product']
code = form.cleaned_data['code']
price = form.cleaned_data['price']
product = Product(code=code, name=product, price=price, category_id=category)
product.save()
return HttpResponseRedirect('/ms-admin/')
else:
form = AddProductForm() # more is required here to fill the choices again
return render_to_response('product-form.html', {'form':form})
我試着用TypedChoiceField相同,但得到了同樣的無效數據。我知道它與字符串和int和unicode之間的轉換有關。你能解釋一下嗎?