Django说“没有返回HttpResponse对象。它没有返回任何结果。”

2024-10-01 07:50:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在寻找解决方案,但没有一个能帮到我。大多数解决方案都与缩进有关,但我认为我的不是。如果有人能帮我解决这个问题,我会很感激的!在

以下是我所拥有的:

模型.py

from django.db import models

class QuestionPost(models.Model):
    question = models.CharField(max_length=1000)
    tag = models.CharField(max_length=200)
    pub_date = models.DateTimeField('Date published')


class AnswerPost(models.Model):
    answer_text = models.CharField(max_length=1000)
    answer_rate = models.IntegerField()

表单.py

^{pr2}$

视图.py

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from .forms import QuestionPostForm
from .models import QuestionPost
from django.template import RequestContext

# Create your views here.

def get_question(request):
    if request.method == 'POST':
        form = QuestionPostForm(request.POST)
        if form.is_valid():
            obj = QuestionPost()
            obj.question = form.cleaned_data['question']
            obj.tag = form.cleaned_data['tag']
            obj.save()
            return HttpResponseRedirect('forum/index.html',{'form':form})

        else:
            form = QuestionPostForm()
        return render_to_response(request, 'forum/index.html', {'form': form})

为什么我得到错误:没有返回HttpResponse对象。它没有返回任何结果?我不明白?我是Django的初学者,这将帮助我学到一些东西。。在


Tags: djangofrompyimportformobjmodelsrequest
2条回答

现在请确认,在get请求中您没有返回任何内容

def get_question(request):
    if request.method == 'POST':
        form = QuestionPostForm(request.POST)
        if form.is_valid():
            obj = QuestionPost()
            obj.question = form.cleaned_data['question']
            obj.tag = form.cleaned_data['tag']
            obj.save()
            return HttpResponseRedirect('forum/index.html',{'form':form})

    else:
        form = QuestionPostForm()
    return render_to_response(request, 'forum/index.html', {'form': form})

您没有考虑到请求的动词不是POST的情况,在这种情况下,函数get_question将为没有显式return:None的函数返回默认值。这就是为什么在函数式语言(如ML和{})中始终结合使用if和{}是非常重要的,这有助于您更好地理解程序的数据流。在

相关问题 更多 >