I am trying to restrict users in groups from being able to change fields their group does not have permission to change. For example:
class StudentReferral(models.Model):
teacher = models.CharField(max_length=50)
referral_first_name = models.CharField(max_length=50)
referral_last_name = models.CharField(max_length=50)
accepted = models.BooleanField(blank=True)
Now the teachers are all in one user group and the person who accepts or declines the referral is in another user group. The teacher user group should only be able to edit the following fields: teacher, referral_first_name and referral_last_name. The other user group should only be able to edit the accepted field. Both groups should be able to see all of the fields.
Is there something built into django that makes this possible or a custom way of doing this?
Override
ModelAdmin.get_fieldsets, and do something like the following:EDIT
Sorry, I missed the bit about they should still be able to see all fields, just not edit them. I’ve left the original answer intact, as it might still be of use to you. For this, though, you’ll need to override
ModelAdmin.get_readonly_fields:I’m assuming here that the choices are only teacher or “other user”. If there’s other types to consider, or you don’t want the fields limited at all in one circumstance, you might want to remove the
readonly_fieldsattribute and replace it with something likeother_readonly_fields, and branch accordingly (the default value forreadonly_fieldsis only those fields that haveeditable=Falseon the model).Also, be aware that if a field is required, you can’t make it read-only as well. If some of these are required fields, you’ll need to override
ModelForm.__init__as well, to make them not required in the circumstances where they will be read-only, which requires some extra hackery (ModelFormdoesn’t have access torequest, normally):