1

In my form i have an input field of ENDDATE AND TIME but when i select end date and time and i give submit the form was not valid. Here i have mentioned my html, views.py models.py and form.py. i don't why its happening so please help me to do this.

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)
ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • 1
    If you output `{{ form.errors }}` in your template, then Django will *tell* you why it is not valid. – Daniel Roseman Oct 03 '18 at 14:15
  • I guess the `DateTimeInput` is returning a string and `DateTimeField` is expecting a `list` – Vineeth Sai Oct 03 '18 at 14:16
  • 2
    @DanielRoseman @Vineeth Sai I have removed widgets in form.py if i try to save form was not valid `return HttpResponse(form)` it returns like in this format `2018-10-05T01:01` but expected output like `2018-10-05T11:11:00Z` so please help me to do this thank you. – Sudharsan Venkatraj Oct 04 '18 at 05:33
  • Truly an infuriating problem. – diek Dec 01 '18 at 19:03

2 Answers2

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

This code must include form template for rendering form

Change code to this:

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

In event view change use something like this code:

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

You need to set the format in the field, in addition to the widget.

See https://stackoverflow.com/a/53194594/3057341

Psddp
  • 998
  • 10
  • 17