簡體   English   中英

Django 管理員“保存並在現場查看”按鈕

[英]Django admin "save and view on site" button

Django 管理站點非常棒,我們在工作中經常使用它。 我的問題是 - 我如何在底部添加一個額外的按鈕,旁邊是“保存”、“保存並繼續編輯”等按鈕,保存 model,然后重定向到可用的“現場查看”按鈕在已定義模型的表格右上角?

提前致謝!

除了在change_form模板中添加按鈕外,您還希望覆蓋ModelAdmin(和response_add )的response_change方法。

這樣的事情應該有效:

def response_change(self, request, obj):
  res = super(MyModelAdmin, self).response_change(request, obj)
  if "_preview" in request.POST:
    return HttpResponseRedirect('preview-url-here')
  else:
    return res

要做到這一點,但也可以選擇顯示/隱藏某些模型表單,這是我做的:

1.首先通過在主模板文件夾下創建自定義模板來覆蓋submit_line.html模板: my_project/templates/admin/submit_line.html ,復制原始my_project/templates/admin/submit_line.html的內容並將自定義按鈕添加到submit-row塊(它贏了默認顯示,因為它設置為False):

# submit_line.html

{% load i18n admin_urls %}
<div class="submit-row">
{% block submit-row %}
{% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save">{% endif %}
...
...
...
{% if show_save_and_preview|default:False %}<input type="submit" value="{% trans 'Save and preview' %}" name="_preview">{% endif %}
{% endblock %}
</div>


2.接下來,只需為某些模型顯示它,只需覆蓋ModelAdmin方法:

changeform_view :顯示模板上的按鈕。

response_change :設置保存后重定向到的位置。

# admin.py

class MyModelAdmin(admin.ModelAdmin):
    # ..
    # ..

    def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context['show_save_and_preview'] = True
        return super(MyModelAdmin, self).changeform_view(request, object_id, extra_context=extra_context)

    def response_change(self, request, obj):
        res = super(MyModelAdmin, self).response_change(request, obj)
        if "_preview" in request.POST:
            # used object's custom method "get_url()":
            return HttpResponseRedirect(obj.get_url())
        else:
            return res

現在它將顯示為此特定表單,對其他模型執行相同操作,只需覆蓋上面的兩個方法。

您可以在特定管理員的“添加”表單和“更改”表單的底部添加自定義按鈕。

首先,在django 項目根目錄下,創建“templates/admin/custom_change_form.html” ,如下圖:

在此處輸入圖像描述

接下來,在“django”庫下,有“change_form.html” ,即“django/contrib/admin/templates/admin/change_form.html” ,因此將“change_form.html”的所有代碼復制並粘貼到“custom_change_form.html” "如下圖:

# "templates/admin/custom_change_form.html"

{% extends "admin/base_site.html" %}
{% load i18n admin_urls static admin_modify %}

{% block extrahead %}{{ block.super }}
<script src="{% url 'admin:jsi18n' %}"></script>
{{ media }}
{% endblock %}

... Much more code below

接下來是第 64 行的代碼,如下所示:

# "templates/admin/custom_change_form.html"

{% block submit_buttons_bottom %}{% submit_row %}{% endblock %} # Line 64

然后,在"{% submit_row %}""{% endblock %}"之間添加以下代碼:

{% if custom_button %}
<div class="submit-row">
    <input type="submit" value="{% translate 'Custom button' %}" name="_custom_button">
</div>
{% endif %}

因此,這是完整的代碼,如下所示:

# "templates/admin/custom_change_form.html"

{% block submit_buttons_bottom %} # Line 64
{% submit_row %}
{% if custom_button %}
<div class="submit-row">
    <input type="submit" value="{% translate 'Custom button' %}" name="_custom_button">
</div>
{% endif %}
{% endblock %}

接下來,這是“settings.py”中模板的設置:

# "settings.py"

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

然后,將“os.path.join(BASE_DIR, 'templates')”添加到“DIRS” ,如下所示:

# "settings.py"

import os # Here

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')], # Here
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

現在,這是“人”model ,如下所示:

# "models.py"

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

然后,這是“人”管理員,如下所示:

# "admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person) # Here
class PersonAdmin(admin.ModelAdmin):
    pass

接下來,對於“Person” admin ,將“admin/custom_change_form.html”設置為“change_form_template” ,在“changeform_view ()”中將“True”設置為“extra_context['custom_button']” ,並設置“response_add()”“ response_change()”分別定義在“添加”“更改”表單中按下“自定義按鈕”后的動作,如下圖所示:

# "admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    change_form_template = "admin/custom_change_form.html" # Here
    
    def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
        extra_context = extra_context or {}
        
        extra_context['custom_button'] = True # Here
        
        return super().changeform_view(request, object_id, form_url, extra_context)

    def response_add(self, request, obj, post_url_continue=None): # Here

        if "_custom_button" in request.POST:
            # Do something
            return super().response_add(request, obj, post_url_continue)
        else:
            # Do something
            return super().response_add(request, obj, post_url_continue)

    def response_change(self, request, obj): # Here
        
        if "_custom_button" in request.POST:
            # Do something
            return super().response_change(request, obj)
        else:
            # Do something
            return super().response_change(request, obj)

最后,在“人員”管理員的“添加”表單和“更改”表單的底部添加了“自定義按鈕” ,如下所示:

在此處輸入圖像描述

在此處輸入圖像描述

另外,對於"Person" admin ,可以將" changeform_view()" 替換為"render_change_form()"設置"context.update({"custom_button": True})" ,如下所示:

# "admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    change_form_template = "admin/custom_change_form.html"
    
    def render_change_form(self, request, context, add=False, change=False, form_url="", obj=None):        
        
        context.update({"custom_button": True}) # Here

        return super().render_change_form(request, context, add, change, form_url, obj)

    def response_add(self, request, obj, post_url_continue=None):

        if "_custom_button" in request.POST:
            # Do something
            return super().response_add(request, obj, post_url_continue)
        else:
            # Do something
            return super().response_add(request, obj, post_url_continue)

    def response_change(self, request, obj):
        
        if "_custom_button" in request.POST:
            # Do something
            return super().response_change(request, obj)
        else:
            # Do something
            return super().response_change(request, obj)

然后,在“人員”管理員的“添加”表單和“更改”表單的底部添加“自定義按鈕” ,如下所示:

在此處輸入圖像描述

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM