Django Create Project – How to Create Django Project Tutorial

Django Create Project – How to Create Django Project Tutorial. In this post, we introduce Django, and its advantages then show you how to create a Django project on Linux.

Most people who are interested in Python and web development have probably heard of Django, a popular web framework. Python is a widely recognized programming language globally, and in 2017, it was the second most used language in GitHub projects. With the proliferation of web frameworks, selecting a new one can be difficult, and deciding which one to use is even more challenging. Therefore, this article provides an in depth examination of Django, its capabilities, and why it is extensively used in the tech industry, to provide a comprehensive understanding of this exceptional technology.

What is Django?

All in all, Django is a web framework that web developers use to create web applications. According to its own definition, it is a “batteries included” web framework that prioritises robustness and simplicity while creating code that is effective, clear, and strong. It is one of the most popular and widely used web frameworks globally, with well known companies such as Google, Instagram, YouTube, and NASA’s website utilizing it.

Advantages of Django

Here are some advantages of using Django:

Highly Secure

Django makes sure that developers don’t make any security related blunders when creating online applications. Finding security flaws in Django won’t be that easy, not even in the user authentication scheme. The framework has safeguards in place to stop the most frequent security concerns, such as XSS and CSRF (Cross Site Request Forgery) attacks, SQL injections, Clickjacking, etc. Therefore, Django’s user authentication system, which controls users and passwords, is also reliable.

Django offers a Default Admin Panel

By default, Django produces an admin interface. There is no need to write any code in order to construct it. Django provides all features to users by default, which minimizes the amount of effort required for development.

Good for SEO

Also, Django gives you lots of useful SEO tools. By using cached templates, CSS and JavaScript compression, and the Django SEO framework module, developers increase the speed at which web pages load. It has a mechanism to manage robots.txt. In the subject of SEO, it might not be as successful as WordPress (the most popular CMS programme for blogging). Yet, in comparison to other web development frameworks, Django is among the best for SEO.

Good Documentation and Tutorials

The Django framework includes exceptional documentation for its users. And, there are plenty of free learning materials available on the internet. Educational resources such as articles, tutorials, and video courses are available for learning Django, making it conveniently easy for its users to learn.

Django offers Object Relational Mapper

Django ORM offers efficient and appealing object oriented database interaction. The commonly used objects in application code automatically translate their data into data that is saved in databases by using a library called ORM.

There are no special SQL queries that must be made to create tables and insert data. The ORM automatically generates a table for each declared class. This table’s one field is linked to one of the class’s variables. Moreover, on building items, the table automatically adds rows.

Features of Django

  • Versatile in Nature: Django’s versatility lies in its logical project structure and MVT architecture, which may sometimes appear limiting. However, this is a misconception because the framework’s file system provides a solid foundation that developers use to create any type of application they desire. Therefore, the apparent limitations of Django are nothing but its strength as they allow developers to build on a stable and reliable base to create custom applications.
  • Thoroughly Tested: When learning a new technology, we want it to be durable and adaptable enough to keep pace with the fast changing industry, and in that regard, Django excels tremendously. Since, Django has been in existence for over ten years and is still a popular technology that outperforms frameworks like Laravel (PHP) in their domain is a testament to its resilience and adaptability.
  • Object Relational Mapping (ORM): Instead of writing SQL queries to interface with the database, Django’s advanced ORM enables developers to use Python classes and objects. Database integration is made easy and effective by this feature.

Django Create Project - How to Create Django Project Tutorial

In this section, we show you how to install Django in Python virtual environment. We then explain how to create a Django project on your Linux system.

Prerequisites

  • A server running Linux operating systems.
  • A root user or a user with sudo privileges.

Install Nginx Web Server

For a production environment, you need to install the Nginx web server on your server. Install it using the following command.

				
					apt install nginx -y
				
			

After installing Nginx, start and enable the Nginx service using the following command.

				
					systemctl start nginx
systemctl status nginx
				
			

Install Python and Other Dependencies

Django is Python based application. So you will also need to install Python and other required dependencies to your server. Install all of them with the following command.

				
					apt install python3-pip python3-dev libpq-dev curl -y
				
			

Once all the packages are installed, verify the Python version with the following command.

				
					python3 --version
				
			

You should see the Python version in the following output.

				
					Python 3.10.6
				
			

Next, update the PIP to the latest version using the following command.

				
					pip3 install --upgrade pip
				
			

Then, install the virtual environment package using the following command.

				
					pip3 install virtualenv
				
			

Once you are finished, please proceed to the next step.

Install and Configure PostgreSQL Database

Django uses PostgreSQL as a database backend. Install it with the following command.

				
					apt-get install postgresql postgresql-contrib -y
				
			

After the successful installation, connect to the PostgreSQL shell with the following command.

				
					su - postgres
psql
				
			

Next, create a user and database for Django with the following command.

				
					CREATE DATABASE djangodb;
CREATE USER djangouser WITH PASSWORD 'password';
				
			

Then, assign all required roles to the Django database.

				
					ALTER ROLE djangouser SET client_encoding TO 'utf8';
