Register models in Django admin(Django admin model class)

Register models in Django admin

Hello Techies,

This blog is about, how to register models in Django admin. In my previous blog, I have covered all the basic things about the Django admin panel like how to create superuser, how to change Django admin panel header and site name, etc. So in this blog, we will check how to register models in Django admin with example.

Prerequisites

Before starting to developing this project first install the below things:

  • Python Installation
  • Virtual Environment Installation
  • Django installation and create the Django project

See our previous blog for guidance on the same requirement.

So I’m creating Blog based project where we will handle all the CRUD-related operations from the Admin panel and at the frontend will list down all blog content.

Register models in Django admin: Step By Step

Create App

To create an app in Django use the below command.

python manage.py startapp blog

After this step, add the blog app in the INSTALLED_APPS section in the settings.py file. After that, run the migrations to create those applications models mapped tables in the backend database.

Add blog app in Installed_Apps

# settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog'
]

Let’s create an app in models.py file

# blog/model.py

from django.contrib import admin
from django.db import models
from django.utils import timezone


class Blog(models.Model):
    class Meta:
        db_table = 'blog'

    options = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )

    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=150)
    slug = models.SlugField(max_length=100, unique=True)
    content = models.TextField()
    excerpt = models.TextField()
    published_at = models.DateTimeField(default=timezone.now)
    status = models.CharField(max_length=10, default='draft'
, choices=options)
    author = models.CharField(max_length=500)

Below are the commands to run migrations.

> python manage.py makemigrations blog

> python manage.py migrate

Now our table is migrated to the main database. Now we will register the blog model class to Django admin in the blog(app_name)/admin.py file.

Before registering the model to the admin panel

Below is the code to register the model in Django admin.

from django.contrib import admin

# Register your models here.

from .models import Blog

admin.site.register(Blog)

After registering the model to the admin panel

Register models in Django admin (Blog)

You can add multiple records to a blog table using the Change button.


If you see a list of blogs here, it is not user friendly. This blog is showing objects instead of details.

Register models in Django admin (Object View)

To make this model objects user friendly, we can change the definition of model class in the blog/model.py file. Add the __str__ function to your model and return the details you want to show in the list view.

from django.contrib import admin
from django.db import models
from django.utils import timezone


class Blog(models.Model):
    class Meta:
        db_table = 'blog'

    options = (('draft', 'Draft'), ('published', 'Published'))

    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=150)
    slug = models.SlugField(max_length=100, unique=True)
    content = models.TextField()
    excerpt = models.TextField()
    published_at = models.DateTimeField(default=timezone.now)
    status = models.CharField(max_length=10, default='draft', choices=options)
    author = models.CharField(max_length=500)

    def __str__(self):
        return self.title + ', ' + str(self.published_at) + ', ' + self.status + ', ' + self.author

After adding the above code. You will get the following results.

Register models in Django admin (String Format)

ModelAdmin Class in Django (Register models in Django admin)

  • The ModelAdmin class is the representation of a model in the Django admin interface.
  • To show the table’s all data in the admin interface we have to create a ModelAdmin class in the admin.py file of the Application folder.

Syntax for creating class:

class ModelAdminClassName(admin.ModelAdmin):
    list_display=('field1', 'field2', ....)

Register the above-created class:

admin.site.register(ModelClassName, ModelAdminClassName)

list_display:

Set list_display to control which field is displayed on the change list page of the admin. If you don’t set list_display, by default it will display a single column that displays the __str__() representation of each object.

We can add 4 different types of value in list_display.

  • The name of a model field.
  • A callable that accepts one argument, and the model instance.
  • A string representing a ModelAdmin method that accepts an argument, and the model instance.
  • A string representing an attribute or method (without any required arguments).

For the proper list, view add the below code.

# blog/admin.py

from django.contrib import admin

# Register your models here.

from .models import Blog


class BlogAdmin(admin.ModelAdmin):
    list_display = ('title', 'published_at', 'status', 'author')

admin.site.register(Blog, BlogAdmin)

Register model by Decorator (Register models in Django admin)

A decorator can be used to register ModelAdmin Classes.

Syntax:

@admin.register(ModelClassName1,ModelClassName2,...site=custom_admin_site)

Resgister the model class:

@admin.register(ModelClassName)

Creating a Class:

class ModelAdminClassName(admin.ModelAdmin):
    list_display=('field1', 'field2', ....)
# blog/admin.py

from django.contrib import admin

# Register your models here.

from .models import Blog

@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
    list_display = ('title', 'published_at', 'status', 'author')
Register models in Django admin (ListView)

Frontend View For Blog List and Blog Detail View

Now we registered the model. We will check how to show this blog data on the front end.

Change the below code in the settings.py file.

# settings.py

'DIRS': [os.path.join(BASE_DIR, 'templates')]

To avoid duplication in the other templates use the below base.html code.

Base.html

# templates/base.html

<!DOCTYPE HTML>
<html>
<head>
<title>Home :: TechPlusLifestyle</title>
{% load static%}

