How to pass variable as argument in Meta class in Django Form?

大城市里の小女人 提交于 2019-12-12 03:09:56

问题


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

Below is where you have to pay attention to. (in Meta class)

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

self.variation_query is from __init__.

How can I do this?

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:


That's not a thing you would do in Meta. You need to do the whole thing in __init__.

You're already doing that in fact, so I don't know why you want to override Meta at all.



来源:https://stackoverflow.com/questions/39785703/how-to-pass-variable-as-argument-in-meta-class-in-django-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!