Note that there are some explanatory texts on larger screens.

plurals
  1. POUnderstanding django admin readonly_fields
    primarykey
    data
    text
    <p>I created some code to differentiate between two usergroups in Django admin, resulting in showing all fields readonly or only some of them, which are set directly in the ModelAdmin class.</p> <p>At first here is the code:</p> <pre><code>class PersonAdmin(admin.ModelAdmin): readonly_fields = ('created_at','created_by',) def get_form(self, request, obj=None, **kwargs): if obj: # we are in edit mode if request.user.is_superuser: self.readonly_fields = () else: for group in request.user.groups.all(): if str(group) == 'readonlyuser': allfields = tuple(obj._meta.get_all_field_names()) self.readonly_fields = allfields return super(PersonAdmin, self).get_form(request, obj, **kwargs) </code></pre> <p>I divide between the groups and set the fields accordingly. Everything works fine if users from the two groups are not logged in at the same time! <strong>After a 'readonly' user logged in, the adminuser will get all fields readonly too.</strong></p> <p>My inspections provided a solution also: If I put an additional if statement for the adminuser within the <em>for</em> block everything works as expected.</p> <pre><code>if str(group) == 'adminuser': self.readonly_fields = PersonAdmin.readonly_fields </code></pre> <p>Why is that and what's happening there?</p> <p>I have no special cache settings made and it happens on the dev server as well as on an Apache with WSGI.</p> <p>From my understanding request.user.groups.all() should return all groups the <em>currently logged in</em> user belongs to. Where does Django get the allfields (readonly) from, if another user on a different IP and session match this if block?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload