Search code examples
pythondjangodjango-permissions

best way to implement privacy on each field in model django


I am trying to provide privacy settings at the model's field level for users. So a user can decide which data he wants to display and which data he wants to hide.

Example:

class Foo(models.Model):
    user = models.OneToOneField("auth.User")
    telephone_number = models.CharField(blank=True, null=True, max_length=10)
    image = models.ImageField(upload_to=get_photo_storage_path, null=True, blank=True)

I want to provide an option to the user to select the fields which he wants to display and which he doesn't. Consider a user doesn't want to display telephone_number, so he should have the option for that.

Which is the best way to approach this?


Solution

  • You can create a CommaSeparatedIntegerField field inside the model, and use it to store a list of field_names (Integers that denote a field_name) that the user wants to hide.

    You can create a mapping between the field_names and integers as a constant inside your models.py. And check whichever field_names are those the the user had checked.

    Example mapping:

    FIELD_NAME_CHOICES = (
        (1, Foo._meta.get_field('telephone_number')),
        (2, Foo._meta.get_field('name')),
        .
        .
    )
    

    Check the following link for reference https://docs.djangoproject.com/en/1.8/ref/models/fields/#commaseparatedintegerfield