Add a View to index.html

Learn how to add a custom view to the index.html file.

Adding a view to index.html

Now to complete the Advance Customisation lesson you will proceed to add a new view to your my_index.html file.

Consider the case where you would like to link a new view with the text “My custom view” on your main Django page. To do this, you will modify your my_index.html file and add this item.

<div class="col-lg-6">
   <div class="card-header py-3 card shadow mb-4 border border-primary">
      <a href="/admin/my_view">My custom view </a>
   </div>
   {% include "admin/app_list.html" with app_list=app_list show_changelinks=True %}
</div>

Now, you will modify your admin to deal with this view.

You will need to declare this new URL /admin/my_view. To do so you can override the get_urls method of the admin

class MyUltimateAdminSite(AdminSite):
    site_header = 'My Django Admin Ultimate Guide'
    site_title = 'My Django Admin Ultimate Guide Administration'
    index_title = 'Welcome to sample_app'
    index_templacate = 'sample_app/templates/admin/my_index.html'
    login_template = 'sample_app/templates/admin/login.html'

	def get_urls(self):
		urls = super(MyUltimateAdminSite, self).get_urls()
		custom_urls = [
		    path('my_view/', self.admin_view(self.my_view), name="my_view"),
		]
		return custom_urls + urls

Then you will write the code for your new view.

def my_view(self, request):
	# your business code
	context = dict(
		self.each_context(request),
		welcome="Welcome to my new view",
	)
	return TemplateResponse(request, "admin/sample_app/custom_view.html", context)

In this view, you can do your business logic, add your results (if any) to the context, and return the template of your page. The content of the HTML file for the new custom_view.html page will look something like this:

{% extends "admin/base_site.html" %}
{% block content %}
<div class="card" style="width: 18rem;">
<img src="..." class="card-img-top" alt="...">
<div class="card-body">
<h3 class="card-title"> {{welcome}} </h3>
<p class="card-text" >An example of a custom view.</p>
<a href="#" class="btn btn-primary" style="color:white">
	Go somewhere
</a>
</div>

The final results will look something like what can been seen below and if you click on “My custom view” then it will take you to the custom_view.html page.

Get hands-on with 1400+ tech skills courses.