Tuesday, 6 July 2021

*Episode 8* PYTHON (Project Structure and Apps of Django)


Examining the project structure and apps


This episode covers :-


 1.) What are apps?

 2.) Overview of the project structure.

 3.) What does all the project files do?


  • Adding features with apps :-

      Application (app) is a Python package that adds features to your project. With the myapp application we added a simple homepage “feature”. The project now has a custom homepage rather than the default welcome screen.


     You create new apps with the startapp command. This creates the Django app folder structure:

Terminal

python manage.py startapp myapp


     It makes sense to group similar set of features into apps. For example you could create a forum app that provides a forum functionality in forum or maybe a custom administration area in myadmin.


    You could potentially re-use these apps in other projects.


    The mysite folder that was created with the startproject command can also be considered an app. This app makes your Python project a web project.


    You typically enable apps by adding a string to the INSTALLED_APPS list in the settings.py file:

mysite/settings.py

INSTALLED_APPS = [

'django.contrib.admin',

...

'myapp', # <-- here

]


  •  Exploring the project structure :-

Let’s take a closer look at an example project structure:

Project folder structure

├── 09-Hello-World <-- Project root

│ ├── db.sqlite3 <-- Database

│ ├── manage.py <-- Management tool

│ ├── myapp <-- Custom app

│ ├── forum <-- Custom app

│ ├── myadmin <-- Custom app

│ └── mysite <-- Project package

└── venv <-- Virtual environment (Django + Python)


     The project root contains the database, manage.py file and all the apps that are not installed in the virtual environment. Django package and Python is installed in the venv folder.


Here are the default contents for new apps:

Default files for a new app

myapp

├── __init__.py

├── __pycache__

├── admin.py

├── apps.py

├── migrations

├── models.py

├── templates

├── tests.py

└── views.py


     __init__.py is usually an empty file that marks this directory as a Python package. Note: in newer Python versions (3.3+) it’s not required to have this file: https://samuli.to/PEP-420.


     __pycache__ contains bytecode that makes the program start faster.


     Django has an automatic admin interface in admin that you can use to manage content. You usually register models in the admin.py file so that they are available for management:

myapp/admin.py

from django.contrib import admin

from myapp.models import Post

admin.site.register(Post)


      Don’t worry about this for now. We will get back to it when we cover models. Also note that the default admin interface is intended for internal management purposes. You might want to allow content management with a custom solution that provides forms to add and edit content. Custom forms will be covered later in the book.


      apps.py is used to configure the app. For example you could change the human- readable name for the app like this:

myapp/apps.py

from django.apps import AppConfig

class MyConfig(AppConfig):

verbose_name = "Excellent App"


      Now in the admin interface it would say “Excellent App” instead of “Myapp”.


      migrations folder contains the migration files for the app. These are used to apply changes to the database. You can think of the migration system as a version control for the database schema.


      models.py file store information about the data you want to work with. Typically each model maps to a database table.


      Here’s an example of the Flower model we will use later:

myapp/models.py

from django.db import models

class Flower(models.Model):

title = models.CharField(max_length=255, default='')


       This model is mapped to a database table called Flower and each attribute like the title field is mapped to a database field.

      Put app template files in the templates folder:

Templates folder

├── 09-Hello-World

│ ├── myapp

│ │ ├── templates

│ │ │ └── myapp

│ │ │ └── index.html # < template file


      Templates allow you to separate the presentation from the application logic. Django has its own template language where you mix static HTML, variables,  tags and filters to generate the final HTML.


      You typically create a subfolder for each app inside the templates folder. It might look a bit odd to have another myapp folder inside the templates folder but in this way we don’t have to do anything special for Django to discover the template. We just have to use the right naming conventions.


      For example in the myapp views.py file we used myapp/index.html as an argument for the render function:

myapp/views.py

from django.shortcuts import render

def index(request):

return render(request, 'myapp/index.html') # here


      With this parameter Django’s template loading mechanism finds the correct template in myapp/templates/myapp/index.html.


      tests.py is a typical place for the app testing code.


     It’s a convention to put view functions in the views.py file. View function takes a web request and returns a web response. In our “hello world” example the index view returns HTML contents generated with the help of the index.html template.



  •  Exploring the project package :-

     Let’s take a look at the project package files:

Project package files

├── 09-Hello-World

│ ├── db.sqlite3

│ ├── manage.py

│ ├── myapp

│ └── mysite

│   ├── __init__.py

│   ├── __pycache__

│   ├── settings.py # < here

│   ├── urls.py # < here

│   └── wsgi.py # < here


      Most of the project configuration happens in the settings.py file.


      For example the default database configuration looks like this:

mysite/settings.py

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.sqlite3',

'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

}

}


      This allows you to start working with a database immediately.

      For PostgreSQL database we would do something like this:

PostgreSQL configuration example

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.postgresql_psycopg2',

'NAME': 'mysitedb',

'USER': 'username',

'PASSWORD': 'password',

'HOST': 'localhost',

'PORT': '',

}

}


      With Heroku platform you don’t have to configure this manually though because the django-heroku package does it for you.


     urls.py file contains URL patterns. Django starts going through these patterns when user requests a page and stops when a pattern matches the requested URL.


      In our “Hello world!” example the index view will be called when user visits the homepage:

urls.py

from django.contrib import admin

from django.urls import path

from myapp import views as myapp_views

urlpatterns = [

path('admin/', admin.site.urls),

path('', myapp_views.index, name='index'), # < here

]


       WSGI is a specification that deals with interactions between web servers and Python web applications. The startproject command sets up default configuration for it in wsgi.py.



Summary


  •  startproject command creates a project skeleton with all the files you need to get started.
  •  Project package (folder with settings.py file) connects your Python project  with Django.
  •  You typically add features to your project with apps.
  •  startapp command creates a basic application skeleton.

👈Episode 7(P).                                                                                  Episode 9(P)👉
Share This Post
PRINT THIS POST

No comments:

Post a Comment

If you have any doubts. Please let me know.

Featured post

*Episode 1* MCQ for Govt. Job/ Private Job/ MNCs

  Topic:- One Word Substitution 1) Especially skilled in storytelling  Answer:- Raconteur 2) Fear of loneliness Answer:- Eremophobia  3) Usa...