ALTER ROLE djangouser SET default_transaction_isolation TO 'read committed';
ALTER ROLE djangouser SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE djangodb TO djangouser;
				
			

Finally, exit from the PostgreSQL shell with the following command.

				
					\q
exit

				
			

Create a Django Project

Before creating a Django project, create a directory to hold the project.

				
					mkdir ~/djangoproject
				
			

Next, navigate to the project directory and create a Python virtual environment for the Django project.

				
					cd ~/djangoproject
virtualenv djangoenv
				
			

Then, activate the virtual environment with the following command.

				
					source djangoenv/bin/activate
				
			

Next, install the Django and other required dependencies inside the Django virtual environment.

				
					pip install django gunicorn psycopg2-binary
				
			

Finally, create a Django project with the following command.

				
					django-admin startproject djangoproject ~/djangoproject
				
			

Next, verify all files created by the above commands using the following command.

				
					ls -l djangoproject/
				
			

You should see all files in the following output.

				
					-rw-r--r-- 1 www-data root 403 Mar 17 15:09 asgi.py
-rw-r--r-- 1 www-data root 0 Mar 17 15:09 __init__.py
drwxr-xr-x 2 www-data root 4096 Mar 17 15:12 __pycache__
-rw-r--r-- 1 www-data root 3445 Mar 17 15:11 settings.py
-rw-r--r-- 1 www-data root 755 Mar 17 15:09 urls.py
-rw-r--r-- 1 www-data root 403 Mar 17 15:09 wsgi.py

				
			

Configure Django Project

At this point, the Django project is created. Now, you will need to edit the Django configuration file and define your database settings.

				
					nano ~/djangoproject/djangoproject/settings.py
				
			

First, change the following line to define your domain name.

				
					ALLOWED_HOSTS = ['django.example.com', 'localhost']
				
			

Next, remove the following default database settings:

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

				
			

And, add your PostgresQL database settings:

				
					DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'djangodb',
'USER': 'djangouser',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',

}
}


				
			

Then, add the following lines at the end of the file.

				
					STATIC_URL = '/static/'
import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

				
			

Save and close the file when you are done. Next, migrate the database settings using the following command.

				
					./manage.py makemigrations
./manage.py migrate
				
			

Then, create a super user to secure the Django web interface.

				
					./manage.py createsuperuser
				
			

You will be asked to set up a user and password as shown below.

Next, copy all static files to the desired location.

				
					./manage.py collectstatic
				
			

Start Django Project

You can now run the Django project with the following command.

				
					./manage.py runserver 0.0.0.0:8000
				
			

Once the Django is started, you will see the following screen.

Now, open your web browser and access the Django default dashboard using the URL http://django.example.com:8000/. You should see the following screen.

To access the Django admin interface, type the URL http://django.example.com:8000/admin/. You will see the Django login page.

Provide your admin username, password and click on the Login button. You should see the Django admin dashboard on the following screen.

Now, press the CTRL+C on your terminal interface to stop the Django. Next, deactivate from the virtual environment using the following command.

				
					deactivate
				
			

Create a Systemd Service File for Django

At this point, Django is installed and configured. However, you need to start Django every time after the system reboot. So, it is a good idea to create a systemd file to start the Django project at system reboot.

First, create a Gunicorn socket file with the following command.

				
					nano /etc/systemd/system/gunicorn.socket
				
			

Add the following configuration.

				
					[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

				
			

Then, create a Gunicorn system service file for Django.

				
					nano /etc/systemd/system/gunicorn.service
				
			

Add the following configuration.

				
					[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=root
Group=www-data
WorkingDirectory=/root/djangoproject
ExecStart=/root/djangoproject/djangoenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock djangoproject.wsgi:application

[Install]
WantedBy=multi-user.target
				
			

Save and close the file then set the ownership of the Django project directory to www-data.

				
					chown -R www-data:root ~/djangoproject
				
			

Next, reload the systemd daemon to apply the changes.

				
					systemctl daemon-reload
				
			

Next, start and enable the Gunicorn service with the following command.

				
					systemctl start gunicorn.socket
systemctl enable gunicorn.socket
				
			

You can now verify the status of the Gunicorn with the following command.

				
					systemctl status gunicorn.socket
				
			

Configure Nginx to Serve Django Project

Next, create an Nginx virtual host configuration file to serve the Django project on port 80.

				
					nano /etc/nginx/conf.d/django.conf
				
			

Add the following configuration.

				
					server {
listen 80;
server_name django.example.com;
location = /favicon.ico { access_log off; log_not_found off; }


location /static/ {
root /root/djangoproject;
}

location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}

				
			

Save and close the file then restart the Nginx service to apply the change.

				
					systemctl restart nginx
				
			

You can now access your Django project using the URL http://django.example.com.

Thank you for reading this article blog Django Create Project – How to Create Django Project Tutorial. We shall conclude. 

Django Create Project - How to Create Django Project Tutorial

The Django software has made Python web development easier. It is the best option for developers worldwide owing to its built in capabilities and adherence to the MVC model. Finally, Django gives programmers the tools they need to quickly and simply create sophisticated, scalable, and secure online applications due to its thriving community and rich ecosystem of plugins and frameworks.

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x