2

I have extended the django User model by adding a company field:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    company = models.ForeignKey(Companies, on_delete=models.CASCADE, null=True, blank=True)

Now assume another model that holds data across companies:

class Product(models.Model):
    name = models.CharField(max_length=256, null=True, blank=True)
    tags = TaggableManager(blank=True)
    company = models.ForeignKey(Companies, on_delete=models.CASCADE, null=True, blank=True, editable = False)

Note that the company field here is not editable, as I have overridden save_model(), to get users' company field from their profiles:

class ProductAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        if getattr(obj, 'company', None) is None:
            obj.company = request.user.profile.company
        obj.save()

How can I go about creating custom permissions based on user profile fields (e.g. company)?

Sample permissions requirements:

  1. Users should only be able to edit product fields related to their own company.
  2. Users should be able to create new users only with their company in the new user's profile field

Thanks in advance

fekioh
  • 894
  • 2
  • 9
  • 22

0 Answers0