Focus Ifeanyi
Focus Ifeanyi

Reputation: 57

Multiple User Types In Django

I am new to Django and trying to create an App with two User Types (Freelancers and Customers). I understand how to create a User profile Class and it works well for me:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    description = models.CharField(max_length=100, default='')
    country = models.CharField(max_length=100, default='')
    website = models.URLField(default='')
    phone = models.IntegerField(default=0)

def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = UserProfile.objects.create(user=kwargs['instance'])


post_save.connect(create_profile, sender=User)

This works well for me on a one user type user. But now I am building an app with 2 types of users (freelancers and customers), what is the best approach to get this done. Both users will have different view and info. Should I:

  1. Create 2 different apps, and repeat the normal registeration and login for each.
  2. If I do the above, hope the freelancers when logged in won't access customers view.
  3. How do I add user type to the user profile if I decide to use one app and model for it. Please I need a step by step beginner approach, or a link to relevant source. Thanks.

Upvotes: 3

Views: 3770

Answers (3)

Saad Mirza
Saad Mirza

Reputation: 1177

You Could Try extending the Default Django Auth User like this Create an App with Account or Whatever name you like , then in models.py write like below

class User(AbstractUser):
    is_head = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_public = models.BooleanField(default=False)

Add Auth Extended Model in Settings.py

AUTH_USER_MODEL = 'accounts.User'

Migrate your Account app and you are all set with Your User Extended Model.

Upvotes: 1

Fadil Olamyy Wahab
Fadil Olamyy Wahab

Reputation: 626

You could try this:

class UserProfile(models.Model):
    user = models.ForeignKey(User)
    #define general fields

class Freelancer(models.Model):
    profile = models.ForeignKey(UserProfile)
    #freelancer specific  fields

    class Meta:
        db_table = 'freelancer'

class Customers(models.Model):
    profile = models.ForeignKey(UserProfile)
    #customer specific fields 

   class Meta:
        db_table = 'customer'

You can then have as many Users as you want from the UserProfile.

Upvotes: 4

m.antkowicz
m.antkowicz

Reputation: 13571

You should need just use Groups Django mechanism - you need to create two groups freelancer and let say common and check whether user is in first or second group - then show him appropriate view

To check whether user is in group you can use

User.objects.filter(pk=userId, groups__name='freelancer').exists()

Upvotes: 5

Related Questions