View didn't return an HttpResponse object. It returned None instead

前端 未结 3 826
轻奢々
轻奢々 2021-01-21 09:22

The view below is gives me the error when using the POST method. I\'m trying to load the model data into a form, allow the user to edit, and then update the database. When I try

3条回答
  •  广开言路
    2021-01-21 10:07

    You are redirecting if form.is_valid() but what about the form is invalid? There isn't any code that get's executed in this case? There's no code for that. When a function doesn't explicitly return a value, a caller that expects a return value is given None. Hence the error.

    You could try something like this:

    def edit(request, row_id):
        rating = get_object_or_404(Rating, pk=row_id)
        context = {'form': rating}
        if request.method == "POST":
            form = RatingForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect('home.html')
            else :
                return render(request, 'ratings/entry_def.html', 
                              {'form': form})
        else:
            return render(
                request,
                'ratings/entry_def.html',
                context
            )
    

    This will result in the form being displayed again to the user and if you have coded your template correctly it will show which fields are invalid.

提交回复
热议问题