How to Setup Django with MySQL Database on Ubuntu 22.04

How to Setup Django with MySQL Database on Ubuntu 22.04. In this post, we introduce Django, its features and advantages. After,  we navigate through steps of how to set up Django with MySQL on Ubuntu 22.04 server.

What is Django?

First of all, Django is a popular web development framework written in the Python programming language. It provides professional developers with an extensive development skillset and allows them to rapidly build complex database driven websites.

Secondly, Django’s stack development approach simplifies the process of web application creation, making it accessible to anyone with basic programming knowledge. All in all, it has many advantages over more traditional approaches, such as scalability and flexibility, which make it ideal for larger projects.

With its versatile features, Django stands out among other popular web frameworks in terms of usability, scalability, and efficiency in web development tasks.

Moreover, Django allows developers to build highly interactive websites with minimal effort. It’s modularity makes it easy to add new features or customize existing ones without having to rewrite code from scratch. Additionally, its built in security measures protect against malicious attacks, while its ORM (Object Relational Mapper) simplifies data management tasks such as querying databases and creating models. Furthermore, Django’s scalability ensures that applications easily expand as the user base grows.

Features of Django

In addition, Django can be used by both new and experienced developers alike due to its extensive support for various features, such as form handling and user authentication. Other features include:

  • Written in Python – Django being a web framework for Python programming language, it provides an efficient solution for the development of web applications. It enables developers to rapidly build and deploy applications with a nice ready to use functional set of components. When creating customized web apps, programmers also save time by reusing existing code and avoiding the need to write new code.
  • API support – It offers useful APIs that make it easy to create websites with more complex features than traditional HTML coding. Furthermore, Django also includes a powerful set of application programming interfaces (APIs) that enable developers to quickly build dynamic websites with account authentication and website content handling capabilities.
  • Interface – Django also has a powerful administrative interface which makes managing the website easier as well as allows for customization of content, including static files and media.
  • Compatible with different operating systems – What is more, with Django it can be used in systems like macOS, Linux, and Windows for application development and administrative activities.

Advantages of Django

Besides, Django is a powerful web framework that enables developers to quickly and easily create complex, database driven websites. It is an open source platform that offers a wide range of advantages for developers, including scalability and flexibility. Other benefits of Django include:

  • Excellent Security Features – Popular amongst developers due to its robust security features which make it perfect for web development projects. With Django, developers easily access data from any source without having to worry about security breaches or malicious activities on their websites. Well, it transmits data using the Get Method while encrypting all passwords and other sensitive data.
  • Community Support – Another advantage of this python framework is its vast community support network where programmers get advice and assistance whenever needed.
  • Simple to Scale and Extend – By making a few adjustments to the web applications’ decoupled components, the framework enables developers to create complex web apps faster. In nutshell, it makes it simple for developers to grow, modify, and customize the web framework. Additionally, programmers disconnect or swap out these detached components based on the needs of their projects.

We have reached the main part of the article How to Setup Django with MySQL Database on Ubuntu 22.04.

How to Setup Django with MySQL Database on Ubuntu 22.04

In this section, we show you the installation steps of Django with MySQL database on Ubuntu 22.04 server.

Prerequisites

  • An Ubuntu 22.04 server is installed on your system.
  • A root user or a user with sudo privileges.

Step 1 - Getting Started

Before starting, you need to update all your system packages to the latest version. Please, update all of them with the following command.

				
					apt update -y
apt upgrade -y
				
			

After updating all the system packages, verify your Python version using the following output.

				
					python3 -V
				
			

You will get the version information in the following output.

				
					Python 3.10.4
				
			

Next, install other Python dependencies using the following command.

				
					apt install python3-venv python3-pip -y
				
			

You can now verify the PIP version using the following command.

				
					pip3 --version
				
			

You will get the following output.

				
					pip 22.0.2 from /usr/lib/python3/dist-packages/pip (python 3.10)
				
			

Step 2 - Install Apache Web Server

Basically, you also need to install the Apache web server on your system. Certainly, you install it with the following command.

				
					apt install apache2 libapache2-mod-wsgi-py3
				
			

After the successful installation, start and enable the Apache service using the following command.

				
					systemctl start apache2
systemctl enable apache2
				
			

Once your are done, you proceed to install the MySQL server.

Step 3 - Install and Configure MySQL Server

First, install the MySQL server with other libraries using the following command.

				
					apt install mysql-server libmysqlclient-dev -y
				
			

Next, start the MySQL service and enable it to start at system reboot.

				
					systemctl start mysql
systemctl enable mysql
				
			

Now, verify the MySQL version using the following command.

				
					mysqld --version
				
			

You will get the following output.

				
					/usr/sbin/mysqld Ver 8.0.31-0ubuntu0.22.04.1 for Linux on x86_64 ((Ubuntu))
				
			

Next, log in to the MySQL console with the following command.

				
					mysql
				
			

After login, create a database and user for Django using the following command.

				
					CREATE DATABASE djangodb;
CREATE USER 'djangouser'@'localhost' IDENTIFIED BY 'yourpassword';

				
			

Next, grant all the privileges to the Django database with the following command.

				
					GRANT ALL ON djangodb.* TO 'djangouser'@'localhost';
				
			

