[Fixed]-Django form is_valid() fails

14👍

All fields of your model are required. So, form.is_valid() will be True, if all fields are filled with correct values and are not blanked.
You have declared fields time, user, views as hidden fields. Are you sure, that you have filled them in your template form?
Also, you may want to auto stamp field time = models.DateField(). Modify your model field like

time = models.DateField(auto_now=True)`. 

After this you don’t have to fill it by yourself in template form.

Your view must return HttpResponse object in all cases. If your form is not valid, i.e. if form.is_valid() will return False, then no HttpResponse object will be returned by your view. This can be the source of your fail. Add else statement for if form.is_valid():

from django.http import Http404
def new(request):  
    if request.method == 'POST': # If the form has been submitted...
        form = StatementForm(request.POST) # A form bound to the POST data
        if form.is_valid():
            stmt = form.save()
            path = 'stmt/' + stmt.id
            return render_to_response(path, {'stmt': stmt})
        else:
            # Do something in case if form is not valid
            raise Http404 
    else: 
        # Your code without changes
👤stalk

4👍

Change this line:

    form = StatementForm(request.POST, initial={'time': d.strftime("%Y-%m-%d %H:%M:%S"), 'user':loggedin_user, 'views':0})

For this:

    form = StatementForm(initial={'time': d.strftime("%Y-%m-%d %H:%M:%S"), 'user':loggedin_user, 'views':0})
👤Goin

Leave a comment