Stalfurion
Stalfurion

Reputation: 31

Multiple types of users

I am writing a django web app that models an application where hospital staff and patients can login. The patients, nurses, and doctors all have different permissions and the models need to store different information. I am currently trying to create a user profile model that holds all the common fields, and then create separate models for each type of employee that each have a oneToOneField(UserProfile) attribute. I was wondering how I could tell which type of user was logged in from my views.py file. For example, is it possible to do something like:

    if request.user.is_patient():
        show patient form
    elif request.user.is_doctor:
        show doctor form

Here is what I have in models.py so far:

class BaseUser(models.Model):
    user = models.OneToOneField(User)
    username = models.CharField(max_length=30)
    firstName = models.CharField(max_length=50)
    middleName = models.CharField(max_length=50)
    lastName = models.CharField(max_length=50)
    sex = models.CharField(max_length=10)
    address = models.CharField(max_length=200)
    email = models.CharField(max_length=50)
    phone = models.CharField(max_length=10)

User.profile = property(lambda u: BaseUser.objects.get_or_create(user=u)[0])

class PatientUser(models.Model):
    user = models.OneToOneField(BaseUser)
    existingConditions = models.TextField()
    prescriptions = models.TextField()

Upvotes: 1

Views: 464

Answers (1)

Alvaro
Alvaro

Reputation: 12037

Well, since you have created a custom BaseUser model, you could set up a set of properties in that class to identify it.

This is a rough example that you could use to test in the view the nature of the user:

class BaseUser(models.Model):
    def is_patient(self):
        try:
            self.patientuser
        except PatientUser.DoesNotExist:
            return False
        else:
            return True

    def is_doctor(self):
        try:
            self.doctoruser
        except DoctorUser.DoesNotExist:
            return False
        else:
            return True

Then, in your view, you could simply:

if request.user.baseuser.is_doctor():
    show doctor form
elif request.user.baseuser.is_patient():
    show patient form

To ensure that your users have a baseuser associated, you can take a look at the post-save signal for the User model. You can check how to register actions for these signals here.

Here is a very simple example on how to do this:

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User


@receiver(pre_save, sender=User)
def my_handler(sender, **kwargs): 
    BaseUser.objects.create(user=sender, ...)

Upvotes: 1

Related Questions