如何在Django Form中的Meta类中传递变量作为参数?

时间:2016-09-30 07:10:36

标签: django django-forms

forms.py

class MySelect(forms.Select):
    def __init__(self, *args, **kwargs):
        self.variations = kwargs.pop('variations')
        super(MySelect, self).__init__(*args, **kwargs)

    def render_option(self, selected_choices, option_value, option_label):
        return '<option whatever>...</option>'

class CartItemForm(forms.ModelForm):

    class Meta:
        model = CartItem
        fields = (
            'variation',
            'width',
            'height',
            'quantity',
        )
        widgets = {
            'variation': MySelect(variations=self.variation_query)
        }

    def __init__(self, *args, **kwargs):
        product = kwargs.pop('product')
        try:
            cart = kwargs.pop('cart')
            self.cart = cart
        except:
            pass

        super().__init__(*args, **kwargs)    
        variation_field = self.fields['variation']
        variation_field.queryset = Variation.objects.filter(
            product=product
        )
        self.variation_query = Variation.objects.filter(
            product=product
        )

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

        return cart_item

以下是您必须注意的地方。 (在Meta类中)

widgets = {
    'variation': MySelect(variations=self.variation_query)
}

self.variation_query来自__init__

我该怎么做?

models.py

class CartItem(models.Model):
    cart = models.ForeignKey("Cart")
    variation = models.ForeignKey(Variation)
    # 벽화 너비
    width = models.PositiveIntegerField(
        default=1,
        validators=[MinValueValidator(1)],
    )


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)
    place_category = models.ForeignKey(
        "PlaceCategory",
        related_name="products_by_place",  # category.products_by_place.all()
    )
    subject_category_set = models.ManyToManyField(
        "SubjectCategory",
        related_name="products_by_subject",  # category.products_by_subject.all()
    )
        # 벽화 높이
        height = models.PositiveIntegerField(
            default=1,
            validators=[MinValueValidator(1)],
        )
        quantity = models.PositiveIntegerField(
            default=1,
            validators=[MinValueValidator(1)],
        )

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)

1 个答案:

答案 0 :(得分:0)

这不是你在Meta中会做的事情。你需要在__init__中完成整个事情。

事实上你已经这样做了,所以我根本不知道你为什么要覆盖Meta。