Django管理员有很多选择

时间:2017-07-23 12:25:44

标签: django django-models django-admin

我有以下models.pyadmin.py个文件。目的是允许在必要时为给定产品选择多个类别。

models.py

class Product(models.Model):
    organization = models.ForeignKey(Organization)
    name = models.CharField(max_length=50)
    brief = models.CharField(max_length=100)
    descrip = models.TextField(max_length=1300)
    categories = models.ManyToManyField('Product_Category')

class Product_Category(models.Model):
    cats = {"AUT":"Automation", "PWA":"Personal Wealth Advisory", 
            "BCH":"Blockchain", "LOS":"Loan Origination", "FX":"Foreign Exchange"}
    choices = tuple((human, c) for human, c in cats.items())
    name = models.CharField(max_length=32, choices=choices)

admin.py

 from .models import Product, Product_Feature, Organization, Product_Category

class PFeatureInLine(admin.StackedInline):
    model = Product_Feature
    extra = 1

class ProductForm(forms.ModelForm):
    logo_file = forms.ImageField()

    def save(self, commit=True):
        logo_file = self.cleaned_data.get("logo_file", None)
        self.instance.logo = b64encode(logo_file.read()).decode("utf-8")
        return forms.BaseModelForm.save(self, commit=commit)

    class Meta():
        exclude = ["logo"]
        model = Product

class ProductAdmin(admin.ModelAdmin):
    form = ProductForm
    inlines = [PFeatureInLine,]

admin.site.register(Product, ProductAdmin)
admin.site.register(Organization)

当通过admin访问Products对象时,会产生以下结果:

enter image description here

1 个答案:

答案 0 :(得分:3)

你需要这样显示吗?

我建议你使用FilteredSelectMultiple

from django import forms
from django.contrib import admin
from django.contrib.admin.widgets import FilteredSelectMultiple

from .models import Product, Product_Feature, Organization, Product_Category


class ProductForm(forms.ModelForm):
    logo_file = forms.ImageField()

    categories = forms.ModelMultipleChoiceField(
          queryset=Product_Category.objects.all(),
          required=False,
          widget=FilteredSelectMultiple(
              verbose_name=_('Categories'),
              is_stacked=False
          )
    )

    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)

        if self.instance and self.instance.pk:
            self.fields['categories'].initial = self.instance.categories.all()

    def save(self, commit=True):
        logo_file = self.cleaned_data.get("logo_file", None)
        self.instance.logo = b64encode(logo_file.read()).decode("utf-8")
        return forms.BaseModelForm.save(self, commit=commit)

    class Meta:
        exclude = ['logo']
        model = Product


class ProductAdmin(admin.ModelAdmin):
    form = ProductForm
    inlines = [PFeatureInLine,]