为什么Django会引发ValueError?

时间:2018-10-25 13:25:35

标签: django python-3.x django-forms django-views

这是我的项目文件夹下的view.py文件。 当我在“待办事项”列表中添加值时,会引发此错误吗?

  

视图my_day.views.index没有返回HttpResponse对象。它返回None。

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

1 个答案:

答案 0 :(得分:3)

您认为,根据if条件,您可能有3种结果,但是只有2种返回HttpResonse对象。更具体地说,if form.is_valid()仅在此条件通过时才返回HttpResponse对象。如果没有,它将返回None(基本上什么都没有),因为没有else条件或其他回退。

您需要向if form.is_valid()添加else条件。更重要的是,您应该实现另一种方法,而不是根据POST请求提供内容。以WillemVanOnsem have commented的身份签出Post/Redirect/Get模式。我已在需要实现的地方替换了return render(...)实例,但需要进行一些调整才能工作,例如替换视图名称(应在urls.py文件中定义)。

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