使用自定义字段更改管理表单字段

时间:2020-07-14 01:23:55

标签: python django

我有一个Category模型

class Category(models.Model):
    name = models.CharField(max_length=120,default='', verbose_name=_('name'))
    color = ColorField(default='#FF0000')

和一个Product模型

class Product(models.Model):
     name = models.CharField(max_length=120)
     category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None)
     ...

在“产品管理”页面中,我要使类别下拉列表显示带有类别颜色的名称。 在以下问题的帮助下:Django form field choices, adding an attribute

我设法在管理页面上创建一个彩色类别字段: enter image description here

这是代码(添加到product / admin.py中):

class SelectWOA(Select):
    def create_option(self, name, value, label, selected, index, 
                      subindex=None, attrs=None):
        option_dict = super(SelectWOA, self).create_option(name, value, 
            label, selected, index, subindex=subindex, attrs=attrs)
            #Category.objects.
        try:
            option_dict['attrs']['style'] =  'color: ' +  Category.objects.get(name=label).color + ';' 
        except:
            pass
            
        return option_dict

from django.forms import ChoiceField, ModelChoiceField
from category.models import Category
class ProductAdminForm(ModelForm):
    test_field = ModelChoiceField(queryset=Category.objects.all(), widget=SelectWOA())
    class Meta:
        model = Product
        exclude = ['category']
        fields = ('name', 'image', 'image2', 'category', 'test_field',)





from django.db import models
class ProductCastumAdmin(admin.ModelAdmin):
    form = ProductAdminForm

,但是test_field不知道我要它“连接”到category字段并替换它。 因此,当我保存表单时,我放入test field中的数据不会保存为类别。 我的问题是排除类别字段后,如何用test field替换它,以便它可以像分类字段一样保存数据?

1 个答案:

答案 0 :(得分:0)

因此,在@Blackdoor的大力帮助下,这是我的解决方案: 谢谢!

# select that change the color of the option based on the category of the product
class SelectWOA(Select):
    def create_option(self, name, value, label, selected, index, 
                      subindex=None, attrs=None):
        option_dict = super(SelectWOA, self).create_option(name, value, 
            label, selected, index, subindex=subindex, attrs=attrs)
            #Category.objects.
        try:
            option_dict['attrs']['style'] =  'color: ' +  Category.objects.get(name=label).color + ';' 
        except:
            pass
            
        return option_dict

from django.forms import ChoiceField, ModelChoiceField
from category.models import Category

class ProductAdminForm(ModelForm):
    category = ModelChoiceField(queryset=Category.objects.all(), widget=SelectWOA())
    class Meta:
        model = Product
        fields = ('name', 'image', 'image2', 'category',)


from django.db import models
class ProductCastumAdmin(admin.ModelAdmin):
    form = ProductAdminForm
    formfield_overrides = {
        models.ForeignKey: {'widget': SelectWOA},
    }
    fields = ( 'name', 'image', 'image2', 'category')