Django管理员有很多选择 [英] Django admin with many to many choices

查看:89
本文介绍了Django管理员有很多选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following models.py and admin.py files. The intention is to allow for selection of multiple categories for a given product if necessary.

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)

通过管理员访问 Products 对象时,结果如下:

This results in the following, when accessing a Products object through admin:

推荐答案

您是否需要像t一样显示他的?

Are you need to display like this?

我建议您使用 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,]

这篇关于Django管理员有很多选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