我有一张表格,我试图有一些"有条件的"验证开启,具体取决于用户点击的按钮。
如果用户点击"提交"则应该都需要这些字段,如果用户点击"草稿"则需要无。
我的模型指定不需要任何字段来容纳草稿。然后我试图覆盖它以仅在点击某个按钮时要求验证,但我无法弄清楚我的生活如何去做。
我已经简化了以下代码。
表格:
class MOCForm(forms.ModelForm):
facility = forms.CharField(required=False)
def fields_required(self, fields):
"""Used for conditionally marking fields as required."""
for field in fields:
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError(" This field is required.")
self.add_error(field, msg)
def clean(self):
self.fields_required(['facility'])
return self.cleaned_data
查看方法:
def post(self, request):
if request.POST.get('_start') == '' or request.POST.get('_draft') == '':
MOC_form = forms.MOCForm(request.POST, prefix="MOC_form", instance=MOC)
if request.POST.get('_draft') == '' or MOC_form.is_valid():
MOC_form.save()
if request.POST.get('_start') == '':
MOC.submitted_date = timezone.now()
if request.POST.get('_draft') == '':
MOC.status = C.moc_status_draft()
if request.POST.get('_start') == '' or request.POST.get('_draft') == '':
MOC.creator = request.user
MOC.save()
if request.POST.get('_start') == '' or request.POST.get('_draft') == '':
# If there is an activation (i.e. it is part of the flow), redirect appropriately
if request.activation:
request.activation.process.MOC = MOC
request.activation.done()
return redirect(get_next_task_url(request, request.activation.process))
# Otherwise, just reload the same page (likely the dashboard)
else:
return redirect(request.path)
else:
if request.POST.get('_start') == '' or request.POST.get('_draft') == '':
context = {}
return render(request, 'MOC/CreateMOC.html', context)
问题是,即使我完全取出MOC_form.is_valid()
支票 ,它仍会给我同样的错误:The MOC could not be changed because the data didn't validate.
我想完全跳过此验证,但仅当POST参数包含提交的' _draft' - 但是我无法访问clean方法中的POST参数。我该怎么做呢?
谢谢!
答案 0 :(得分:1)
但是我无法在clean方法内部访问POST参数
您有权具有访问权限,因为您将POST数据作为data
的{{1}}属性进行传递。
所以您可以这样:
MOCForm.__init__