Part -6

This chapter will teach you the following:

  • creating database tables for our application using Django models
  • Accessing admin page
Models in Django

In Django, the messy issues with SQL is a solved problem: you don’t have to use SQL at all unless you want to, instead, you use a Django model to access the database.

An ORM tool, on the other hand, provides a simple mapping between an object (the ‘O’ in ORM) and the underlying database. This means that the programmer doesn’t need to know the database structure, nor does it require complex SQL to manipulate and retrieve data.

Moreover, we can use admin panel of Django to create, update, delete or retrieve fields of a model and various similar operations. Django models provide simplicity, consistency, version control and advanced metadata handling.

Your First Model

Now that you have an idea what Django models are, it’s time to go ahead and create your first model.

# import the standard Django Model from built-in library
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# declare a new model with a name "Post"
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
#renames the instances of the model with their title name
def __str__(self):
return self.title

Here, we are representing our database structures as Classes or Models.So within our models.py file,we are creating our Post model and adding field attributes to it.

The date_posted includes a DateTimeField of built-in Django and a default parameter is passed as the current time which can be updates as well ,notice that we didn’t put the parenthesis after now(),because we don’t want to call the function just now.

The from django.contrib.auth.models import User imports the built-in User class which will be the table for the authors of our Posts.The author attribute is a OneToMany relationship because one user can have multiple posts,but a post can only have one author and to do this in Django we simply used a foreign key,the second parameter that we passed to the Foreign key , on_delete=models.CASCADE because if a user is deleted then we want to delete their posts as well but that’s only a one-way street so if you delete a post then it’s not going to delete the user because you know that would be definitely a bad design.

Whenever we create a Model, Delete a Model, or update anything in any of models.py of our project. We need to run two commands makemigrations and migrate. makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created app’s model which you add in installed apps whereas migrate executes those SQL commands in the database file.
So when we run,

Python manage.py makemigrations

SQL Query to create above Model as a Table is created and

Python manage.py migrate

creates the table in the database.

Note: To see the actual SQL code of the model, you can use this command in terminal and it prints out the SQL it is going to run

Python manage.py <appname> <migration number>
or
Python manage.py blogapp 0001

Now that we’ve created models, we’ll use the Django Admin site to add some “real” data. First we’ll show you how to register the models with the admin site, then we’ll show you how to login and create some data.

Registering models

open admin.py in the blogapp.

Register the models by copying the following text into the bottom of the file. This code simply imports the models and then calls admin.site.register to register each of them.

from .models import Postadmin.site.register(Post)

This is the simplest way of registering a model, or models, with the site

Creating a superuser

In order to log into the admin site, we need a user account with Staff status enabled. In order to view and create records we also need this user to have permissions to manage all our objects. You can create a “superuser” account that has full access to the site and all needed permissions using manage.py.

Call the following command, in the same directory as manage.py, to create the superuser. You will be prompted to enter a username, email address, and strong password.

python3 manage.py createsuperuser

Once this command completes a new superuser will have been added to the database. Now restart the development server so we can test the login:

python3 manage.py runserver

Logging in and using the site

To login to the site, open the /admin URL (e.g. http://127.0.0.1:8000/admin) and enter your new superuser userid and password credentials (you’ll be redirected to the login page, and then back to the /admin URL after you’ve entered your details).

This part of the site displays all our models, grouped by installed application. You can click on a model name to go to a screen that lists all its associated records, and you can further click on those records to edit them. You can also directly click the Add link next to each model to start creating a record of that type.

Next Up..

Previously..

Posting Django Tutorials with Beginner to Advanced Projects

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store