Javascript Django 管理弹出功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2347582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:53:14  来源:igfitidea点击:

Django Admin popup functionality

javascriptdjangopopupadmin

提问by Ed.

This topic is fairly common (most explicitly detailed here: http://www.hoboes.com/Mimsy/hacks/replicating-djangos-admin/), but I'm still having trouble with it. I'm trying to use the "plus" button functionality used in the admin site where one can add an additional foreign key to a linked entry. In the admin site, a popup displays allowing the user to submit a new field and then that new value is populated on the original form.

这个话题很常见(最详细的在这里:http: //www.hoboes.com/Mimsy/hacks/replicating-djangos-admin/),但我仍然有问题。我正在尝试使用管理站点中使用的“加号”按钮功能,可以在其中向链接条目添加额外的外键。在管理站点中,会显示一个弹出窗口,允许用户提交新字段,然后将新值填充到原始表单中。

I think my issue centers around the inclusion of this line:

我认为我的问题集中在包含这一行:

within the base.html template and the popadd.html template. Clicking the plus button does not bring up a new window. The popadd template simply loads in the same tab. And submitting a new entry does not take the user back to the original form.

在 base.html 模板和 popadd.html 模板中。单击加号按钮不会打开新窗口。popadd 模板只是在同一个选项卡中加载。并且提交新条目不会将用户带回原始表单。

The admin site is functional. I am including ADMIN_MEDIA_PREFIX = '/media/admin/' in the settings.py file. Does it have something to do with where the RelatedObjectLookups.js lives? It's currently in an admin directory outside of my project folder. Do I have to create a symlink?

管理站点正常运行。我在 settings.py 文件中包含 ADMIN_MEDIA_PREFIX = '/media/admin/' 。它与RelatedObjectLookups.js 所在的位置有关吗?它目前位于我的项目文件夹之外的 admin 目录中。我必须创建符号链接吗?

Sorry for the noob questions. Would appreciate any suggestions (as detailed as possible).

对不起,菜鸟问题。将不胜感激任何建议(尽可能详细)。

回答by cooncesean

Following the steps outlined below will allow you to recreate Django admin's related object pop-up functionality without having to create any custom widgets, views, and urls. These steps assume you are trying to get this pop-up working in your own custom admin site which subclasses Django's admin.

按照下面概述的步骤,您可以重新创建 Django 管理员的相关对象弹出功能,而无需创建任何自定义小部件、视图和 url。这些步骤假设您正在尝试让这个弹出窗口在您自己的自定义管理站点中工作,该站点是 Django 管理的子类。

Lets assume the following two models Bookand Author, with an FK from Book to Author. Lets also assume that we'll want the ability to use the Related Object Pop-Upto add an Author when creating/editing a Book:

让我们假设以下两个模型BookAuthor,以及从 Book 到 Author 的 FK。还假设我们希望能够在创建/编辑书籍时使用相关对象弹出窗口添加作者:

[app_name]/models.py:

[app_name]/models.py:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=200)

class Book(models.Model):
    author = models.ForeignKey(Author)
    title = models.CharField(max_length=200)

Lets create our custom admin site:

让我们创建我们的自定义管理站点:

[app_name]/sites.py:

[app_name]/sites.py:

from django.contrib.admin.sites import AdminSite

my_admin_site = AdminSite(name='my_custom_admin')

Our custom admin site will register two ModelAdmins to allow users to add/edit/delete both the Book and Author models:

我们的自定义管理站点将注册两个 ModelAdmins 以允许用户添加/编辑/删除 Book 和 Author 模型:

[app_name]/admin.py:

[app_name]/admin.py:

from django.contrib.admin.options import ModelAdmin

from [app_name].forms import BookForm # We'll create this form below
from [app_name].models import Author, Book
from [app_name].sites import my_admin_site

class BookModelAdmin(ModelAdmin):
    form = BookForm()

# Register both models to our custom admin site
my_admin_site.register(Author, ModelAdmin)
my_admin_site.register(Book, BookModelAdmin)

Now, we'll setup the BookFormwhich is used in the BookModelAdminabove. This is where the magic happens. For more info on the RelatedFieldWidgetWrapper api, click here:

现在,我们将设置上面BookForm使用的BookModelAdmin。这就是魔法发生的地方。有关 RelatedFieldWidgetWrapper api 的更多信息,请单击此处

[app_name]/forms.py:

[app_name]/forms.py:

from django.contrib.admin.widgets import RelatedFieldWidgetWrapper
from django import forms

from [app_name].models import Book
from [app_name].sites import my_admin_site

class BookForm(forms.ModelForm):
    author = Book._meta.get_field('author').formfield(
        widget=RelatedFieldWidgetWrapper(
            Book._meta.get_field('author').formfield().widget,
            Book._meta.get_field('author').rel,
            my_admin_site,
            can_add_related=True
        )
    )

    class Meta:
        model = Book

Notes:

笔记:

  1. You will need to ensure that these two javascript files included in your templates: admin/js/core.jsand admin/js/admin/RelatedObjectLookups.js.
  1. 您需要确保这两个 javascript 文件包含在您的模板中:admin/js/core.jsadmin/js/admin/RelatedObjectLookups.js.

Gotchas:

陷阱:

  1. is_popupneeds to be set and passed correctly in your templates. Specifically, in any custom change_form.htmltemplates you override, you must remember to add this line somewhere within your form tags: {% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}, so that the logic in BaseModelAdmin.response_add()returns the correct response.
  1. is_popup需要在模板中正确设置和传递。具体来说,在change_form.html您覆盖的任何自定义模板中,您必须记住在表单标记中的某处添加此行:{% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %},以便逻辑BaseModelAdmin.response_add()返回正确的响应。

Under The Hood:Essentially, we're re-using the form processing logic, widget wrapper and javascript that is already included with Django admin.

Under The Hood:本质上,我们正在重新使用已包含在 Django admin 中的表单处理逻辑、小部件包装器和 javascript。

  1. Using RelatedFieldWidgetWrapperto wrap the widget associated to the related object field in our form (and specifically passing can_add_related=Truein the constructor) tells the widget to append the necessary '+' link with the appropriate javascript onclick event attached to it.
  2. Django admin's javascript handles all of the logic necessary to launch the pop-up.
  3. The {% if is_popup %}...{% endif %}logic in our change_form.htmltemplate(s) and the logic in BaseModelAdmin.response_add()handles the saving of the new related object and returns the appropriate javascript response that informs the pop-up that it needs to be closed.
  1. 使用RelatedFieldWidgetWrapper在我们的表单中包装与相关对象字段关联的小部件(特别是传入can_add_related=True构造函数)告诉小部件附加必要的“+”链接,并附加适当的 javascript onclick 事件。
  2. Django admin 的 javascript 处理启动弹出窗口所需的所有逻辑。
  3. {% if is_popup %}...{% endif %}我们的逻辑change_form.html模板(S)和在逻辑BaseModelAdmin.response_add()手柄的新的相关对象,并返回相应的JavaScript响应,通知弹出,它需要被关闭的储蓄。

Related Repo:This public repo should provide sample code for the Django project discussed above: https://github.com/cooncesean/Books

相关仓库:这个公共仓库应该为上面讨论的 Django 项目提供示例代码:https: //github.com/cooncesean/Books

回答by SaeX

Google pointed me to this page when searching how to get a "+" icon next to fields in a custom form with ForeignKey relationship (just like the admin site would do), so I thought I'd add.

在搜索如何在具有外键关系的自定义表单中的字段旁边获得“+”图标时,Google 将我指向此页面(就像管理站点一样),所以我想我会添加。

For me, using django-autocomplete-lightdid the trick very well, using the "add another" functionality. See this live demo.

对我来说,使用django-autocomplete-light“添加另一个”功能很好地解决了这个问题。请参阅此现场演示

See Django ModelChoiceField has no plus buttonas well.

请参阅Django ModelChoiceField 也没有加号按钮

回答by sontek

I've also created an app you can just include in your project at http://github.com/sontek/django-tekextensions

我还创建了一个应用程序,您可以在http://github.com/sontek/django-tekextensions 上将其包含在您的项目中

回答by Fabio Caccamo

If in the adminyou want to display related objectsin modals instead of old popup windowsI suggest you to try the django-admin-interface.

如果管理员要显示相关对象情态动词,而不是旧的弹出窗口,我建议你去尝试的django-admin-interface

To install it follow these steps:

要安装它,请按照下列步骤操作:

  • pip install django-admin-interface
  • Add admin_interface, flat_responsiveand colorfieldto settings.INSTALLED_APPSbeforedjango.contrib.admin
  • python manage.py migrate
  • python manage.py collectstatic
  • pip install django-admin-interface
  • 添加admin_interface,flat_responsivecolorfieldsettings.INSTALLED_APPS之前django.contrib.admin
  • python manage.py migrate
  • python manage.py collectstatic

For more detailed info, see django-admin-interfaceon GitHub.

有关更多详细信息,请参阅GitHub 上的django-admin-interface