Dark Mode
Image
  • Thursday, 12 December 2024
Django-3: Create First Django App

Django-3: Create First Django App


Django-3: Create First Django App - Outline

1.1. What is App in Django?

Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. An app is a web application that has a specific meaning in your project, like a home page, a contact form, or a members database. Django application consists of project and app, it also generates an automatic base directory for the app, so we can focus on writing code (business logic) rather than creating app directories.

For example, if you are creating a Blog, Separate modules should be created for Comments, Posts, Login/Logout, etc. In Django, these modules are known as apps. There is a different app for each task.

What’s the difference between a project and an app?
An app is a web application which is written to perform business logic – e.g., a blog system, a database of public records or a small poll app.
A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

 

 

1.2. Create App in Django

I will name my app myApp. Start by navigating to the selected location where you want to store the app and you should be back in the virtual environment.

Let us start building an app.

Method-1: To create a basic app in your Django project you need to go to the directory containing manage.py and from there enter the command:

(myenv) E:\code\django\mysite> python manage.py startapp myApp

Method-2: To create a basic app in your Django project you need to go to the directory containing manage.py and from there enter the command:

(myenv) E:\code\django\mysite> django-admin startapp myApp

Django Tutorial Introduction

 

Registry "myApp" to INSTALLED_APPS : To consider the app in your project you need to specify your project name in INSTALLED_APPS list as follows in ..\mysite\mysite\settings.py:

# Application definition

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

 

including myApp URLs: we have finally created an app but to render the app using URLs we need to include the app in our main project so that URLs redirected to that app can be rendered. Let's explore-..\mysite\mysite\urls.py:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('appurl/', include("myApp.urls")),
]

Now You can use the default MVT model to create URLs, models, views, etc. in your app and they will be automatically included in your main project.

 

Create myApp URLs: The main feature of Django Apps is independence, every app functions as an independent unit in supporting the main project. Now the urls.py in the project file will not access the app’s url.

Create a file in the apps directory called urls.py in the ..\mysite\myApp\urls.py:

Add the following code segment to urls.py

from django.urls import path
#now import the views.py file into this code
from . import views

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

The above code will call or invoke the function which is defined in the ..\mysite\myApp\views.py file so that it can be seen properly in the Web browser.

 

 

1.3. Write your first view

Let’s write the first view. Open the file ..\mysite\myApp\views.py and put the following Python code in it: Here it is assumed that views.py contains the following code :-

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse

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

Now run command to start server:

(myenv) E:\code\django\mysite> python manage.py runserver

And Visit the url http://127.0.0.1:8000/appurl/, then you can see following page:

Django App Tutorial

 

Create Django Templates: Now I would like to Separate HTML code from view.py whereas all HTML code will be there

Create a templates folder inside the myApp folder, and create a HTML file named myfirst.html.
The file structure should be something like this:

Django App Tutorial

Open the HTML file (..\mysite\myApp\templates\myfirst.html) and insert the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My First HTML</title>
</head>
<body>
    <h1>Hello World!</h1>
    <p>Welcome to my first Django project!</p>
</body>
</html>

 

Modify the View

Open the ..\mysite\myApp\views.py file and replace the index view with this:

from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse

# Load view from Template
from django.template import loader

def index(request):
    # return HttpResponse("Hello World!")
    template = loader.get_template('myfirst.html')
    return HttpResponse(template.render())

Now again run command to start server:

(myenv) E:\code\django\mysite> python manage.py runserver

And Visit the url http://127.0.0.1:8000/appurl/, then you can see following page:

Django App Tutorial

 

 

1.4. Django Project MVT Structure

Django is based on MVT (Model-View-Template) architecture. MVT is a software design pattern for developing a web application.

Model: The model is going to act as the interface of your data. It is responsible for maintaining data. It is the logical data structure behind the entire application and is represented by a database (generally relational databases such as MySql, Postgres).

View: The View is the user interface — what you see in your browser when you render a website. It is represented by HTML/CSS/Javascript and Jinja files.

Template: A template consists of static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted.

Django App Tutorial

Project Structure : A Django Project when initialized contains basic files by default such as manage.py, view.py, etc. A simple project structure is enough to create a single-page application.

Django App Tutorial

Here are the major files and their explanations.

manage.py- This file is used to interact with your project via the command line(start the server, sync the database… etc). For getting the full list of commands that can be executed by manage.py type this code in the command window-

(myenv) E:\code\django\mysite> python manage.py help

Django App Tutorial

_init_.py – It is a python package. It is invoked when the package or a module in the package is imported. We usually use this to execute package initialization code, for example for the initialization of package-level data.

settings.py – As the name indicates it contains all the website settings. In this file, we register any applications we create, the location of our static files, database configuration details, etc.

urls.py – In this file, we store all links of the project and functions to call.

wsgi.py – This file is used in deploying the project in WSGI. It is used to help your Django application communicate with the webserver.

 

 

1.5. Django App request-response Life Cycle

Django App Tutorial

Let's start understanding the request-response lifecycle of a Django application. Every web application uses HTTP/HTTPS protocol. In the HTTP/HTTPS protocol client sends a request to the server based on the request data server sends the response back to the client. It's the basic principle of HTTP protocol. While setting up the django application in the server we need a webserver and wsgi server. Webserver helps us in serving static files/content. If we did not use the webserver to serve static files then it has to served by WSGI server which results in more number of requests to the server. So, gradually it slow down the application performance. Web server balances the requests load on the server. So, it's highly recommended to use the webserver.

 

A client can be defined as a piece of software which can send a request by following the HTTP/HTTPS protocol. In general we consider client as a Web Browser. While deploying the django application on the server we use one of the combinations of a "Nginx, uWSGI and Django" or "Nginx, gunicorn and Django" or "Apache, mod_wsgi and Nginx". As of now, we will discuss the deployment process but we discuss about request-response lifecycle of Django application. We will be discussing on when a request comes in how it can be processed and how the response will be created and sent back to the client.

 

When a client sends a request to the server it first passed to the webserver, It contains the configuration rules to dispatch the request to the WSGI server or served by itself. WSGI server pass the request to the Django application. Django has the following layers in dealing with request-response lifecycle of a Django application.

 

Layers of Django Application:-

  1. Request Middlewares
  2. URL Router(URL Dispatcher)
  3. Views
  4. Context Processors
  5. Template Renderers
  6. Response Middlewares

 

 

Comment / Reply From