2017-05-28 110 views
0

我一直在尋找解決方案,但沒有人幫助過我。大多數解決方案都與縮進相關,但我認爲我的不是。當有人能幫助我解決這個問題時,我會很感激!Django說「沒有返回HttpResponse對象,它返回None」。

這裏是我有:

models.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() 

forms.py

from django import forms 

# Create your models here. 

class QuestionPostForm(forms.Form): 
    question = forms.CharField(label='Question text', max_length=1000) 
    tag = forms.CharField(label='Tags', max_length=200) 
    pub_date = forms.DateTimeField(label='Date published') 


class AnswerPostForm(forms.Form): 
    answer_text = forms.CharField(label='Answer Text', max_length=1000) 
    answer_rate = forms.IntegerField(label='Rate') 

views.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對象。它返回None而不是?我不明白?我是Django的初學者,這會幫助我學到一些東西。

+1

這是當請求不是POST會發生什麼;將返回默認的'None'。 –

+0

標記正確,如果您發現此答案正確:) – Sagar

回答

4

請立即檢查,在用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}) 
0

你沒有預料到請求的動詞不是POST的情況,在這種情況下,功能get_question將返回沒有明確的returnNone。這就是爲什麼總是使用ifelse結合使用功能性語言的一些重要原因,例如MLHaskell這些都是必需的,根據我的經驗,它可以幫助您更好地理解程序的數據流。

相關問題