首页 > 解决方案 > Django:如何使用“formfield_callback”在“modelform_factory”中指定“include_blank=False”?

问题描述

我正在使用该django.forms.modelform_factory()功能。一些数据库字段是IntegerFields with choices,所以 Django 默认使用一个django.forms.TypedChoiceField有空白选项的 a ("--------------")。我正在使用RadioSelect小部件,所以有一个空白选择是多余的。如何摆脱空白选择?

(我正在回答我自己的问题,但当然,如果您有更好的答案,请随时分享!)

标签: django

解决方案


modelform_factory 有一个 formfield_callbackkwarg,它“是一个可调用的,它接受一个模型字段并返回一个表单字段。”

例如:

from django.forms import modelform_factory
from yourapp.models import Person
import django  # only importing this for type hints

def formfield_callback(f, **kwargs):
    # type: (django.db.models.fields.Field, dict) -> django.forms.Field

    ## pick the field or fields you want to modify.
    ## This example uses the `name` of the field to decide
    if f.name == 'job':
        ## override the 'choices' attribute
        kwargs['choices'] = f.get_choices(include_blank=False)
        ## if you want to, you can override the 'widget' here also
        kwargs['widget'] = RadioSelect
    ## regardless of whether you changed anything, return the result of 
    ## the normal formfield function so everything still works
    return f.formfield(**kwargs)


modForm = modelform_factory(Person, fields=["job", "age"],
                formfield_callback=formfield_callback)

推荐阅读