Search code examples
pythondjangoauthenticationone-to-one

Use is_authenticated using OneToOneField relation with User


I have built a model which have a OneToOne relation with the User object in Django like this :

class Student(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)

But in the HTML file, the filter {% if user.student.is_authenticated %} does not work but the filter {% if user.is_authenticated %} works. I thought that the Student class inherits the attributes from the User class.

Is there an other possibility to create custom users from the User class with the possibility to use {% if user.student.is_authenticated %} ? I want also to have the possibility to use for example {% if user.teacher.is_authenticated %}.


Solution

  • I thought that the Student class inherits the attributes from the User class.

    No, it does not inherit, these are just two models (tables) where one of the tables refers to the others by specifying the primary key.

    You thus check this with:

    {% if user.is_authenticated %}
        …
    {% endif %}

    or if you want to know whether the user of a student is authenticated, you can work with:

    {% if mystudent.user.is_authenticated %}
        …
    {% endif %}