视图未返回HttpResponse对象

时间:2013-09-13 15:43:57

标签: python django

我在linux上使用django来建立一个注册网站。它无法运行!!

错误讯息:     视图blog.views.register未返回HttpResponse对象。

models.py

from django.db import models
class User(models.Model):
        username = models.CharField(max_length = 20)
        headImg  = models.FileField(upload_to = './upload/')
        def __unicode__(self):
                return self.username

views.py

class UserForm(forms.Form):
        username = forms.CharField()
        headImg  = forms.FileField()

def register(req): 
        if req.method == "POST":
                uf = UserForm(req.POST)
                if uf.is_valid():
                        print uf.cleaned_data['username']
                        print uf.cleaned_data['headImg'].name
                        user = User()
                        user.username = uf.cleaned_data['username']
                        user.headImg  = uf.cleaned_data['headImg']
                        user.save()
                        return HttpResponse('ok') 
        else:
                uf = UserForm()
                return render_to_response('register.html',{'uf':uf})

2 个答案:

答案 0 :(得分:2)

您需要减少最后一行的缩进。这应该是它不是POST的情况,,当它是一个POST,但表单无效时。

答案 1 :(得分:-1)

def register(req): 
        if req.method == "POST":
                uf = UserForm(req.POST)
                if uf.is_valid():
                        ....
                        return HttpResponse('ok') 
                # If control flow is reach here, nothing is returned.
        else:
                uf = UserForm()
                return render_to_response('register.html',{'uf':uf})

如果发出无效的POST请求,则视图将不返回任何内容。 (隐含无)

请尝试以下操作:

def register(req): 
    if req.method == "POST":
        uf = UserForm(req.POST)
        if uf.is_valid():
            ....
            return HttpResponse('ok') 
    uf = UserForm()
    return render_to_response('register.html',{'uf':uf})