2๐
You can override the get_form()
method in the admin class to use a different form in the edit & create pages:
class ReadOnlyPkForm(ModelForm):
class Meta:
model = MyModel
exclude = ('myothermodel',)
class MyModelAdmin(ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
if obj: # Object intstance, so we're in edit page
# Override form, to use custom form
kwargs['form'] = ReadOnlyPkForm
return super(MyModelAdmin, self).get_form(request, obj, **kwargs)
The previous snippet would use the custom ReadOnlyPkForm
form โ which excludes the field โ when you attempt to edit an instance. The standard form (i.e. all model fields) without exclusion would be used when you attempt to create a new instance. You could further tweak ReadOnlyPkForm
through init if you wanted the field to appear as read-only (I just used exclude
to make the sample easier).
Note admin classes also have change_view()
and add_view()
methods that you could also use to override the forms in edit / create pages , but in my experience they are for more complex modifications (e.g. the underyling template) not to mention these two methods can have quirky behavior due to caching issues.
0๐
If I understand your question correctly would this work?
Disable link to edit object in django's admin (display list only)?
- [Answered ]-Accessing Django MEDIA_URL and MEDIA_ROOT setting.py values from ReactJS frontend
- [Answered ]-After installing django in virtual environment, still can't import module
- [Answered ]-Django: how to create a column whose default value is now()?