Django ModelChoiceField 没有加号按钮 [英] Django ModelChoiceField has no plus button
问题描述
我正在为自定义用户制作一个 Django 应用程序.我在下面概述了我的问题的关键组成部分,缺少的代码用..."表示.我的自定义用户模型具有如下外键关系:
I'm making a Django app with custom users. I've outlined the key components of my problem below, missing code is denoted by '...'. My custom user model has a foreign key relationship as follows:
class MyCustomUser(models.AbstractBaseUser, models.PermissionsMixin)
...
location = models.ForeignKey(Location)
class Location(models.Model)
name = models.CharField(max_length=50, blank=True, null=True)
我编写了一个包含此字段的自定义用户表单,如下所示:
I've written a custom user form that includes this field as follows:
class MyCustomUserCreationForm(models.ModelForm)
...
location = forms.ModelChoiceField(Location.objects.all())
这一切似乎都正常工作,但是,位置选择字段的右侧没有加号按钮.我希望能够在创建用户时添加位置,就像在 Django 教程.根据这个问题,我可能不会如果我无权更改模型,请查看绿色加号,但我以具有所有权限的超级用户身份登录.知道我做错了什么吗?
This all appears to be working correctly, however, there is no plus button to the right of the select field for location. I want to be able to add a location when I create a user, in the same way that you can add polls when creating choices in the Django tutorial. According to this question, I might not see the green plus if I don't have permission to change the model, but I am logged in as a superuser with all permissions. Any idea what I'm doing wrong?
推荐答案
你需要在你的模型表单中设置一个 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:
- RelatedFieldWidgetWrapper
- 更多相关FieldWidgetWrapper——我自己的弹出窗口莉>
- Django admin - 如何在自定义管理表单中为多对多字段添加绿色加号
- 如何手动使用相关字段aWidget自定义小部件?
- Django:覆盖RelatedFieldWidgetWrapper
这篇关于Django ModelChoiceField 没有加号按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!