Django忽略了“必需”的价值

时间:2016-01-25 18:40:30

标签: django django-forms

我创建了一个日期范围表单,用于我的Django视图。在某些视图中,我在日期范围内使用它是必需的,但在其他视图中则不需要,因此我需要表单接受required关键字。我无法让表单识别required=False

Django表格:

class DateRangeForm(forms.Form):
  def __init__(self, *args, **kwargs):
    initial_start_date = kwargs.pop('initial_start_date')
    initial_end_date = kwargs.pop('initial_end_date')
    required_val = kwargs.pop('required')
    input_formats = kwargs.pop('input_formats')

    super(DateRangeForm,self).__init__(*args,**kwargs)
    self.fields['start_date'].initial = initial_start_date
    self.fields['start_date'].required = required_val
    self.fields['start_date'].input_formats = input_formats
    self.fields['end_date'].initial = initial_end_date
    self.fields['end_date'].required = required_val
    self.fields['end_date'].input_formats = input_formats

  start_date = forms.DateTimeField(widget=forms.DateInput(attrs={'class':"form-control text-center"}))
  end_date = forms.DateTimeField(widget=forms.DateInput(attrs={'class':"form-control text-center"}))

它在我的Django视图中使用如下:

def Nominal_Request(request):

  initial_end = Utils.addToDatetime(datetime.today().strftime("%Y/%m/%d"),weeks=6)

  form_dict = {}
  arg_dict = {}
  message = message = {'last_url':'Nominal_Request'}

  if request.method == 'POST':
    daterange_form = DateRangeForm(request.POST,required=False,initial_start_date=None,initial_end_date=initial_end,input_formats=dateFormats)

    if 'Range' in request.POST:

        if daterange_form.is_valid():
            #process the dates here....
            WS = daterange_form.cleaned_data['start_date']
            WE = daterange_form.cleaned_data['end_date']
            #date processing continues....

        args = {'Start':WS,'End':WE}
    return Request_Results(request,args)

  else:
    daterange_form = DateRangeForm(required=False,initial_start_date=None,initial_end_date=initial_end,input_formats=dateFormats)

    form_dict.update({'daterange_form':daterange_form})

  return render(request,'InterfaceApp/Request_Nominal.html',form_dict)

它显示正常,但Django仍然认为两个日期范围字段都是必需的,并且不允许我提交表单,其中一个或两个字段为空。 enter image description here

为什么它没有接收我的required arg?

0 个答案:

没有答案