【问题标题】:How To Add MultipleChoiceField To Django Admin?如何将 MultipleChoiceField 添加到 Django Admin?
【发布时间】:2019-10-12 06:38:55
【问题描述】:

我的模型中有一个 CharField 字段。我想在 Django 管理站点中将其显示为 MultipleChoiceField 小部件。 models.py:

class Product(models.Model):
    ...
    categories = models.CharField()
    ...

我在 forms.py 中创建了一个自定义表单小部件:

from django import forms

CATEGORIES_LIST = [
    ('for_him', 'For Him'),
    ('for_her', 'For Her'),
    ('for_kids', 'For Kids'),
]

class Categories(forms.Form):
    categories = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=CATEGORIES_LIST,
    )

不太确定下一步该做什么。如何将此小部件与我的产品模型的 Django Admin 连接?提前感谢您的帮助!

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    您要做的并不是直接使用 CharField 并在其中放置多个选项,因此您必须首先找到一种方法来序列化数据并将其恢复到模型中,看看 here

    如果您使用的是 postgres 数据库,您可以这样做(感谢 postgres 数组字段,您没有序列化和恢复数据的麻烦)

    from django.contrib.postgres.fields import ArrayField
    class ChoiceArrayField(ArrayField):
        """
        A field that allows us to store an array of choices.
    
        Uses Django 1.9's postgres ArrayField
        and a MultipleChoiceField for its formfield.
    
        Usage:
    
            choices = ChoiceArrayField(models.CharField(max_length=..., choices=(...,)), default=[...])
        """
    
        def formfield(self, **kwargs):
            defaults = {
                'form_class': forms.MultipleChoiceField,
                'choices': self.base_field.choices,
            }
            defaults.update(kwargs)
            return super(ArrayField, self).formfield(**defaults)
    

    然后你可以在你的模型上使用 ChoiceArrayField

    更新:

    所以要在你的模型上使用它,你可以这样做:

    class Product(models.Model):
        categories = ChoiceArrayField(max_length=8, choices=CATEGORIES_LIST, default=['for_him', 'for_her'])
    

    【讨论】:

    • 谢谢!但是,能否请您向我展示如何在一个实时示例中使用 ArrayField,究竟应该将什么添加到我的 models.py 中?我有点失落。再次感谢您帮助我。
    • @Android_Minsky 编辑了答案并添加了示例
    猜你喜欢
    • 2011-03-28
    • 1970-01-01
    • 2018-10-13
    • 2018-03-05
    • 1970-01-01
    • 2014-06-17
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多