Django 动态管理表单

问题描述 投票:0回答:1

在我的 Django 项目中,我有模型 Product 和 ClothingProduct。产品有一个称为类别的属性。 ClothingProduct 继承自 Product。当创建类别值 == 'Clothes' 的产品时,还应该创建 ClothingProduct 的实例,然后用户应该能够输入 ClothingProduct 的属性值(通过管理面板)。 我尝试了以下 save() 方法,但它不起作用。

    class Product(models.Model):
        name = models.CharField(max_length=100)
        category = models.ForeignKey(Category, on_delete=models.CASCADE)
   
        def save(self, *args, **kwargs):
            super().save(*args, **kwargs)
            if self.category.name == 'Clothes':
                clothingProd, created = ClothingProduct.objects.get_or_create(product=self)
                if created:
                    clothingProd.color = 'White'
                    clothingProd.save()


        def __str__(self):
            return self.name

    class ClothingProduct(Product):
        product = models.OneToOneField(Product, on_delete=models.CASCADE, related_name='clothing_product')
        color = models.CharField(max_length=10, help_text='eg. White')

#This is the admin.py content:
    @admin.register(Product)
    class ProductAdmin(admin.ModelAdmin):
        inlines = [ProductImageAdmin]
        fields = ('name', 'category')

        def get_form(self, request, obj=None, **kwargs):
            if obj and obj.category.name == 'Clothes':
                form = ClothingProductForm
            else:
                form = super().get_form(request, obj, **kwargs)
            return form

    class ClothingProductForm(forms.ModelForm):
        class Meta:
            model = ClothingProduct
            exclude = ['product']

    admin.site.register(ClothingProduct)
django database django-models django-admin
1个回答
0
投票

创建类别名称为 Clothes 的产品后,您应该使用 django 信号 创建 ClothingProduct

© www.soinside.com 2019 - 2024. All rights reserved.