[Django]-RelatedObjectDoesNotExist Exception

3👍

You could set a related_name to the field user in the Student, Teacher tables like this,

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

Also, you need to make sure that for a user , the corresponding student, parent, model is created.

Also, you are checking the prefix to an upper case letter, where in your model they are lower case. Python is strictly case-sensitive.

I think you need to change the if statement too,

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')

Because, the way in your view, every if statement is encountered during the view. Then if the user is Teacher, then it has no student object. Then, Django raises error. So better is to use a try-except combination for the purpose.

Also, from your code, I came up with a suggestion about Student, Teacher, Parent models.
You could use a single Model Profile, with two flags is_teacher, is_parent and a default null ForeignKey field, which is set only if the is_parent flag is True, rather than repeatedly creating tables in the database.
But, this is only a suggestion, as in your approach the Student, Teacher, Parent can be distinguished easily, though it takes up more storage space.

Leave a comment