<link href="{% static 'css/bootstrap.css' %}" rel='stylesheet' type='text/css' />
<link href="{% static 'css/style.css' %}" rel='stylesheet' type='text/css' />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="Personal Blog Responsive web template, Bootstrap Web Templates, Flat Web Templates,  Android Compatible web template,
Smartphone Compatible web template, free web designs for Nokia, Samsung, LG, sony ericsson, Motorola web design" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!----webfonts---->
<link href='//fonts.googleapis.com/css?family=Oswald:100,400,300,700' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Lato:100,300,400,700,900,300italic' rel='stylesheet' type='text/css'>
<!----//webfonts---->
<script src="{% static 'js/jquery.min.js' %}"></script>
<!--end slider -->
<!--script-->
<script type="text/javascript" src="{% static 'js/move-top.js' %}"></script>
<script type="text/javascript" src="{% static 'js/easing.js' %}"></script>
<!--/script-->
<script type="text/javascript">
			jQuery(document).ready(function($) {
				$(".scroll").click(function(event){
					event.preventDefault();
					$('html,body').animate({scrollTop:$(this.hash).offset().top},900);
				});
			});
</script>
<!---->
</head>
<body>

<script>
(function(){
if(typeof _bsa !== 'undefined' && _bsa) {
	// format, zoneKey, segment:value, options
	_bsa.init('fancybar', 'CKYDL2JN', 'placement:demo');
}
})();
</script>

<div id="codefund"><!-- fallback content --></div>

<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-149859901-1');
</script>

<script>
     window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
     ga('create', 'UA-149859901-1');
     ga('require', 'eventTracker');
     ga('require', 'outboundLinkTracker');
     ga('require', 'urlChangeTracker');
     ga('send', 'pageview');
   </script>

<meta name="robots" content="noindex">
	<!-- Demo bar start -->

<!---header---->
<div class="header">
	 <div class="container">
		  <div class="logo">
			  <a href="index.html"><img src="{% static 'images/logo.png' %}" title="" /></a>
		  </div>
			 <!---start-top-nav---->
			 <div class="top-menu">
				  <span class="menu"> </span>
				   <ul>
						<li class="active"><a href=" {% url 'home' %} ">HOME</a></li>
						<div class="clearfix"> </div>
				 </ul>
			 </div>
			 <div class="clearfix"></div>
					<script>
					$("span.menu").click(function(){
					$(".top-menu ul").slideToggle("slow" , function(){
					});
					});
					</script>
				<!---//End-top-nav---->
	 </div>
</div>
<!--/header-->
<!---728x90--->

<div class="content">
	 <div class="container">
		 <div class="content-grids">
			 <div class="col-md-8 content-main">
				{% block content %}
                {% endblock %}
			  </div>
			  <div class="clearfix"></div>
		  </div>
	  </div>
</div>
<!---728x90--->

<!---->
<div class="footer">
	<div class="container">
		<p>© 2015 Personal Blog . All rights reserved </p>
	</div>
</div>

Let’s add the blog list view in blog/urls.py file.

# blog/urls.py

from django.urls import path

from .views import *

urlpatterns = [
    path('', IndexView.as_view(), name="home"),
]

Code for the blog list view.

# blog/views.py

from django.views.generic import ListView, DetailView
from .models import Blog
# Create your views here.

class IndexView(ListView):
    model = Blog
    queryset = Blog.objects.filter(status='published').all(). \
        order_by('-published_at')
    template_name = 'blog/list_view.html'
    context_object_name = 'index_post_list'

HTML for the Blog list

# templates/blog/list_view.html

{% extends 'base.html' %}
{% load static%}
{% block content %}
	 <div class="content-grid">
		 {% if object_list %}
			{% for each in index_post_list %}
				 <div class="content-grid-info">
					 <img src="{% static 'images/post1.jpg' %}" alt=""/>
					 <div class="post-info">
					 <h4><a href="{% url 'post_detail_view'  slug=each.slug %}">{{each.title}}</a> {{each.published_at}} </h4>
					 <p>{{each.content}}</p>
					 <a href="{% url 'post_detail_view'  slug=each.slug %}"><span></span>READ MORE</a>
					 </div>
				 </div>
			{% endfor %}
		{% else %}
			No Post Found
		{% endif %}
	 </div>
{% endblock %}

Rendered HTML

Register models in Django admin (Blog ListView)

Blog Detailed View

URL for the blog detailed view.

# blog/urls.py

from django.urls import path

from .views import *

urlpatterns = [
    path('<slug:slug>', DetailedView.as_view(), name="post_detail_view"),
]

Views for the blog detailed view.

# blog/views.py

from django.views.generic import ListView, DetailView
from .models import Blog
# Create your views here.

class DetailedView(DetailView):
    model = Blog
    template_name = 'blog/detail_view.html'
    context_object_name = 'post'

HTML for the Blog Detailed view

# templates/blog/detail_view.html

{% extends 'base.html' %}
{% load static%}
{% block content %}

	<div class="col-md-16 single-main">
	  <div class="single-grid">
		  <h1>{{post.title}}</h1>
		  <br/>
		  <br/>
		  <img src="{% static '/images/post1.jpg' %}" alt=""/>
		  <p>{{post.content|safe}}</p>
	  </div>
	  <!---728x90--->

	 <ul class="comment-list">
	   <h5 class="post-author_head">Written by <a href="#" title="Posts by admin" rel="author">{{post.published_at | date:"M d, Y"}} by {{post.author}}</a></h5>
	   <li>
			<div class="desc">
			</div>
			<div class="clearfix"></div>
	   </li>
	  </ul>
	</div>
	  <div class="clearfix"></div>
{% endblock %}

Rendered HTML

Register models in Django admin (Blog DetailedView)

Check the GitHub Link of the Register models in Django admin Project for CSS, js, and images.

I hope you understand how to Register models in Django admin interface. If you have any queries regarding the Register models in Django admin, write your query in the comment box.

Leave a Comment