Django表单从链接的ModelChoiceFields中选择字段

时间:2010-12-24 15:09:46

标签: python django django-forms

我正在为商店建立一个表单,允许客户从多个选项中选择价格。当前的Django模板看起来非常好并且运行良好。

<select>
    <option>{{ p.equipment_list.season_price.currency }} {{ p.equipment_list.season_price.daily }} per day.</option>
    <option>{{ p.equipment_list.season_price.currency }} {{ p.equipment_list.season_price.weekly }} per week.</option>
    <option>{{ p.equipment_list.season_price.currency }} {{ p.equipment_list.season_price.monthly }} per month.</option>
</select>

我有一个产品'p',它是名为Equipment List的一个组成部分。此列表具有不同的定价(season_price),具体取决于一年中的时间或通过销售报价。这允许最大程度的可定制性和任务分离。以下是模型:

class SeasonPrice(models.Model):
    name = models.CharField(_('Season Price'), max_length=300)
    slug = models.SlugField(max_length=150, unique=True)
    description = models.TextField(blank=True)

    currency = models.ForeignKey(Currency)
    daily = models.DecimalField(max_digits=10, decimal_places=2)
    weekly = models.DecimalField(max_digits=10, decimal_places=2)
    monthly = models.DecimalField(max_digits=10, decimal_places=2)
…

class EquipmentList(models.Model):
   ...
    name = models.CharField(_('Equipment List'), max_length=100)
    slug = models.SlugField(unique=True)
    description = models.TextField(blank=True)

    season_price = models.ForeignKey(SeasonPrice)
    ….

class Product(ImageModel):
     ...
    equipment_list = models.ForeignKey(EquipmentList, related_name='Equipment')

    name = models.CharField('Name', max_length=300)
    slug = models.SlugField(max_length=150, unique=True)
    description = models.TextField()
    is_active = models.BooleanField(default=True)
    quantity = models.IntegerField()

   …
    @models.permalink
    def get_absolute_url(self):
       return ('product_detail', (), {'product_slug': self.slug})

   ….

表单看起来像这样:

class ProductAddToCartForm(forms.Form):
    ...
    product_slug = forms.CharField(widget=forms.HiddenInput())
    price = forms.ModelChoiceField(EquipmentList)
    quantity = forms.IntegerField(widget=forms.TextInput(attrs={'size':'2', 'value':'1', 'class':'quantity'}), 
                                  error_messages={'invalid':'Please enter a valid quantity.'}, 
                                  min_value=1)
   ...

观点:

def show_product(request, product_slug, template_name="shop/product_detail.html"):

    p = get_object_or_404(Product, slug=product_slug)
    page_title = p.name


    # need to evaluate the HTTP method
    if request.method == 'POST':

        postdata = request.POST.copy()
        form = ProductAddToCartForm(request, postdata)

        if form.is_valid():
            cart.add_to_cart(request)
            url = urlresolvers.reverse('show_cart')
        return HttpResponseRedirect(url)
    else:

        form = ProductAddToCartForm(request=request, label_suffix=':')

    form.fields['product_slug'].widget.attrs['value'] = product_slug
    request.session.set_test_cookie()
    return render_to_response("shop/product_detail.html", locals(), context_instance=RequestContext(request))

我在ModelChoiceField中看到的所有示例都是一个深入的ForeignKey。从上面开始,我希望能够链接2到3个ForeignKeys,并输出一个数字字符串,与购物者想要的数量相乘,然后放入购物车。

由于

1 个答案:

答案 0 :(得分:0)

我认为ModelChoiceField不适合您展示的原始<select>。您正在选择货币/小数组合,而不是模型实例。或许,您希望构建一个临时的ChoiceField

myform.fields['price'].choices = (
    ('1::3.50', "EUR 3.50 per day"),
    # ...
)

其中1::3.50可以在clean / save中分割()以给出货币ID和金额字符串。这样的事情。