Django Admin-如何防止删除某些内联 [英] Django Admin - how to prevent deletion of some of the inlines

查看:144
本文介绍了Django Admin-如何防止删除某些内联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2种型号-例如,Book和Page。
页面具有Book的外键。



每个页面都可以标记为 was_read(布尔值),我想防止删除已读取的页面(在管理员中)。



在管理员中-Page是Book中的内联函数(我不希望Page在管理员中成为独立模型)。

p>

我的问题-如何实现读取的页面不会被删除的行为?
我正在使用Django 1.4,并尝试了几种选择:


  1. 重写删除以引发ValidationError-问题是管理员在删除时未捕获 ValidationError并获得错误页面,因此这不是一个好选择。

  2. 在PageAdminInline中覆盖方法-has_delete_permission-问题在这里-它是每种类型的,所以我允许删除所有页面,或者我不允许删除。

还有其他没有覆盖的好选择html代码?



谢谢,
Li

解决方案

解决方案如下(不需要HTML代码):



在管理文件中,定义以下内容:



<来自django.forms.models的pre> 导入BaseInlineFormSet

类PageFormSet(BaseInlineFormSet):

def clean(self):
super(PageFormSet,self).clean()

for self.forms中的表单:
如果没有hasattr(form,' cleaned_data'):
继续

数据= form.cleaned_data
curr_instance = form.instance
was_read = curr_instance.was_read


if(data.get('DELETE')and was_read):
引发ValidationError('Error')



class PageInline(admin.TabularInline) :
模型=页面
格式集= PageFormSet


I have 2 models - for example, Book and Page. Page has a foreign key to Book.

Each page can be marked as "was_read" (boolean), and I want to prevent deleting pages that were read (in the admin).

In the admin - Page is an inline within Book (I don't want Page to be a standalone model in the admin).

My problem - how can I achieve the behavior that a page that was read won't be deleted? I'm using Django 1.4 and I tried several options:

  1. Override "delete" to throw a ValidationError - the problem is that the admin doesn't "catch" the ValidationError on delete and you get an error page, so this is not a good option.
  2. Override in the PageAdminInline the method - has_delete_permission - the problem here -it's per type so either I allow to delete all pages or I don't.

Are there any other good options without overriding the html code?

Thanks, Li

解决方案

The solution is as follows (no HTML code is required):

In admin file, define the following:

from django.forms.models import BaseInlineFormSet

class PageFormSet(BaseInlineFormSet):

    def clean(self):
        super(PageFormSet, self).clean()

        for form in self.forms:
            if not hasattr(form, 'cleaned_data'):
                continue                     

            data = form.cleaned_data
            curr_instance = form.instance
            was_read = curr_instance.was_read


            if (data.get('DELETE') and was_read):            
                raise ValidationError('Error')



class PageInline(admin.TabularInline):
    model = Page
    formset = PageFormSet

这篇关于Django Admin-如何防止删除某些内联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