Following that, flush the privileges and exit from the MySQL shell with the following command.

				
					FLUSH PRIVILEGES;
EXIT
				
			

Step 4 - Install and Configure Django

Before installing Django, create a directory for Django inside the Apache web root.

				
					mkdir /var/www/html/django
				
			

Navigate to the Django directory and create a Python virtual environment.

				
					cd /var/www/html/django
python3 -m venv django_env
				
			

Now, activate the virtual environment with the following command.

				
					source django_env/bin/activate
				
			

Now, install Django using the following command.

				
					pip install django
				
			

You will get the following output.

				
					Collecting django
Downloading Django-4.1.5-py3-none-any.whl (8.1 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 8.1/8.1 MB 35.9 MB/s eta 0:00:00
Collecting sqlparse>=0.2.2
Downloading sqlparse-0.4.3-py3-none-any.whl (42 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 42.8/42.8 KB 12.8 MB/s eta 0:00:00
Collecting asgiref<4,>=3.5.2
Downloading asgiref-3.6.0-py3-none-any.whl (23 kB)
Installing collected packages: sqlparse, asgiref, django
Successfully installed asgiref-3.6.0 django-4.1.5 sqlparse-0.4.3
				
			

After the installation, verify the Django version with the following command.

				
					django-admin --version
				
			

You should see the Django version in the following output.

				
					4.1.5
				
			

Next, install the MySQL client package with the following command.

				
					pip install mysqlclient
				
			

Now, create your Django project with the following command.

				
					django-admin startproject djangoapp .
				
			

Then, edit the Django configuration file with the following command.

				
					nano djangoapp/settings.py
				
			

Add your server IP and domain name as shown below:

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

Next, remove the following lines:

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

				
			

And, add the following lines:

				
					DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'djangodb',
'USER': 'djangouser',
'PASSWORD': 'yourpassword',
'HOST': '127.0.0.1',
'PORT' : '3306',
}
}
				
			

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

				
					import os

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

MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'media/')

				
			

Save and close the file when you are done. Then, migrate the database with the following command.

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

				
			

You will get the following output.

				
					Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK

				
			

After that, create an administrative user for Django:

				
					./manage.py createsuperuser
				
			

Define your admin username and password as shown below.

				
					Username (leave blank to use 'root'): admin
Email address: hitjethva@gmail.com
Password:
Password (again):
Superuser created successfully.
				
			

Next, copy all files from your static folders into the STATIC_ROOT directory:

				
					./manage.py collectstatic
				
			

Finally, deactivate from the Python virtual environment:

				
					deactivate
				
			

Step 5 - Configure Apache for Django

At this point of time, you need to create an Apache virtual host configuration file for Django. You create it with the following command.

				
					nano /etc/apache2/sites-available/django.conf
				
			

Add the following configurations.

				
					<VirtualHost *:80>

ServerAdmin admin@example.com
ServerName django.example.com

DocumentRoot /var/www/html/django

ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined

Alias /static /var/www/html/django/static
<Directory /var/www/html/django/static>
Require all granted
</Directory>

Alias /media /var/www/html/django/media
<Directory /var/www/html/django/media>
Require all granted
</Directory>

<Directory /var/www/html/django/djangoapp>
<Files wsgi.py>
Require all granted
</Files>
</Directory>

WSGIDaemonProcess djangoapp python-path=/var/www/html/django python-home=/var/www/html/django/django_env
WSGIProcessGroup djangoapp
WSGIScriptAlias / /var/www/html/django/djangoapp/wsgi.py

</VirtualHost>

				
			

Save and close the file then activate the Django virtual host with the following command.

				
					a2ensite django.conf
				
			

Finally, restart the Apache service to apply the changes.

				
					systemctl restart apache2
				
			

In here, set proper permission and ownership to the Django directory.

				
					chown -R www-data:www-data /var/www/html/django
chmod -R 775 /var/www/html/django

				
			

Step 6 - Access Django Web Interface

At this point, Django is installed and configured with MySQL and Apache.

 

  1. Access the Django admin interface using the URL http://django.example.com/admin. You should see the Django login page:

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

3. You can also access Django directly using the URL http://django.example.com. You should see the Django website sample page on the following screen.

Thank you for reading How to Setup Django with MySQL Database on Ubuntu 22.04. We shall conclude this article now. 

How to Setup Django with MySQL Database on Ubuntu 22.04 Conclusion

Summarizing, in this article blog, you have learned how to set up Django with MySQL and Apache on Ubuntu 22.04 server. You can now host Python applications easily on the Django platform. Finally, Django is a Python based open source web framework that allows users to quickly create robust websites and user interfaces. It is versatile, powerful, and easy to use. Comes with great libraries to help programmers build applications quickly and efficiently. Moreover, with its fast web development process, it is possible to develop complex systems from scratch in no time at all.

Lastly, this open source web framework is simple to understand and enables programmers to easily create unique web apps. With it’s robust security system, it prevents malicious attacks from happening on your website. Moreover, its scalability makes it ideal for creating large websites with high traffic levels. Check about the above listed features and benefits to get a better understanding of Django.

Feel free to explore more Django content in our blog by clicking here

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.

5 1 vote
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