Thursday, 28 April 2022

Djang 4.04 admin pages and modifcations

 Django has default admin endpoint /admin/ and contains a list of UI for admin user to view models(tables), edit model rows(list), and add/change model rows.


The URL to access the django admin feature is 


https://docs.djangoproject.com/en/dev/ref/contrib/admin/#reversing-admin-urls


PageURL nameParameters
Changelist{{ app_label }}_{{ model_name }}_changelist 
Add{{ app_label }}_{{ model_name }}_add 
History{{ app_label }}_{{ model_name }}_historyobject_id
Delete{{ app_label }}_{{ model_name }}_deleteobject_id
Change{{ app_label }}_{{ model_name }}_changeobject_id

The UserAdmin provides a named URL:

PageURL nameParameters
Password changeauth_user_password_changeuser_id

These named URLs are registered with the application namespace admin, and with an instance namespace corresponding to the name of the Site instance.


For example 

        # /admin/core/user/1

        url = reverse('admin:core_user_change', args=[self.user.id])


To register model into admin, 

http://www.john-player.com/django/how-to-register-a-model-with-django-admin/

in admin.py


from django.contrib import admin

from .models import <modelname>


admin.site.register(<modelname>)


To change how the table will look like, create ur modelName class on top of admin.site.register like below :

class UserAdmin(BaseUserAdmin):

    # Set list view display

    ordering = ['id']

    list_display = ['email', 'name']


    # Set change view forum display fields

    fieldsets = (

        # First comma indicates the name of the field, second is fields

        (None, {'fields': ('email', 'password')}),

        (_('Personal Info'), {'fields': ('name',)}),

        (

            _('Permissions'),

            {'fields': ('is_active', 'is_staff', 'is_superuser')}

        ),

        (

            _('Important dates'),

            {'fields': ('last_login',)}

        ),

    )

    # set add view fields

    add_fieldsets = (

        # First part is title, secnd part is def

        (None,

            {

                'classes' : ('wide',),

                'fields': ('email', 'password1', 'password2')

            }

        ),

    )



# Add model to admin site UI so it can be displayed in admin site UI. When clicked, list view will be displyaed

admin.site.register(models.User, UserAdmin)


https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fieldsets





No comments:

Post a Comment