Django exclude field in admin if creator of this object is request user
<p>How can I exclude a field from the Django admin if the creator of this object is current user. Is there any way to customise my model in <code>admin.py</code>?</p>

<pre><code>class Toys(BaseModel):
    name = models.CharField(max_length=255)
    tags = models.ManyToManyField(Tag, related_name='Item_tags')
    price = models.CharField(max_length=255)
    status = models.BooleanField(default=False)
</code></pre>

<p>First, you need to add a field to your model to store the creator.</p>

<pre><code>class Toys(BaseModel):
    creator = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    tags = models.ManyToManyField(Tag, related_name='Item_tags')
    price = models.CharField(max_length=255)
    status = models.BooleanField(default=False)
</code></pre>

<p>The override the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_fields" rel="nofollow"><code>get_fields</code></a> method of your model admin.</p>

<pre><code>class ToyAdmin(admin.ModelAdmin):
    def get_fields(self, request, obj=None):
        fields = super(ToyAdmin, self).get_fields(request, obj)
        if obj is not None and request.user.is_authenticated():  # In Django 1.10+ use request.user.is_authenticated
            if obj.creator == request.user:
            fields = [f for f in fields if f != 'status']
        return fields
</code></pre>

<p>In Django 1.11+, you can use <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_exclude" rel="nofollow"><code>get_exclude</code></a> instead.</p>

<pre><code>class ToyAdmin(admin.ModelAdmin):
    def get_exclude(self, request, obj=None):
        if obj is not None and request.user.is_authenticated():  # In Django 1.10+ use request.user.is_authenticated
            if obj.creator == request.user:
                return ['status']
        else:
            return []
</code></pre>

python django django-admin