AppDividend
Latest Code Tutorials

Django Crud Tutorial Example | Python Web Framework

3,745

Get real time updates directly on you device, subscribe now.

Django Crud Tutorial is the topic; we will perform in this practice. Django is the high-level Python Web framework that encourages rapid development and clean, pragmatic design. If you have not previously installed Django on a mac, then please check out my How To Install Django On Mac.  It will help you to install python and Django web framework step by step.

Django Crud Tutorial Example

We will start our application by creating a new Django project, and then we will configure it step by step and finally make a fully functional CRUD application.

Step 1: Create a Django Project.

First, start the virtual environment by typing the following command.

source bin/activate

Okay, now we will create a project by the following command.

django-admin startproject djangocrud

Our application name is djangocrud and opens this project on your IDE or Editor. I am using Visual Studio Code. Our primary project structure looks like this.

Django Project Structure

Step 2: Configuring the database.

I am using MySQL database, so I need to configure it. By default, it comes with SQLite, but we do not use that instead of we will use phpMyAdmin

Now, install mysqlclient.

sudo pip install mysqlclient

Go to the djangocrud  >>  settings.py file and edit the Databases object. Replace that object with the following object to configure the mysql database.

// settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangocrud',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': '127.0.0.1',
        'PORT': '8889',
        'OPTIONS': {
            'sql_mode': 'traditional',
        }
    }
}

Please make sure your database name, username, password and port number. I am using MAMP so; mine might be different from yours. Confirm your all that settings.

Okay, now check the connection of your Django application with the database.

python manage.py check

If you see that System check identified no issues message, then you are good to go.

Now, migrate the tables in the database using the following command.

python manage.py migrate

 

How To Connect MySQL database with Django web application

It will migrate the tables to the database successfully. Now, we need to create a superuser for our application. Hit the following command.

python manage.py createsuperuser

 

Django Create Superuser

Okay, so we have successfully created a superuser. Now, start the python server by using the following command.

python manage.py runserver

Now so it will start the server, and we can access the application at http://localhost:8000

django rest framework tutorial

Related Posts

We can also access the admin area of our application since we have created the superuser. Go to http://localhost:8000/admin Insert your newly created superuser username and password, and you can log in to the application.

Django Administration Tutorial

Step 3: Create a new app.

Next step is to create a new module or app we can say. So in the root of your project, type the following command.

python manage.py startapp coins

Now, analyze the folder structure. We have one more folder in the root called coins. 

application development framework

So, it has created a bunch of files for models and views.

Register this new app coins inside djangocrud  >>  settings.py file.

// settings.py

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

Step 4: Write your first view.

First, create urls.py file inside coins folder.

// urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

Now, include this file inside djangocrud  >>  urls.py file.

// urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('coins/', include('coins.urls')),
]

Finally, inside coins  >>  views.py file, write the following code to send the HTTP response.

// views.py

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're from the coins index")

Switch to the browser and hit http://localhost:8000/coins/

You will get the HTTP response “Hello, world. You’re from the coins index“.

Next, create the templates folder inside main root folder. In that folder create one folder called coins. Go into that folder and create one file called index.html.

Writing Templates in Django

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Django CRUD Application</title>
</head>
<body>
    <h1>Welcome to Coins app in Django</h1>
</body>
</html>

Now, we need to tell the Django application that where our template files are located. So go to the setting.py file and edit the TEMPLATES array. Right now ‘DIRS‘ key is empty, and we need to fill the value with the following code. We are merely telling the Django that load all the template files from templates folder.

// settings.py

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

Again, switch to the browser and go to the http://localhost:8000/coins/

Now, you can able to load the index.html template.

Jinja Templating Engine.

Python uses Jinja templating engine by default. Now, if we return the variable from the view like this,

// view.py

from django.shortcuts import render

def index(request):
    return render(request, "coins/index.html", 
    {'title': 'All Coins Price'})

Then, we can display title variable inside index.html file like this.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Django CRUD Application</title>
</head>
<body>
    <h1>{{ title }}</h1>
</body>
</html>

We can also define the master layout and then use that layout to another layout. You can find more about jinja templating engine on their official documentation.

Step 5: Write the model for coins application.

Now, open the coins  >>  models.py file and create a new model called Coin.

// models.py

from django.db import models

class Coin(models.Model):
    coin_name = models.CharField(max_length=30)
    coin_price = models.IntegerField()
    created_at = models.DateField()

Next step is to make migration from this Coin model. Go to the terminal and type the following.

python manage.py makemigrations coins

It will create the migration file inside coins  >>  migrations folder.

// 0001_initial.py

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Coin',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('coin_name', models.CharField(max_length=30)),
                ('coin_price', models.IntegerField(max_length=10)),
                ('created_at', models.DateField()),
            ],
        ),
    ]

Finally, create a table from this migration file by the following command.

python manage.py migrate

It will create a table in the database name like coins_coin.

Step 6: Register the model Coin.

Open coins  >>  admin.py file and add the following code.

// admin.py

from .models import Coin

admin.site.register(Coin)

So, basically, we are attaching this model to the backend of our application, which is admin area. Now, go to the admin area of the application. The URL is: http://localhost:8000/admin/

Now, you can see that our newly created coins application is there.

Now, try to add the new coin and its price and yes you can add the new coin to the database. But wait, till now we have not created any store function or write the query to insert the values in the database. We event have not created the form at the backend. So what is going on?? The answer is when we have defined the model, Django has created all the files for us and based on the database fields, it has created the form fields and write the code to insert, edit, update and delete functionalities. So Django framework is very popular for rapid development.

We are facing one problem here. After creating the Coin name and price. We can not see their name clearly instead of that, we are seeing the name object, which is not right. So let us fix that by the following code inside coins  >>  models.py file.

// models.py

 def __str__(self):
        return self.coin_name

Now, you can see that we clearly see the name of the coins. You can view, edit and delete the coins as well.

So basically, Create, Insert, Update and Delete functionalities are done by default by just creating the models.

That is it. Django Crud Tutorial Example is over. Thanks for taking.

Fork Me

1 Comment
  1. Matthew Koster says

    A little note. the last part needs to be in the class and not just in the models.py file:

    class Coin(models.Model):
    coin_name = models.CharField(max_length=30)
    coin_price = models.IntegerField()
    created_at = models.DateField()

    def __str__(self):
    return self.coin_name

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.