Reputation: 195
This is my view.py file under my project folder. When I add a value in ToDo list it raises this error?
The view my_day.views.index didn't return an HttpResponse object. It returned None instead.
views.py
from django.shortcuts import render, redirect
from .models import List
from .form import ListForm
from django.contrib import messages
# Create your views here.
def index(request):
if request.method == "POST":
form = ListForm(request.POST or None)
if form.is_valid():
form.save()
all_items = List.objects.all
messages.success(request, ('Task Added'))
return render(request, 'index.html', {'all_items': all_items})
else:
all_items = List.objects.all
return render(request, 'index.html', {'all_items': all_items})
Upvotes: 0
Views: 589
Reputation: 3611
In your view, you have 3 possible outcomes based on the if
conditions but only 2 of them returns a HttpResonse
object. More specifically, the if form.is_valid()
only returns a HttpResponse
object if this condition passes. If it doesn't, it will return None
(basically nothing) because there is no else
condition or other fallback.
You need to add an else condition to the if form.is_valid()
. More so, you should implement another approach than to serve content on a POST
request. As WillemVanOnsem have commented, check out the Post/Redirect/Get pattern. I have replaced the return render(...)
instances where needed to achieve this, but will need some tweaking to work, for instance replace the view name (should be defined in your urls.py
file).
def index(request):
if request.method == "POST":
form = ListForm(request.POST or None)
if form.is_valid():
form.save()
all_items = List.objects.all
messages.success(request, ('Task Added'))
# Replaced the render(...) with a redirect instead.
# Replace "index" with the name of the view (if not index)
return HttpResponseRedirect(reverse("index"))
else:
# Added fallback if the form.is_valid() didn't pass
messages.failure(request, ('Failed when saving task'))
return render(request, 'index.html', {'all_items': all_items})
else:
all_items = List.objects.all
return render(request, 'index.html', {'all_items': all_items})
Upvotes: 3