Django Form:使用ForeignKey的表单

时间:2016-09-25 05:34:41

标签: django django-forms

我使用Django(1.9.7)框架制作网上商城。

我认为显示代码比在文本中解释容易得多。

models.py

class Product(TimeStampedModel):
    name = models.CharField(max_length=120, unique=True)
    slug = models.SlugField(null=True, blank=True)
    description = models.TextField(max_length=400, blank=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.name



class Variation(TimeStampedModel):
    COLOR_CHOICES = (
        ('black', '흑백'),
        ('single', '단색'),
        ('multi', '컬러'),
    )
    price = models.DecimalField(
        decimal_places=0,
        max_digits=15,
        blank=True,
        null=True,
    )
    product = models.ForeignKey(Product)
    color = models.CharField(
        max_length=10,
        choices=COLOR_CHOICES,
    )
    is_active = models.BooleanField(default=True)

    class Meta:
        unique_together = (('product', 'color'))

    def __str__(self):
        return str(self.product) + ' - ' + self.get_color_display()

我在product_detail视图中创建表单,并将其作为上下文数据传递给template

views.py

class ProductDetailView(DetailView):
    model = Product
    context_object_name = "product"

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)

        product = self.get_object()
        context['cartitem_form'] = CartItemForm(product)

        return context

我想通过表格做什么:

  
    

我想展示variations仅与给定的product相关联。因此,我在product中将form作为view的参数传递并保存此product。我尝试将variation查询集设置为ModelChoiceField

  
class CartItemForm(forms.ModelForm):
    variation = forms.ModelChoiceField(
        queryset=Variation.objects.filter(product=self.product)
    )

    class Meta:
        model = CartItem
        fields = (
            'variation',
            'width',
            'height',
            'quantity',
        )

    def __init__(self, *args, **kwargs):
        self.product = kwargs.pop('product')
        super().__init__(*args, **kwargs)

    def save(self):
        cart_item = super().save(commit=False)
        cart_item.save()

        return cart_item

但它不起作用。我该如何实现呢?

0 个答案:

没有答案