Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple User Types In Django

Tags:

python

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.
like image 239
Focus Ifeanyi Avatar asked Mar 15 '26 22:03

Focus Ifeanyi


2 Answers

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()
like image 199
m.antkowicz Avatar answered Mar 17 '26 12:03

m.antkowicz


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.

like image 27
Fadil Olamyy Wahab Avatar answered Mar 17 '26 12:03

Fadil Olamyy Wahab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!