0

我在linux上使用django来建立一个注册网站。它不能工作!!

错误消息:视图 blog.views.register 没有返回 HttpResponse 对象。

模型.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

视图.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})
4

2 回答 2

2

您需要减少最后一行的缩进。这应该在它不是 POST 的情况下以及当它是 POST 但表单无效的情况下都被捕获。

于 2013-09-13T15:59:16.870 回答
-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})
于 2013-09-13T15:46:03.873 回答