Thursday, June 24, 2021

Django Registering Model Admin

To change how a model is displayed in the admin interface you define a ModelAdmin class (which describes the layout) and register it with the model.


From the below line, to specify custom information for the model 

admin.site.register(Author)


below line to be placed 

# Define the admin class

class AuthorAdmin(admin.ModelAdmin):

    pass


# Register the admin class with the associated model

admin.site.register(Author, AuthorAdmin)




class AuthorAdmin(admin.ModelAdmin):

    list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')



The above will actually specify last name, first name, DOB, DOD 



Organize detail view layout


By default, the detail views lay out all fields vertically, in their order of declaration in the model. You can change the order of declaration, which fields are displayed (or excluded), whether sections are used to organize the information, whether fields are displayed horizontally or vertically, and even what edit widgets are used in the admin forms.


class AuthorAdmin(admin.ModelAdmin):

    list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')

    fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]



The fields attribute lists just those fields that are to be displayed on the form, in order. Fields are displayed vertically by default, but will display horizontally if you further group them in a tuple (as shown in the "date" fields above).






References:

https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Admin_site#register_a_modeladmin_class

No comments:

Post a Comment