Django:添加一个“添加新的"ModelForm 中外键的按钮 [英] Django: adding an "Add new" button for a ForeignKey in a ModelForm
问题描述
TL;DR:如何为 ModelForm 中的外键添加添加新"按钮?
TL;DR: How can I add an "Add new" button for a ForeignKey in a ModelForm?
长版:我在一个项目中使用 Django 1.7.我的models.py中有这两个模型
Long version: I'm using Django 1.7 for a project. I have these two Models in my models.py
class Client(models.Model):
name = models.CharField(max_length=100)
class Order(models.Model):
code = models.IntegerField()
client = models.ForeignKey(Client)
[其他一些不相关的字段被省略]
我正在使用 ModelForm 用新订单填充数据库,如下所示:
I am using a ModelForm to populate the db with new orders, like this:
class OrderNewForm(forms.ModelForm):
class Meta:
model = Order
Django 在为客户端字段添加下拉菜单方面做得非常好,用从客户端获取的条目填充它.尽管如此,我还是希望有一个添加新客户"链接/按钮/任何东西,以便在添加相关订单的同时添加一个全新的客户.
Django does quite a good job at adding a dropdown menu for the client field, populating it with entries taken from Client. Nevertheless, I'd like to have an "Add new client" link/button/whatever to add a brand new client at the same time I add a related Order.
Django 管理员会自动执行此操作,添加一个+"按钮来打开一个弹出窗口,但我在上面的 ModelForm 中找不到一种简单的方法来执行此操作.我在这里阅读了许多问题并在别处阅读了链接,但没有什么能真正帮助我.对此有任何想法吗?
Django admin does that automatically, adding a "+" button" that opens a popup, but I couldn't find an easy way to do that in a ModelForm like the one above. I read many questions here and links elsewhere, but nothing really helped me. Any idea about that?
推荐答案
我已经在自定义小部件中解决了它.我不记得我是从 Django 管理员那里得到了一部分,还是从头开始构建.
I have solved it in a custom widget. I don't remember if I took parts from Django admin, or I have built from scratch.
所以表格将是:
class OrderNewForm(forms.ModelForm):
client = forms.ModelChoiceField(
required=False,
queryset=Client.objects.all(),
widget=RelatedFieldWidgetCanAdd(Client, related_url="so_client_add")
)
class Meta:
model = Order
fields = ('code', 'client')
呈现+"按钮并链接到管理界面中的添加弹出窗口或您使用 related_url 参数提供的自定义视图的小部件是:
And the widget, that renders the "+" button and link to the add popup in the admin interface or to a custom view you provice with the related_url argument is:
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from django.forms import widgets
from django.conf import settings
class RelatedFieldWidgetCanAdd(widgets.Select):
def __init__(self, related_model, related_url=None, *args, **kw):
super(RelatedFieldWidgetCanAdd, self).__init__(*args, **kw)
if not related_url:
rel_to = related_model
info = (rel_to._meta.app_label, rel_to._meta.object_name.lower())
related_url = 'admin:%s_%s_add' % info
# Be careful that here "reverse" is not allowed
self.related_url = related_url
def render(self, name, value, *args, **kwargs):
self.related_url = reverse(self.related_url)
output = [super(RelatedFieldWidgetCanAdd, self).render(name, value, *args, **kwargs)]
output.append(u'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' %
(self.related_url, name))
output.append(u'<img src="%sadmin/img/icon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (settings.STATIC_URL, _('Add Another')))
return mark_safe(u''.join(output))
这篇关于Django:添加一个“添加新的"ModelForm 中外键的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!