python - Django 管理员自定义选择表单字段选择

标签 python django django-admin

在 django 管理中,如果数据库中的字段为 None 或有值,我试图创建自定义选择,但我无法使其工作,我只能获取整个查询集,但无法获取数据的 id这样我就可以过滤请求。

有什么建议吗?

def formfield_for_choice_field(self, db_field, request, **kwargs):
        ordered = False
        qs = self.get_queryset(request)
        for query in qs:
            if query:
                if query.order:
                    ordered = True
        if db_field.name == "status":
            if ordered:
                kwargs['choices'] = (
                    ('Ordered', 'Ordered'),
                    ('Shipped', 'Shipped'),
                    ('Delivered', 'Delivered'),
                    ('Late', 'Late'),
                    ('Never Arrived', 'Never Arrived'),
                )
            else:
                kwargs['choices'] = (
                    ('Shipped', 'Shipped'),
                    ('Delivered', 'Delivered'),
                    ('Late', 'Late'),
                    ('Never Arrived', 'Never Arrived'),
                )
        return super(xxxxxx, self).formfield_for_choice_field(
            db_field, request, **kwargs)

最佳答案

由于在调用此函数时,已经检索了模型实例,因此您只需 Hook 该检索并使模型实例在当前请求上下文中可用,以便您可以在有请求的任何地方轻松使用它:

def get_object(self, *args, **kwargs):
    request._admin_obj = super(xxxxxx, self).get_object(*args, **kwargs)
    return request._admin_obj

def formfield_for_choice_field(self, db_field, request, **kwargs):
    if db_field.name == "status":
        obj = request._admin_obj
        if obj and obj.order:
            kwargs['choices'] =  # ordered_choices
        else:
            kwargs['choices'] =  # unordered_choices
    return super(xxxxxx, self).formfield_for_choice_field(
        db_field, request, **kwargs)

另一种方法是在管理员中使用自定义 ModelForm 并覆盖其 __init__ 来修改基于 self.instance 的字段选择。

关于python - Django 管理员自定义选择表单字段选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56680592/

相关文章:

django-models - Django : error with "username" in my custom user model - 'UserProfile' object has no attribute 'username'

python - chart.render_to_file ('python_repos.svg' )AttributeError : 'NoneType' object has no attribute 'decode'

django - 如何更改 Django 网站中特定页面的语言

python - Python批量查询结果分组

python - Django 分页 |获取页面索引中分页项目的当前索引(不是页面索引范围本身)

Django 身份验证 : Where to put custom templates?

python - 将数据发布到 django 管理表单

python - python中的N维数组

python - 没有分隔符时以某种方式分割行的问题

python - 从元组列表创建 pandas 日期时间索引