在Django Admin中保存模型之前显示警告消息

yvgpqqbh  于 2023-05-19  发布在  Go
关注(0)|答案(3)|浏览(365)

模型保存到数据库后或保存过程中出现错误时,有显示消息的方法。但是当用户在Django Admin中点击保存按钮时,我如何显示警报?有办法做到吗?

hpxqektj

hpxqektj1#

如果你浏览了django admin,你可以看到django使用submit_line.html来呈现保存(保存和继续)按钮。
有很多方法可以做到这一点,
1)如果你想要应用程序明智的警报,然后在你的admin.py文件中包括自定义js文件与管理媒体选项,

@admin.register(Model)
class ModelAdmin(admin.ModelAdmin):
   class Media:
        js = (
            'js/myscript.js',  # project's static folder ( /static/js/myscript.js )
        )

在您的myscript.js写入中,

window.addEventListener("load", function () {
(function ($) {
    $('form').submit(function () {
        var c = confirm("continue submitting ?");
        return c;
    });

})(django.jQuery);

}); 2)如果你想在admin中的所有表单的警报,只需继承templates/admin/submit_line.html目录中的submit_line.html,并简单地写,

<script>
    $(document).ready(function(){
        $('form').submit(function() {
            var c = confirm("continue submitting ?");
            return c;
        });
    })
</script>
fjaof16o

fjaof16o2#

但是当用户在Django Admin中点击保存按钮时,我如何显示一个警报?有办法做到吗?
它被称为validation。Django的最佳实践是在服务器上进行验证,文档中描述了这种方式。
您需要执行以下步骤:
1.在管理模型中设置form
1.在新表单中定义clean_name方法,其中name是要检查的字段的名称。您也可以覆盖整个干净。
1.如果出现错误,则引发ValidationError以向用户发送消息。如果在clean_name方法中引发异常,name字段将在界面中突出显示。

from django.core.exceptions import ValidationError
from django import forms
from django.contrib import admin

class ArticleAdmin(admin.ModelAdmin):
    form = MyArticleAdminForm

class MyArticleAdminForm(forms.ModelForm):
    def clean_name(self):
        if some_condition:
            raise ValidationError("Message which you want to show to the user")
        return self.cleaned_data["name"]
fkvaft9z

fkvaft9z3#

当Django Admin中出现错误时,你可以通过点击SAVE(Save)按钮来显示一条警告消息。
例如,有Person模型,如下所示:

# "app1/models.py"

from django.db import models

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

    def __str__(self):
        return self.first_name + " " + self.last_name

< Add and Change pages>

首先,我解释了当Django Admin中出现错误时,如何通过点击AddChange页面上的SAVE按钮来显示警报消息。
Person admin如下所示:

# "app1/admin.py"

from django.contrib import admin
from .models import Person

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

然后,在core/static/core/admin/app1/js/中创建additional.js,并将submit_line.html从django/contrib/admin/templates/admin/submit_line.html复制到templates/admin/app1/person/,如下所示。* 您可以看到原始的submit_line.html

Django Project
 |-core
 |  |-settings.py
 |  └-static
 |     └-core
 |        └-admin
 |           └-app1
 |              └-js
 |                 └-additional.js # Here
 |-app1
 |  |-models.py
 |  └-admin.py
 |-app2
 └-templates
    └-admin
       └-app1
          └-person
             └-submit_line.html # Here

然后在additional.js中,定义checkIfEmpty(),如果first_namelast_name为空,则显示警报消息,如下所示:

// "core/static/core/admin/app1/js/additional.js"

function checkIfEmpty() {
    let firstName = document.querySelector(
        'form input[name="first_name"]'
    ).value;
    let lastName = document.querySelector(
        'form input[name="last_name"]'
    ).value;
    if (firstName == "" || lastName == "") {
        alert("Fill all fields!!")
        return false
    }
    return true;
}

然后,将onclick="return checkIfEmpty();"添加到submit_line.html中的<input ... name="_save">,如下所示:

# "templates/admin/app1/person/submit_line.html"

# ...

{% block submit-row %}
{% if show_save %}
<input 
  type="submit" 
  value="{% translate 'Save' %}" 
  class="default" 
  name="_save" 
  onclick="return checkIfEmpty();" # Here
>
{% endif %}
{% if show_delete_link and original %}

# ...

然后,在Media类中将"core/admin/app1/js/additional.js"设置为js,如下所示:

# "app1/admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    class Media: # Here
        js = ("core/admin/app1/js/additional.js",)

然后,单击SAVE按钮显示警报消息,因为Add页面上的First name:为空,Change页面上的Last name:为空,如下所示。* 在本例中,仅在PersonAddChange页面上显示警报消息,而在其他admin AddChange页面上不显示警报消息:

并且,如果您希望仅在Add页面中显示警报消息,请在submit_line.html中添加{% if not change %}...{% endif %},如下所示:

# "templates/admin/app1/person/submit_line.html"

# ...

