django - RelatedObjectDoesNotExist 异常

标签 django django-models django-views

我尝试定义登录用户的前缀,但出现此异常 RelatedObjectDoesNotExist。问题是 django 找不到用户 Student 和 Parent(异常值:User has no student)

我想根据用户的类型渲染不同的模板

模型.py

from django.db import models
from django.contrib.auth.models import User


# Create your models here.


class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    prefix = 't'

    def __str__(self):
        return self.user.first_name + ' ' + self.user.last_name


class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    parent = models.ForeignKey('Parent', null=True)
    prefix = 's'

    def __str__(self):
        return self.user.first_name + ' ' + self.user.last_name


class Parent(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    prefix = 'p'

    def __str__(self):
        return self.user.first_name + ' ' + self.user.last_name

View .py

def sign_in(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user_login = User.objects.get(username=username)
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user_login)
            if user_login.student.prefix == 'S':
                return render(request, 's.html')
            if user_login.teacher.prefix == 'T':
                return render(request, 't.html')
            if user_login.parent.prefix == 'P':
                return render(request, 'p.html')
        else:
            return render(request, 'index.html', {'error': True})
    else:
        return render(request, 'index.html')
System check identified no issues (0 silenced).
May 20, 2017 - 21:43:51
Django version 1.11.1, using settings 'e_diary.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[20/May/2017 21:43:56] "GET / HTTP/1.1" 200 983
Internal Server Error: /sign_in/
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\USER\Desktop\e_diary\electronic_diary\views.py", line 29, in sign_in
    if user_login.teacher.prefix == 'T':
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 406, in __get__
    self.related.get_accessor_name()
django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: User has no teacher.
[20/May/2017 21:44:02] "POST /sign_in/ HTTP/1.1" 500 70872

最佳答案

你可以像这样在 Student, Teacher 表中给 user 字段设置一个 related_name,

user = models.OneToOneField(User, related_name='student')

此外,您需要确保为用户创建了相应的学生、家长、模型。

此外,您正在检查大写字母的前缀,而在您的模型中它们是小写的。 Python 严格区分大小写。

我认为您也需要更改 if 语句,

try:
    if user_login.student.prefix == 'S'
        return render(request, 's.html')
except:
    try:
        if user_login.teacher.prefix == 'T'
            return render(request, 't.html')
    except:
        if user_login.parent.prefix == 'P':
            return render(request, 'p.html')

因为在您的 View 中,每个if 语句 都会在 View 中遇到。那么如果用户是Teacher,那么它就没有student对象。然后,Django 引发错误。因此,更好的做法是为此目的使用 try-except 组合。

此外,根据您的代码,我提出了关于学生、教师、家长模型的建议。 您可以使用具有两个标志 is_teacher、is_parent 和默认空 ForeignKey 字段的单个模型配置文件,该字段仅在 is_parent 标志为 True 时设置,而不是在数据库中重复创建表。 但是,这只是一个建议,因为在您的方法中,Student,Teacher,Parent 很容易区分,尽管它会占用更多的存储空间。

关于django - RelatedObjectDoesNotExist 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44086746/

相关文章:

python - 如何通过 id 连接两个模型(没有外键)并按管理中的链接模型字段排序

python - 按高度/方向对图像进行排序

python - html中的csrf token ,但无法设置cookie

python - setup.py 引入非 Python github 存储库并将它们放在正确的目录中?

python - 如何在 intellij python-project 中为 Django 设置源文件夹? (Python 插件)

python - 反向 'update' 关键字参数 '{' id' : '' }' not found. 1 pattern(s) tried: [' update/(? P<id>[0-9]+)/\\Z']

python - 为什么 django 中没有定义名称 'self' 即使包含 self

python - pip-3.3 安装 MySQL-python

python - Django Rest Framework SerializerMethodField 传递额外参数

python - Django:禁用生产中的初始系统检查?