How To Add Custom Views To Django Admin

How To Add Custom Views To Django Admin

how to add custom views to django admin without actually creating the database table? Let's talk about it. In *django admin * to get the url link in the admin we have to register the model but in some cases we just need the a url with some functionality under an application. We can implement it with a simple trick. To implement it we have to create a dummy model. It's just inherits the models.Model from django. It will not create any migrations/table. Now, create a ModelAdmin class to the dummy model that we have created, override the method get_urls and return the url paths like below and url name should match with the format "{app_label}_{model_name}__changelist". Now register the Dummy Model with Dummy Model Admin Class. Now, open thedjango admin there you can find the link with the name of your model. Check out the below code to know how to implement it.

admin.py

from django.contrib import admin
from django.http import HttpResponse
from django.urls import path

# my dummy model
class DummyModel(models.Model):

    class Meta:
        verbose_name_plural = 'Dummy Model'
        app_label = 'sample'

def my_custom_view(request):
    return HttpResponse('Admin Custom View')

class DummyModelAdmin(admin.ModelAdmin):
    model = DummyModel

    def get_urls(self):
        view_name = '{}_{}_changelist'.format(
            self.model._meta.app_label, self.model._meta.model_name)
        return [
            path('my_admin_path/', my_custom_view, name=view_name),
        ]
admin.site.register(DummyModel, DummyModelAdmin)

Above code is reference code that shows you how to implement *custom views to django admin*without actually creating the database table. You can find the reference project in my github account (https://github.com/AnjaneyuluBatta505/learnbatta/tree/master/django/django_admin_custom_view).