django - Django:如何使用“formfield_callback”在“modelform_factory”中指定“include_blank=False”?
问题描述
我正在使用该django.forms.modelform_factory()
功能。一些数据库字段是IntegerField
s with choices
,所以 Django 默认使用一个django.forms.TypedChoiceField
有空白选项的 a ("--------------")。我正在使用RadioSelect
小部件,所以有一个空白选择是多余的。如何摆脱空白选择?
(我正在回答我自己的问题,但当然,如果您有更好的答案,请随时分享!)
解决方案
modelform_factory
有一个 formfield_callback
kwarg,它“是一个可调用的,它接受一个模型字段并返回一个表单字段。”
例如:
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)
推荐阅读
- jquery - 使用 Jquery 无限加载
- reactjs - 如何在这个反应组件中居中 svg?
- azure - 如何正确设置 RDMS 外部数据源的防火墙规则
- reactjs - How to pass a function to child component as a prop?
- webots - Vehicle modelisation on WeBots
- azure - Azure IoT Hub:撤销设备会话
- postgresql - PostgreSQL 文本到 tsquery 使用管道运算符
- python - 找不到页面 404 没有博客与给定的查询匹配
- python - Python,创建时复制文件
- python - How to multiply dictionary keys?