如何在Django中使用Input type =“ datetime-local”保存表单

时间:2018-10-03 14:09:58

标签: python django django-models django-forms django-templates

在我的表单中,我有一个结束日期和时间的输入字段,但是当我选择结束日期和时间并提交时,该表单无效。在这里,我提到了我的html,views.py models.py和form.py。我不知道为什么会发生这种情况,所以请帮助我。

HTML

<label>End Date & Time</label>
  <div >
     <input class="form-control" id="party"  type = "datetime-local" name="end_date">
   </div> 

Views.py

def event(request):
    if request.method == 'POST':
        form = EventForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request, "Insertion Success!")
            return redirect('/event')
        else:

            messages.success(request,"You missed to fill some fields!")
            return HttpResponse(form)

form.py

class EventForm(forms.ModelForm):
   class Meta:
       model = Events
       fields = ['end_date']
       widgets = {
        'end_date': DateTimeInput(attrs={'type': 'datetime-local'}),
}

models.py

class Events(models.Model):
    end_date =models.DateTimeField(auto_now=False,blank=True)

2 个答案:

答案 0 :(得分:0)

  <div >
     <input class="form-control" id="party"  type = "datetime-local" name="end_date">
   </div> 

此代码必须包含用于呈现表单的 form 模板

将代码更改为此:

<form>
{% csrf_token %}
{{ form.as_p  }}
</form>

在事件视图更改中,使用类似以下代码的内容:

from .forms import EventForm 
def event(request):
    if request.method == 'POST':
        form = EventForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request, "Insertion Success!")
            return redirect('/event')
        else:

            messages.success(request,"You missed to fill some fields!")
            return HttpResponse(form)

    else:
        form=EventForm()
        return render(request,'your template name ',context={'form':form})

答案 1 :(得分:0)

除了小部件之外,您还需要在字段中设置格式。

请参见https://stackoverflow.com/a/53194594/3057341