2011-10-23 55 views
0

我正在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之間的轉換有關。你能解釋一下嗎?

回答

2

出於某種原因,您已將呈現表單的視圖(包括添加選項)和處理提交的視圖分開。您不會在提交時添加選項,因此這些值當然不會有效。

你應該完全擺脫add_product_form視圖。您可以將form.fields['category'].choices...位移入add_product視圖,但更好的解決方案是使用專門設計用於從模型或查詢集中獲取選擇的表單字段 - 即ModelChoiceField

只需使用:

category = forms.ModelChoiceField(model=Category) 

在你的表單定義。

0

謝謝丹尼爾。我很久以前就開始學習Django,並且我有添加視圖來顯示錶單的趨勢,這是不必要的。所以是的,我擺脫了add_product_form並完全依靠add_product。至於現在的類別選擇領域中,編碼這樣的forms.py:

forms.py:

from django import forms 
from django.utils.translation import ugettext_lazy as _ 

from myapp.models import Category 

class AddProductForm(forms.Form): 
    category = forms.ModelChoiceField(label=_('Category'), queryset=Category.objects.all()) 
    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(request): 
    if request.method == 'POST': 
     form = AddProductForm(request.POST) 

     if form.is_valid(): 
     category = request.POST['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() 

     # redirect to 'ms-admin/category_id' (the category to which belongs the newly added product 
     return HttpResponseRedirect('/ms-admin/'+category) 
    else: 
     form = AddProductForm() 

    return render_to_response('product-form.html', {'form':form}) 

我希望這可以幫助初來乍到Django的。請隨意提及任何改善上述代碼的方法......

相關問題