更新时间:2023-11-30 16:05:10
解决方案如下(不需要HTML代码):
在管理文件中,定义以下内容:
导入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:
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