Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to have a field that only the superuser can add/edit?

Is there a way to have a field that only the superuser can add/edit?

class ProductPage(Page):
    price = models.IntegerField(blank=True)
    description = RichTextField(blank=True)
    featured = models.BooleanField(default=False)

Above is part of my model but i only want the superuser to access the featured field.

like image 943
Lendl Smith Avatar asked Jan 22 '26 04:01

Lendl Smith


2 Answers

I'm assuming you mean that only superusers logged in the Django admin site should be able to edit the featured field. If you want to restrict access in your own forms and views, you just need to check the user's status and customize the form/view accordingly. Here's what you can do in admin.py, in your ModelAdmin:

def get_readonly_fields(self, request):
    fields = super().get_readonly_fields(request)
    if not request.user.is_superuser:
        fields.append('featured')
    return fields
like image 61
dirkgroten Avatar answered Jan 23 '26 20:01

dirkgroten


I tried out the solution given by @dirkgroten but had to make a few changes to make it work.

According to the Django Documentation for >2.1 versions of Django, the get_readonly_fields take 3 parameters.

Also, fields need to set a list to append, as it creates a tuple on default.

def get_readonly_fields(self, request, obj=None):
    fields = list(super().get_readonly_fields(request))
    if not request.user.is_superuser:
        fields.append('featured')
    return fields
like image 45
aswinshenoy Avatar answered Jan 23 '26 21:01

aswinshenoy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!