内联ModelAdmin的Django管理验证

2024-10-01 13:24:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我在我的管理页面中使用表格内联,其中一条指令可能有多个废弃代码和事件代码。但是一个代码或事件代码不能有多条指令。 我在整个表中创建了报废代码和事件代码,这样它们就不能被复制了

我的管理员

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

当用户试图输入已经存在的事件代码或废弃代码时,我需要向他们显示一个警报。 但问题是,即使我们有数据指令,s\u码和e\u码都是无的

我的表格.pyfile:- 你知道吗

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))

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


Tags: 代码selfeventdatagetobjects指令事件
1条回答
网友
1楼 · 发布于 2024-10-01 13:24:21

类说明dminformset(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

相关问题 更多 >