user9092892
user9092892

Reputation:

How to display different custom users after logging in Django

I have 2 custom users, student and teacher. I want that if student is logged in, a particular message is displayed, otherwise if teacher is logged in, another message to show.

 {% if request.user.is_authenticated %}
            {% if user is student %}
                <p>Welcome, {{ user.student.surname }} Thanks for logging in.</p>
                {% else %}
                {% if user is teacher%}
                <p>Welcome, {{ user.teacher.surname }} Thanks for logging in.</p>
            {% endif %}
        {% endif %}
class User(AbstractUser):
    pass


class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    name = models.CharField(max_length=30, null=True, blank=True, default=None)
    surname = models.CharField(max_length=50, null=True, blank=True, default=None)

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    name = models.CharField(max_length=30, null=True, blank=True, default=None)
    surname = models.CharField(max_length=50, null=True, blank=True, default=None)
    email = models.EmailField(unique=True, null=True, blank=True, default=None)


User.student = property(lambda p: Student.objects.get_or_create(user=p)[0])
User.teacher = property(lambda p: Teacher.objects.get_or_create(user=p)[0])

Upvotes: 0

Views: 191

Answers (1)

Daniel Konovalenko
Daniel Konovalenko

Reputation: 1289

First, I believe it's not a really good idea to have user.teacher and user.student as a property for two reasons:
1. I assume that a user can be either a student or a teacher, but not both (please correct me if I'm mistaken). You are using get_or_create, so, for instance, if you'll try to access a user teacher property with user being already a student, you will end up in the situation when the user is both a student and a teacher.
2. Django ORM already does this for you: using OneToOneField you can reference Teacher or Student object from your User object as user.teacher or user.student as long as the corresponding User or Teacher exists.

You can use hasattr to check if the given user is a teacher or a student:

class User(AbstractUser):
     @property
     def is_teacher(self):
          return hasattr(self, 'teacher')
     @property
     def is_student(self):
          return hasattr(self, 'student')

Then render your template accordingly:

{% if user.is_teacher %}
    # Do teacher-related logic
{% elif user.is_student %}
    # Do student-related logic
{% else %}
    # This should not be the case, but you may want to display an error message or something
{% endif %}

Upvotes: 2

Related Questions