Python Web Development Using Django in 2023
Tags: python, django, webdev, beginners
Published: 2023-01-09 10:29:16

Django is a [web app development](https://quokkalabs.com/web-application-development) framework, and we will be using Django Python in this blog to make understanding simple that we are using Python too. Django has also known as a batteries-included framework. Why? Because it got built-in features like a default database, an admin interface, and more. In short, in this blog, we will learn Python web development using Django!

Let's get started!
## Why use the Django Framework?

- Highly scalable
- Best in documentation
- Django python is used by top MNCs like Instagram, Spotify, and more for rapid web development.
- Python got an extensive library and features like Web Scraping, ML, Image processing, and more. Because of them, it's advantageous. If you integrate all, you can do advanced stuff. 

Now let's see the Django architecture!
## Django Architecture
Django is based on MVT architecture. MVT stands for "Model View Template." It got the following parts. 
### Virtual Environment Setup
In the Django Web app development project, you may want a different version as sometime the problem arises. This problem occurs when you are in a default environment. 

To solve this problem, you will need to use virtual environments in Python, or you can Hire python developers to resolve and streamline all the issues. 

It will enable you to create multiple Django enlivenments on a single machine/computer. 

To make a virtual environment of it, type the underneath command in the terminal:

`python3 -m venv ./name`

You can see the "name" on the code, which suggests the virtual environment. Let's now create the virtual environment with the name VENV. 

`python3 -m venv ./venv`

Now, you can see the folder named venv with its subdirectories like below:

![subdirectories ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3fkdh42l4i9u76hr1ldc.png)
Now, let's activate it after making a virtual environment. To trigger it, type the below command in the terminal.

`source ./venv/bin/activate`

As you can see in the above command ./ is used to show that it's a working folder.

You should see (VENV) at the start of every line in your terminal. 
## Django Installation
Now, let's install Django! To install Django, we can use the pip command, like the one below, in the terminal.

`pip install django`
## Initiating The Project
On your computer, to start the project, open the terminal and add the following command.

`django-admin startproject projectName`

You can see that a new folder will be created named" ProjectName." In the folder, type the following command in the terminal.

`cd projectName`

To see if it's working, let's try running the server. To run the server, enter the following command.

`python manage.py runserver`

After commanding like above, go to [http://127.0.0.1:8000/](http://127.0.0.1:8000/) and see if it's opening like the below image.

![Server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t3zich2twy4eai61xu78.png)
## Structure Of Project
There are raw files are there when Django is installed, like

- Manage.py
- View.py etc

A simple project structure is enough to create a simple page app in your Web app development. Inside our project folder, there are major files are there like listed below:

- pycache
- init.py
- Asgi.py
- Settings.py
- Urls.py
- Wsgi.py
- Manage.py

**Manage.py:** It's used to communicate with the project via the command line.

**_init_.py:** It's a Python package that starts when the module or package inside it is imported. 

**Settings.py:** it has all website settings where we can register an app we create, static files or database configs, etc. 

**Urls.py:** here, all links are stored off the project.

**Wsgi.py:** it's used to deploy the project in wsgi. It helps the Django app communicate with the web server. 
## Creating the App
Django is well known for its fully managed, unique managed app structure. An app can be created for each function as an autonomous module. 

**For instance:** if you are generating a blog, separate modules can be created for comments, posts, and login/logout. These functions are known as "apps" in Django. In short, there are different apps for each function. 

Django also provides preinstalled apps for users. You can see preinstalled apps by navigating to

<u>projectName –> projectName –> settings.py
</u>

You can find installed apps provided by Django in your settings.py file. It will look like the one below.

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

```
Here we can also create and add our custom apps. To make a basic app in your Django project, go to a directory with manage.py and enter the command below.

`python manage.py startapp projectApp`

Now, it's time to create an app named qfq_site_app. You can add the below command to make the same.

`python manage.py startapp qfq_site_app`

Later then, you can spot the director named "qfq_site_app." To make this app appear in your app list, you must specify the project name in installed_apps. 

```
INSTALLED_APPS = [
	'django.contrib.admin',
	'django.contrib.auth',
	'django.contrib.contenttypes',
	'django.contrib.sessions',
	'django.contrib.messages',
	'django.contrib.staticfiles',
	'qfq_site_app.apps.QfqSiteAppConfig',
]
```
## Django Views
"View" is a function in Python. It processes requests from the web and returns a web response. This response from a "view" can be the HTML content of a webpage or a redirect, an XML Doc or 404 or an image, or anything possible. 

Django view is very important for the user interface. It renders CSS/HTML/Javascript in template files so the browser can render a web page. 
### How To Create a View Function?

```
from django.http import HttpResponse

# create a function
def quokka_view(request):
	
	return HttpResponse("<h1>Welcome to QuokkaforQuokka</h1>")
```
First, import a class called HttpResponse from the Django.http module with Python's datetime library. 

Now, we will define a function, and it will be a new type. Each function takes the Httprequest object as its first para.

This function will process the page's text "Welcome" as H1. Now, you will get a question: on which URL will this function be asked, and how will we handle them?

Don't worry. We will do it. Keep reading. But before that, we will see the types of views. 
#### Function-Based Views
These writers use a python function that gets an argument, the HTTPRequest object, and backs the HTTPResponse object. 
These functions-based views are divided into four basic strategies: 

- Create
- Retrieve
- Update
- Delete

The short form is CRUD. It is the base of any framework that uses development. 
#### Class-Based Views
Instead of using functions to install views as Python objects, these are an alternative way. Class-based views don't remove the function-based views but have deference as an advantage compared to functions-based views
## Django URL Patterns
Each view must be plotted to a conforming URL pattern in Django. It's done via a Python model named URLConf.
 
Each Urlconf module must contain a variable URLPATTERNS. 

URLPATTERNS are set off to be matched to the requested URL. 

These patterns run in flow and run until it finds matches. Later, the corresponding view is invoked. But if it does not find any matches, it shows an error. 

In our project, we have created an app called qfq_site. It's the Python module used as URLConf. Its value of ROOT_URLCONF in file qfq_site/settings.py. It's default set to qfq_site. URLs. At last, all process processes occur, as we discussed above. 

Sample code of qfq_site/urls.py

```
from django.urls import path
from . import views

urlpatterns = [
	path('', views.quokka_view, name='quokka_view'),
]
```
If we add another URLCONF module, the code will look like the one below.

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

urlpatterns = [
	path('admin/', admin.site.urls),
	path('', include('qfq_site_app.urls'))
]
```
## Django Models
It's a built-in feature to create tables, fields, and constraints. We can also refer to them as the SQL databases that one uses with Django in our web app development. We know that SQL is complex, but the Django model simplifies it and maps it to a single database table.

Sometimes creating models is complex for complex projects; you simply hire Python developers for it.

Django models give us simplicity, consistent version control, and other advanced features like metadata handling.

```
# import the standard Django Model
# from built-in library
from django.db import models
from datetime import datetime

class QuokkaModel(models.Model):

	# Field Names
	title = models.CharField(max_length=200)
	description = models.TextField()
	created_on = models.DateTimeField(default=datetime.now)
	image = models.ImageField(upload_to="images/%Y/%m/%d")

	# rename the instances of the model
	# with their title name
	def __str__(self) -> str:
		return self.title
```
Whenever we edit a model, we have to run two commands: makemigrations and migrate.makemigrations. These commands are for preinstalled apps and newly installed app models. 

`Python manage.py makemigrations`

It creates the model and

`Python manage.py migrate`

It creates the table in the database. 

Now we must add data to our SQLite table. Let's do that!

First, we must access the Django ORM using the below command inside our directory.

`python manage.py shell`

Now let's add the objects by using the following command.

```
from qfq_site_app.models import QuokkaModel

obj = QuokkaModel(title="QuokkaforQuokka",
description="QFQ is a portal for computer science students")
obj.save()
```
To retrieve the objects of a model, we can add the below command to the terminal:

`QuokkaModel.objects.all()`

To delete objects, we can write the below code.

```
obj = QuokkaModel.objects.get(id=1)
obj.delete()

QuokkaModel.objects.all()
```
## Django: Uploading Images
To upload images, we must write the below code in the setting.py. File. 

```
MEDIA_ROOT = BASE_DIR/'media'
MEDIA_URL = '/media/'
```
In the file named urls.py, we must have to edit it like follows:

```
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
       urlpatterns += static(settings.MEDIA_URL,
                             document_root=settings.MEDIA_ROOT)
```
## Django Admin Interface: Render a Model
First, we need to edit app/admin.py. to render a model in Django admin. Add the below code in quokka_site_app from admin.py. 
```
from django.contrib import admin
from .models import QuokkaModel

# Register your models here.
admin.site.register(QuokkaModel,)
```
Let's make a superuser for our project in our site's admin area. Add the following command.

`python manage.py createsuperuser`

Now, go to the site: [http://127.0.0.1:8000/admi](http://127.0.0.1:8000/admi)n and the interface will look like the below.

![Interface](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ifol4d081x7ez8wr9qnx.png)
Enter the username and password; the following window states "Site administration." Enter the data using the dashboard. You can add the title, description, created data, and image upload. After doing that, you can see the window as a model-wise structure that you can edit later. 

Hiring Python developers to streamline the flow is good if you face difficulties. 
## Connecting Django to Different Databases
We know previously that Django comes with an SQlite database. You can see it in the databases dictionary in the file named settings.py. 

```
DATABASES = {
	'default': {
		'ENGINE': 'django.db.backends.sqlite3',
		'NAME': BASE_DIR / 'db.sqlite3',
	}
}
```
If we change the current database to PostgreSQL, then the database dictionary will look like the below:

```
DATABASES = {
'default': {
	'ENGINE': 'django.db.backends.postgresql',
	'NAME': '<database_name>',
	'USER': '<database_username>',
	'PASSWORD': '<password>',
	'HOST': '<database_hostname_or_ip>',
	'PORT': '<database_port>',
}
}
```
## Django Templates
They are an essential part of the Django MVT structure. Templates in Django are generally written in HTML, CSS, and Javascript with the file extension .html. 
Django functions in the backend, so we must use templates to provide our website's front end and layout. 

We will create a single temple folder for our current project that will apply all over the project to simplify it. 

There are app-level templates, too, but they are used in large projects where we require different templates. 

Configuration of the template can be done in the file app_name/settings.py.

```
TEMPLATES = [
	{
		# Template backend to be used, For example Jinja
		'BACKEND': 'django.template.backends.django.DjangoTemplates',
		
		# directories for templates
		'DIRS': [],
		'APP_DIRS': True,
		
		# options to configure
		'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',
			],
		},
	},
]
```
Now, let's add the location to our template folder of that folder. 

```
TEMPLATES = [
	{
		'BACKEND': 'django.template.backends.django.DjangoTemplates',
		
		# adding the location of our templates directory
		'DIRS': [BASE_DIR/"templates"],
		'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',
			],
		},
	},
]
```
Now we will create an HTML file with the name index.html. 

```
<!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>Homepage</title>
</head>
<body>
	<h1>Welcome to Quokkaforquokka</h1>
</body>
</html>
```
We will use the function render from the Django.shortcuts to generate that HTML file.

```
from django.shortcuts import render

# create a function
def quokka_view(request):
	
	return render(request, "index.html")
```
These templates show data from other databases too that are connected to it. Now we will render a database for our website. 

Let's see the file views.py file.

```
from django.shortcuts import render
from .models import QuokkaModel

# create a function
def quokka_view(request):
	
	content = QuokkaModel.objects.all()
	context = {
		'content': content
	}
	return render(request, "index.html", context=context)
```
**Index.html**

```
<!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>Homepage</title>
</head>
<body>

	{% for data in content %}
	<h2>{{data.title}}</h2>
	<img src="{{ data.image.url }}" alt="">
	
<p><strong>Description:</strong>{{data.description}}</p>

	
<p><strong>Created On:</strong>{{data.created_on}}</p>

	{% endfor %}

</body>
</html>
```
## Language of Django Template
It's also one of the most critical facilities in the Django template to add to our Web app development. Some important ones are Variables, tags, Filters, Comments, etc. 
### Variables
It outputs value from the context sent from the view that variables can use in the templet.

`{{ variable_name }}`

### Tags
These provide arbitrary logic in the rendering process. A tag outputs the content and serves as a control structure. 

`{% tag_name %}`

### Comments
It's an optional note that you can insert in the tag. It's advantageous to comment code.

`{% comment 'comment_name' %}
{% endcomment %}`

## Django Forms
In creating a form in Django, the most important part is defining its fields of it. There is custom validation logic with other hooks as well. 
### Creating Django Forms
It's like creating a model. You only need to specify what fields you need in the form and their types. 

You can create a Django form by creating a forms.py in the app folder. 

```
from django import forms

class QuokkaForm(forms.Form):

	title = forms.CharField(max_length=200)
	description = forms.CharField(widget=forms.Textarea)
	image = forms.ImageField()
```
Now, let's create another view function for managing forms, and we will map it with another URL. 

```
from .forms import QuokkaForm

def quokka_form(request):
	context = {}
	context['form'] = QuokkaForm
	return render(request, "form.html", context=context)
```
To map this function to a different URL, go to urls.py.

```
from django.urls import path
from . import views

urlpatterns = [
	path('', views.quokka_view, name='quokka_view'),
	path('add/', views.quokka_form, name="quokka_form")
]
```
Now, it's time to create the form.html for rendering it.

```
<form action="" method="POST">
	{% csrf_token %}
	{{form.as_p}}
	<input type="submit" value="submit">
</form>
```

Now, store all the archives and go to [http://127.0.0.1:8000/add/ ](http://127.0.0.1:8000/add/ )to see if it's been created. 
### Creating Django Form from Models
Django ModelForm is a class. It's used to convert a model into a Django form directly. 

To create a form from the model, go to forms.py and enter the below code.

```
from django import forms
from .models import QuokkaModel

class QuokkaForm(forms.ModelForm):

	class Meta:
		model = QuokkaModel
		fields = ['title', 'description', 'image']
```
Now go to [http://127.0.0.1:8000/add/](http://127.0.0.1:8000/add/) and check.
 
As you can notice, both forms are the same, but the difference is the same method. We need to save the data on our database using ModelForm. 

To make this change, follow the below procedure.

```
def quokka_form(request):
	if request.method == 'POST':
		form = QuokkaForm(request.POST, request.FILES)

		if form.is_valid():
			form.save()
			return redirect("quokka_view")
		else:

			# uncomment the below line to see errors
			# in the form (if any)
			# print(form.errors)
			return redirect("quokka_form")
	else:
		context = {}
		context['form'] = QuokkaForm
		return render(request, "form.html", context=context)
```
That's it. Now you can see the whole webpage using [http://127.0.0.1:8000.](http://127.0.0.1:8000. )
## Final Words
In this web development tutorial blog, we have successfully created the webpage using Django python. We have added some basic functionalities. As you learned in this blog, there are many functions to add, and after some practice, it's easy to do so. 

Well, in critical projects, it's always good to hire Python developers to streamline the workflow for web app development. You can find a suitable development company to make it possible.