“视图没有返回 HttpResponse 对象。而是返回了 None。”

Posted

技术标签:

【中文标题】“视图没有返回 HttpResponse 对象。而是返回了 None。”【英文标题】:"The view didn't return an HttpResponse object. It returned None instead." 【发布时间】:2019-11-27 02:50:41 【问题描述】:

“视图没有返回 HttpResponse 对象,而是返回了 None。”

“我正在使用 python django 开发考试应用程序,但是在本地主机上运行时登录视图功能出错,我该如何解决这个问题?”

在views.py 中显示错误的以下loginview 类

class LoginView(FormView):
    form_class = AuthenticationForm
    template_name = 'exam/login.html'
    def form_valid(self, form):
    username = form.cleaned_data['username']
    password = form.cleaned_data['password']
    user = authenticate(username  = username, password = password)
    if user is not None and user.is_active:
        login(self.request, user)
        if user.role == 2:
            return redirect("student")
        elif user.role == 3:
            return redirect("index")
    else:
        return self.form_invalid(form)`

错误显示是: /login/处的ValueError

The view exam.views.LoginView didn't return an HttpResponse 
object. It returned None instead.

用户角色已设置,请参考附件 ` 从 django.db 导入模型

# Create your models here.
from datetime import datetime, timedelta

from django.contrib.auth.models import AbstractBaseUser, 
BaseUserManager, PermissionsMixin

class UserManager(BaseUserManager):
    def create_user(self, email, password, **kwargs):

    if not email or not password:
        raise ValueError("User must have email and password")

    user = self.model(
        email=UserManager.normalize_email(email),
        **kwargs
    )

    user.set_password(password)
    user.save()

    return user

def create_superuser(self, email, password, **kwargs):
    user = self.create_user(email, password, **kwargs)
    user.is_superuser = True
    user.is_staff = True
    user.role = 1
    user.save()
    return user


class User(AbstractBaseUser, PermissionsMixin):
SUPER_ADMIN = 1
STUDENT = 2
TEACHER = 3
ROLE_CHOICES = (
    (STUDENT, 'Student'),
    (SUPER_ADMIN, 'Super Admin'),
    (TEACHER , 'Teacher'),
)
first_name = models.CharField(max_length = 100, null = False)
last_name = models.CharField(max_length = 100, null = False)
email = models.EmailField(null=False, unique=True)
is_active = models.BooleanField(default=True)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
is_staff = models.BooleanField(default=False)
role = models.SmallIntegerField(choices = ROLE_CHOICES, null = True)
objects = UserManager()
USERNAME_FIELD = 'email'
def get_full_name(self):
    return self.first_name + " " + self.last_name
def get_short_name(self):
    return self.first_name

class Section(models.Model):
section = models.CharField(max_length = 100)

def __str__(self):
    return str(self.section)

class Question(models.Model):
section = models.ForeignKey(Section, on_delete = models.CASCADE, null = True)
question = models.CharField(max_length = 200)

def __str__(self):
    return str(self.question)

class Choice(models.Model):
question = models.ForeignKey(Question,max_length = 200, on_delete = models.CASCADE)
choice = models.CharField(max_length = 200)

def __str__(self):
    return str(self.choice) 

class Exam(models.Model):
name = models.CharField(max_length = 200)
start_date = models.DateTimeField()
duration = models.IntegerField()
section = models.ManyToManyField(Section)

def __str__(self):
    return str(self.name)

`

【问题讨论】:

如果用户角色不是 2 或 3 怎么办? 但请注意,这段代码大部分是没有意义的; AuthenticationForm 已经对用户进行了身份验证,这就是重点。 你能再检查一下我添加了models.py文件吗 您不需要发布模型。您需要考虑如果用户角色为 1 会发生什么。 【参考方案1】:

尝试在def form_valid(self, form) 函数中将return self.form_invalid(form) 更改为return super().form_valid(form)。我认为您正在调用自己的函数,而不是 FormView 类一。还要在后面添加else

if user.role == 2:
    return redirect("student")
elif user.role == 3:
    return redirect("index")

带有重定向功能(可以是raise Http404)。

【讨论】:

以上是关于“视图没有返回 HttpResponse 对象。而是返回了 None。”的主要内容,如果未能解决你的问题,请参考以下文章