{% block submit-row %}
{% if show_save %}
<input 
  type="submit" 
  value="{% translate 'Save' %}" 
  class="default" 
  name="_save" 
  {% if not change %}onclick="return checkIfEmpty();"{% endif %} # Here
>
{% endif %}
{% if show_delete_link and original %}

# ...

并且,如果您希望仅在Change页面中显示警报消息,请在submit_line.html中添加{% if change %}...{% endif %},如下所示:

# "templates/admin/app1/person/submit_line.html"

# ...

{% block submit-row %}
{% if show_save %}
<input 
  type="submit" 
  value="{% translate 'Save' %}" 
  class="default" 
  name="_save" 
  {% if change %}onclick="return checkIfEmpty();"{% endif %} # Here
>
{% endif %}
{% if show_delete_link and original %}

#...

并且,您可以直接在submit_line.html中定义checkIfEmpty(),如下所示,而无需在additional.js中定义checkIfEmpty()并在Media类中将其设置为js

# "templates/admin/app1/person/submit_line.html"

# ...

{% block submit-row %}
{% if show_save %}
<input 
  type="submit" 
  value="{% translate 'Save' %}" 
  class="default" 
  name="_save" 
  onclick="return checkIfEmpty();" # Here
>
{% endif %}
{% if show_delete_link and original %}

# ...

<script>
function checkIfEmpty() {
    let firstName = document.querySelector(
        'form input[name="first_name"]'
    ).value;
    let lastName = document.querySelector(
        'form input[name="last_name"]'
    ).value;
    if (firstName == "" || lastName == "") {
        alert("Fill all fields!!")
        return false
    }
    return true;
}
</script>

< Change List page>

接下来,我解释了如何在Django Admin中出现错误时,通过单击Change List页面上的Save按钮来显示警报消息。
因此,Person管理员如下所示:

# "app1/admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name')
    list_editable = ('first_name', 'last_name')
    list_display_links = None
    ordering = ('id',)

然后,在core/static/core/admin/app1/js/中创建additional.js,并将pagination.html从django/contrib/admin/templates/admin/pagination.html复制到templates/admin/app1/person/,如下所示。* 您可以看到原始的pagination.html

Django Project
 |-core
 |  |-settings.py
 |  └-static
 |     └-core
 |        └-admin
 |           └-app1
 |              └-js
 |                 └-additional.js # Here
 |-app1
 |  |-models.py
 |  └-admin.py
 |-app2
 └-templates
    └-admin
       └-app1
          └-person
             └-pagination.html # Here

然后在additional.js中定义checkIfEmpty(),如果first_namelast_name为空,则显示警报消息,如下所示:

// "core/static/core/admin/app1/js/additional.js"

function checkIfEmpty() {
    let firstNames = document.querySelectorAll(
        'form#changelist-form input[name$="first_name"]'
    );
    let lastNames = document.querySelectorAll(
        'form#changelist-form input[name$="last_name"]'
    );
    for (let i = 0; i < firstNames.length; i++) {
        if (firstNames[i].value == "" || lastNames[i].value == "") {
            alert("Fill all fields!!");
            return false;
        }
    }
    return true;
}

然后,将onclick="return checkIfEmpty();"添加到pagination.html中的<input ... value="{% translate 'Save' %}">,如下所示:

# "templates/admin/app1/person/pagination.html"

# ...

{% if cl.formset and cl.result_count %}
<input 
  type="submit" 
  name="_save" 
  class="default" 
  value="{% translate 'Save' %}"
  onclick="return checkIfEmpty();" # Here
>
{% endif %}
</p>

然后,在Media类中将"core/admin/app1/js/additional.js"设置为js,如下所示:

# "app1/admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name')
    list_editable = ('first_name', 'last_name')
    list_display_links = None
    ordering = ('id',)

    class Media: # Here
        js = ("core/admin/app1/js/additional.js",)

然后,通过单击Save按钮显示警报消息,因为FIRST NAME字段为空,如下所示。* 本例仅在PersonChange List页面显示提醒消息,其他admin Change List页面不显示:

并且,您可以直接在pagination.html中定义checkIfEmpty(),如下所示,而无需在additional.js中定义checkIfEmpty()并在Media类中将其设置为js

# "templates/admin/app1/person/pagination.html"

# ...

{% if cl.formset and cl.result_count %}
<input 
  type="submit" 
  name="_save" 
  class="default" 
  value="{% translate 'Save' %}"
  onclick="return checkIfEmpty();" # Here
>
{% endif %}
</p>

<script>
function checkIfEmpty() {
    let firstNames = document.querySelectorAll(
        'form#changelist-form input[name$="first_name"]'
    );
    let lastNames = document.querySelectorAll(
        'form#changelist-form input[name$="last_name"]'
    );
    for (let i = 0; i < firstNames.length; i++) {
        if (firstNames[i].value == "" || lastNames[i].value == "") {
            alert("Fill all fields!!");
            return false;
        }
    }
    return true;
}
</script>

相关问题