且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django ModelChoiceField 没有加号按钮

更新时间:2023-02-22 10:48:39

你需要在你的模型表单中设置一个 RelatedFieldWidgetWrapper 包装器:

You need to set a RelatedFieldWidgetWrapper wrapper in your model form:

RelatedFieldWidgetWrapper(在 django.contrib.admin.widgets 中找到)用于管理页面以包含外键的功能控件添加新的相关记录.(英文:将绿色的小加号放在控件的右侧.)

The RelatedFieldWidgetWrapper (found in django.contrib.admin.widgets) is used in the Admin pages to include the capability on a Foreign Key control to add a new related record. (In English: puts the little green plus sign to the right of the control.)

class MyCustomUserCreationForm(models.ModelForm)
    ...
    location = forms.ModelChoiceField(queryset=Location.objects.all())

    def __init__(self, *args, **kwargs):
        super(MyCustomUserCreationForm, self).__init__(*args, **kwargs)
        rel = ManyToOneRel(self.instance.location.model, 'id') 
        self.fields['location'].widget = RelatedFieldWidgetWrapper(self.fields['location'].widget, rel, self.admin_site)

我可能在示例代码中犯了一个错误,请查看这些帖子和示例:

I could make a mistake in the example code, so see these posts and examples: