44π
Careful, self.model._meta.fields are not necessarily the same fields that CustomAdmin has!
βAll fields of the Adminβ would look more like this:
from django.contrib import admin
from django.contrib.admin.utils import flatten_fieldsets
class CustomAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
if request.user.is_superuser:
return self.readonly_fields
if self.declared_fieldsets:
return flatten_fieldsets(self.declared_fieldsets)
else:
return list(set(
[field.name for field in self.opts.local_fields] +
[field.name for field in self.opts.local_many_to_many]
))
73π
Since django 2.1, you can prevent editing, while allowing viewing, by returning False
from the ModelAdmin
βs has_change_permission
method, like this:
class CustomAdmin(admin.ModelAdmin):
def has_change_permission(self, request, obj=None):
return False
(This will not work before django 2.1, as it will also deny permission to any user trying only to view.)
- [Django]-Problems extend change_form.html in django admin
- [Django]-How do I create sub-applications in Django?
- [Django]-Django REST Framework upload image: "The submitted data was not a file"
27π
Ok, now thereβs this:
class CustomAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
# ...
return [f.name for f in self.model._meta.fields]
Still looking for a less ugly way.
- [Django]-What is a django.utils.functional.__proxy__ object and what it helps with?
- [Django]-Django: Where to put helper functions?
- [Django]-Sending JSON using the django test client
12π
You could iterate through the model meta fields:
def get_readonly_fields(self, request, obj=None):
if obj:
self.readonly_fields = [field.name for field in obj.__class__._meta.fields]
return self.readonly_fields
- [Django]-Homepage login form Django
- [Django]-Get the list of checkbox post in django views
- [Django]-Generics vs viewset in django rest framework, how to prefer which one to use?
6π
For Inlines (Tab or Stack)
def get_readonly_fields(self, request, obj=None):
fields = []
for field in self.model._meta.get_all_field_names():
if field != 'id':
fields.append(field)
return fields
def has_add_permission(self, request):
return False
- [Django]-Can I access constants in settings.py from templates in Django?
- [Django]-How do I access the request object or any other variable in a form's clean() method?
- [Django]-CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False
4π
This worked for me with Django 1.10
def get_readonly_fields(self, request, obj=None):
if request.user.is_superuser:
return self.readonly_fields
return list(set(
[field.name for field in self.opts.local_fields] +
[field.name for field in self.opts.local_many_to_many]
))
- [Django]-Fields.E304 Reverse accessor clashes in Django
- [Django]-How to add custom search box in Django-admin?
- [Django]-ImportError: Failed to import test module:
4π
If someone still lookign for better way, you can use it like this:
@admin.register(ClassName)
class ClassNameAdmin(admin.ModelAdmin):
readonly_fields = [field.name for field in ClassName._meta.fields]
ClassName is your Model class.
- [Django]-"Too many values to unpack" Exception
- [Django]-Django "You have unapplied migrations". Which ones?
- [Django]-Uwsgi installation error in windows 7
0π
My requirement was similar . I needed only one field to be shown as read-only . And this worked fine:
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 1
fields = ['choice_text', 'votes']
readonly_fields = ['votes']
class QuestionAdmin(admin.ModelAdmin):
#fields = ['pub_date', 'question_text']
fieldsets = [
(None, {'fields': ['question_text']}),
('Date Information', {'fields': ['pub_date']}),
]
search_fields = ['question_text']
inlines = [ChoiceInline]
Refer: C:\Python27\Lib\site-packages\django\contrib\admin\options.py
- [Django]-Difference between different ways to create celery task
- [Django]-How to have a Python script for a Django app that accesses models without using the manage.py shell?
- [Django]-Django get objects not referenced by foreign key
0π
Say you have defined user_mode as;
Admin, Customers and Staff
If youβd like to deny a staff (and of course, customers) the privilege of deleting a customer, product, order etcβ¦
Your code goes;
def get_readonly_fields(self, request: HttpRequest, obj=None):
if request.user.user_mode != "Admin":
return self.readonly_fields + ['user_mode']
return super().get_readonly_fields(request, obj)
where user_mode = a model field holding the type of user.
N.B: my code uses "Pylance" (like typescript in JS)
- [Django]-React Error: Target Container is not a DOM Element
- [Django]-Django dynamic forms β on-the-fly field population?
- [Django]-How to check (in template) if user belongs to a group
-1π
With get_fieldsets you get all fields from the form
def get_readonly_fields(self, request, obj=None):
readonly = []
for fs in self.get_fieldsets(request, obj):
if len(fs) > 1:
readonly += fs[1].get('fields', [])
return readonly
- [Django]-Django β why is the request.POST object immutable?
- [Django]-How can I use redis with Django?
- [Django]-Multiple annotate Sum terms yields inflated answer
-1π
@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
...
readonly_fields = ["father", "mother", "spouse"]
reference :
https://books.agiliq.com/projects/django-admin-cookbook/en/latest/changeview_readonly.html
- [Django]-Login Page by using django forms
- [Django]-What's the best way to store a phone number in Django models?
- [Django]-How to combine django "prefetch_related" and "values" methods?