How to use models in DJango? Part-1

Continuing from our previous post at

https://varanasisoftwarejunction.blogspot.com/2021/02/how-to-create-site-using-django.html

Varanasi Software Junction: DJango



 In this post we will explain the use of models for communicating with a database in a DJango installation. For simplicity we will use the Sqlite database that comes bundled with DJango.

Step 1 will of course be installing DJango and getting it up and running.

Install and run DJango

Create a folder called databasedjango and then give the following commands via a command prompt.

Open a command prompt and give the following command

django-admin startproject databasesite

Next step, run and test the installation.
python manage.py runserver 777



Type http://localhost:777 in a browser and see the results


A DJango Sqlite3 database file is created automatically.

Next Step.

Create an app. Write this command on the command prompt

python manage.py startapp dbuse


Next step, create a views.py file and create your own url by importing it into urls.py.

Open the file and create a simple function called Index and return Hello from it.


views.py

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

from . import views


def index(request):
return HttpResponse("Hello")


Define the default path in urls.py, also import views.py.



urls.py


from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
path("",views.index),
]


Next step, specify the templates folder in settings.py and also give the app name.

settings.py


from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '(kvm!umqw6w*gd3tcirt%hs^+4-3*95#@_c-rg)rb^#dwt5rrn'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'databasesite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['dbtemplates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'databasesite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'


Go back to views.py and define a new function and return a template.

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

from . import views


def index(request):
return HttpResponse("Hello")

def test(request):
return render(request,"test.html")


test.html in templates directory

<!Doctype>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Hello Template</h1>
</body>
</html>

Next step, create a model in the app.
Open models.py in the app and add your class.


from django.db import models

# Create your models here.

class Book(models.Model):
bookname=models.CharField(max_length=50)
price=models.IntegerField()
subject=models.CharField(max_length=20)

class Meta:
db_table="book"





Next step, Insert data into the books table

views.py

from django.http import HttpResponse
from django.shortcuts import render
from dbuse.models import Book
from . import views


def index(request):
return HttpResponse("Hello")
def test(request):
return render(request,"test.html")

def insert(request):
bookname="The Recursion Sutras"# request.GET["bookname"]
price=399#request.GET["price"]
subject="Recursion"#request.GET["subject"]
print(bookname,price,subject)
book=Book(
bookname=bookname,price=price,subject=subject
)
book.save()
data={"bookname":bookname,"price":price,"subject":subject}
return render(request,"book.html",{'data':data})





Here is the github repository for the DJango sample. In the next post we will update, delete and search.

https://github.com/Varanasi-Software-Junction/databasedjango























Post a Comment

0 Comments

Me