Django Basics and Structure

By StartxLabs
Date 18-06-21
Django Basics and Structure
" Django Basics and Structure"

 

Django is an open-source, fully-featured Python-based framework initially released on 21 July 2005 by Django Software Foundation. This framework helps in building complex web apps by following MTV (Model Template Views) architectural patterns. Django primarily focuses on developing complex websites, also ensuring certain features such as reusability, pluggability, less code, less coupling, quicker development, and more. Django also provides an effective interface that allows users to manage admin controls such as create, read, delete and update. Some of the popular sites that utilize the Django framework are Instagram, The Washington Times, Disqus, Nextdoor, PBS (Public Broadcasting Service), Bitbucket, and Mozilla.

 

Why Django?

 

In an era where frameworks are abundantly available for web and app development, why does Django stand as an effective choice among the others? There are plenty of answers to this question. Let's see some of them below.

 

Django is written in Python, which is a user-friendly and most-readable programmable language that makes it more suitable for web development. Django stands first because of the outstanding features it provides. While developing a website in Django, you don't need to seek help from external packages or libraries, as working with Django syntax is seamless and makes you feel like using a single framework. Want to add some more features to enhance your website? Of course, you can use a variety of external libraries in Django.

 

Django's in-depth documentation provides clear and detailed documentation about every feature of Django with great examples and tutorials.  

 

Got stuck in the middle of your website development? Django provides an excellent community of developers for this, to whom you can ask for help either by document checking or by asking them.

 

Django Website's Structure 

 

A single project in Django will be divided into separate apps. Each app on the project manages separate functions of the website. Let's say, if you are building a social app, it will consist of various functions to perform. It may have different functions like,

 

  • User Control: User-specific functionalities such as sign in, sign out, register, and more.

  • Feed Control: Feed related functions such as posting, displaying, commenting

  • Messaging: Private messages and notifications.

 

Above are the functions used by a typical social media app. If you are building this with Django, each of these functions will be a different app under a single project.

 

With Django, you can apply some configurations to the whole project. Some of the configurations include project settings, shared templates, URLs, and static files. Each application inside a project has its own database and can manage how the data should be displayed in HTML templates to the user. Apart from this, each application in a single Django project has its URLs, its HTML templates, and static files like JS and CSS.

Each application in Django is structured in a way that should provide a separation of logic. As mentioned earlier, it follows MVC architecture, on which most of the frameworks are developed.

Three files are in each application that controls the separation of logic into three main pieces. They are:

 

  • Model: It defines the data structure. It is the base layer and is the database of an application.

  • View: It displays the data with HTML and CSS to the users.

  • Controller: It controls how the view and database interact.

 

Though Django follows the MVC pattern, some of the properties in its architecture may slightly vary. Django manages the controller part on its own. Interaction between the database and views need not be defined and everything has been done already for you.

 

To know more about MVC, check out Model-View-Controller (MVC) Explained – With Legos.

 

The views of the MVT pattern which is used by Django have views and templates. You only need to add the URLs to map the views and Django manages the remaining works. Every Django website has a number of applications for handling separate functionalities and those applications follow the MVT pattern. This is the basic structure of a Django website.

 

Getting started with our First Django Project

 

We are going to discuss a simple project with Django. Before that, we have to set up the right plan of what we are going to build. Let's build an app that has the following features:

 

  • Blog: A simple application can be created that lets you create, delete, sort, and update blog posts. Users can also comment on the blog posts.

  • Portfolio: You can also showcase your works like your previous projects and more.

 

Setting Up the Development Environment 

 

It is always better to set up the development environment before starting to build a website. A new directory for the live project can be created by,

 

$ mkdir rp-portfolio
$ cd rp-portfolio

 

Now you got into the main directory, the next step is to manage dependencies by creating a virtual environment. It can be created by,

 

$ python3 -m venv venv

 

Now, a folder called "venv" has been created in the working directory. You can now find several files along with the copy of standard libraries of Python inside the working directory. Whenever you are installing any new dependencies, you can find them to be stored in this working directory. The virtual environment can be activated by,

 

$ source venv/bin/activate

 

Users who don't use bash shell need a comment

 

C:\> venv\Scripts\activate.bat

 

to activate the virtual environment.

 

Now you have activated your virtual environment and the control prompt in the terminal will look like,

 

(venv) $

 

Now install Django using pip,

 

(venv) $ pip install Django

 

Everything has been set up now, and you can start creating your first-ever project on Django.

 

Read our article on Data Visualization in Python using Matplotlib

 

 Creating a Project

 

As we know, a Django app consists of a project and the constituent apps associated with it. After the successful creation of your virtual environment, run the command for project creation,

 

$ django-admin startproject personal_portfolio

 

This command creates a new directory named "personal portfolio" and almost all of the works you do will be saved into this directory.

 

After setting up the file structure, you can check whether your setup is successful or not by starting the server. To do this, run the command:

 

$ python manage.py runserver

 

You can now see your newly created Django site in your browser. Let's see how to add views and functionalities to your site.

  

The first step is to create the app.

 

$ python manage.py startapp hello_world

 

 

Here, hello_world is the name of the new app we are going to create. This command will create a directory named hello_world consisting of several other files such as

 

  • __init__.py makes the Python consider the directory as a Python package.

  • admin.py consists of Django admin page settings.

  • apps.py consists of application configuration settings.

  • models.py consists of series of classes that make Django's ORM convert to database tables.

  • tests.py consists of test classes.

  • views.py consists of classes and functions for handling the data displayed in HTML templates.

 

After the successful creation of the app, you have to install the app in your project. To do this, add the following code.

 

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

 

Creating a view 

 

Django views are a set of classes or functions that are contained inside the views.py file. Whenever a URL is browsed, each class or function manages the logic that is processed. Add the following piece of code to the already available import render() code in the views.py file in the hello_world directory.

 

from django.shortcuts import render

def hello_world(request):
    return render(request, 'hello_world.html', {})

 

Here, we have defined a view named hello_world(). Upon function call, this will render the hello_world.html file. Now it is time to create templates inside the app directory.

 

$ mkdir hello_world/templates/
$ touch hello_world/templates/hello_world.html

 

The following HTML lines should be added to your file to get displayed:

 

<h1>Hello, World!</h1>

 

Now, a function for handling the views and templates for displaying it to the user has been created. The last step is to attach the URL which lets you see the page you have created.

 

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

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

 

These commands check for a module named urls.py inside the hello_world app and register the URL defined inside that. For creating the hello_world.url,

 

$ touch hello_world/urls.py

 

Import path objects and the views module inside this module. Then a list of URL patterns for the corresponding view functions should be created.

 

from django.urls import path
from hello_world import views

urlpatterns = [

    path('', views.hello_world, name='hello_world'),
]

 

Now you can see your app when you visit localhost:8000. Success! We have created our first-ever Django project! This is a simple project created only with HTML. You can also add CSS styles or bootstrap styles to the project.

 

"We transform your idea into reality, reach out to us to discuss it.

Or wanna join our cool team email us at [email protected] or see careers at Startxlabs."

subscribe to startxlabs

startxlabs