4 cents
4 cents

Reputation: 13

Django: didn't return a HttpResponse object error

I am trying to make a Post form, but HttPResponse occurs.In my code, there is a redirect method, and I think it is considered as a httpresponse, isn't it?

I am just a begineer, so if someone could find an easy mistake, I would appreciate

from django.shortcuts import render,redirect
from .forms import DayCreateForm


def index(request):
    return render(request,'diary/day_list.html')


def add(request):

    form = DayCreateForm(request.POST or None)


    if request.method == 'POST'and form.is_valid():
        form.save()
        return redirect('diary:index')

        context ={
         'form':form
        }
        return render(request,'diary/day_form.html',context)

Upvotes: 0

Views: 59

Answers (2)

White Dog
White Dog

Reputation: 50

In your code there is no HttpResponse returned if request.method is not POST, so try to add a return of HttpResponse in the case of 'not Post'.

Upvotes: 1

JPG
JPG

Reputation: 88429

You are not returning any HTTP response if the requested method other than HTTP POST. So, try the below snippet

from django.http.response import HttpResponse


def add(request):
    if request.method == 'POST':
        form = DayCreateForm(request.POST or None)
        if form.is_valid():
            form.save()
            return redirect('diary:index')
        else:
            return HttpResponse("form is not valid")
    else:
        form = DayCreateForm()
        context = {
            'form': form
        }
        return render(request, 'diary/day_form.html', context)

Upvotes: 1

Related Questions