【发布时间】:2019-12-23 12:11:35
【问题描述】:
我正在为我的管理页面使用表格内联,其中一条指令可能有多个 scrap_code 和 event_code。但是一个 scrap_code 或 event_code 不能有多个指令。 我已经在整个表格中制作了 scrap_code 和 event_code,这样它们就不会被复制。
我的管理员.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))
如何获取避免无的数据?以及如何向用户显示警报?
【问题讨论】:
-
不要在查询集上直接调用
list(),它已经是list了。 -
知道了,但是指令、s_code 和 e_ode 都没有。
-
首先,e_code 和 s_code 都是 None。其次,它不会进入 if 条件。当我输入相同的 event_code 或 scrap_code 时,它应该进入循环并引发 ValidationError 如果它已经存在
标签: python django django-forms django-admin