gpt4 book ai didi

python - 内联 ModelAdmin 的 Django 管理员验证

转载 作者:行者123 更新时间:2023-12-01 06:41:03 24 4
gpt4 key购买 nike

我在管理页面中使用表格内联,其中的指令可能有多个 scrap_code 和 event_code。但一个 scrap_code 或 event_code 不能有多个指令。我在整个表中制作了 scrap_code 和 event_code,以便它们不能重复。

我的admin.py

class InstructionAdmin(admin.ModelAdmin):
inlines = [ ScrapEventInstructionMapInline, ]
fields=('name',)
form = InstructionMapForm

当用户尝试输入已存在的 event_code 或 scrap_code 时,我需要向用户显示警报。但问题是即使我们有数据指令,s_code 和 e_code 作为 None

我的 forms.py 文件:-

class InstructionMapForm(forms.ModelForm):

def clean(self):
instruction = self.cleaned_data.get('instruction')
s_code = self.cleaned_data.get('scrap_code')
e_code = self.cleaned_data.get('event_code')

qs = ScrapEventInstructionMap.objects.all()
if s_code:
dup_scrap = list(ScrapEventInstructionMap.objects.filter(scrap_code=s_code).values('scrap_code'))
if dup_scrap:
raise forms.ValidationError ('The Scrap Code provided ({}) already exists, kindly edit it or provide another Scrap Code'.format(s_code))

elif e_code:
dup_event = list(ScrapEventInstructionMap.objects.filter(event_code=e_code).values('event_code'))
if dup_event:
raise forms.ValidationError ('The Event Code provided ({}) already exists, kindly edit it or provide another Event Code'.format(e_code))

如何获取数据避免无?以及如何向用户显示警报?

最佳答案

class ScrapEventInstructionAdminFormset(forms.models.BaseInlineFormSet):

def clean(self):
forms = [form for form in self.forms if not form.cleaned_data.get('DELETE')]
for form in forms:
scrap_code = form.cleaned_data.get('scrap_code')
event_code = form.cleaned_data.get('event_code')
if form.instance.id:
scp = SCPInstruction.objects.exclude(id=form.instance.id)
is_scrap_code_exists = scp.filter(instruction=form.instance.instruction, scrap_code=scrap_code)
is_event_code_exists = scp.filter(instruction=form.instance.instruction, event_code=event_code)
else:
is_scrap_code_exists = SCPInstruction.objects.filter(instruction=form.instance.instruction, scrap_code=scrap_code)
is_event_code_exists = SCPInstruction.objects.filter(instruction=form.instance.instruction, event_code=event_code)

if is_scrap_code_exists:
form.add_error('scrap_code', 'The Scrap Code provided ({}) already exists, kindly edit it or provide another Scrap Code'.format(scrap_code))
if is_event_code_exists:
form.add_error('event_code', 'The Event Code provided ({}) already exists, kindly edit it or provide another Event Code'.format(event_code))

return self.forms

关于python - 内联 ModelAdmin 的 Django 管理员验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59455156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com