How to deploy a django project on Beget

Introduction and example files

This article provides detailed instructions on how to host a website written in Django on the servers of the hosting provider beget.
The process of placing a website on Beget hosting using the example of a simple website that I made in a couple of hours.
Here is the archive for download. And the domain name that I will use is a free domain that is given as a gift from this hosting provider. Here it is timachuduk.bget.ru.
This article assumes that you have already registered with beget hosting and registered or transferred a domain.

How to link a domain to beget hosting

What does it mean to link to a domain? This is when you assign a certain directory to a domain. How do I do it?
  • Select (or create) a directory.
    beget website choosing domain
  • In the websites section, click create
    beget website creating domain
  • Select an existing domain
    beget website linking domain
Now that the domain has been connected, you can go to the terminal and connect to the server.

Connect to the server via SSH and install Python

Installing openssl

We connect to the remote server terminal.

ssh USERNAME_PLACEHOLDER@USERNAME_PLACEHOLDER.beget.tech
	
Now, go into the docker container.

ssh localhost -p222
	
And now we go to the temporary directory, where we will download the necessary programs.

cd ~/.beget/tmp/
	
If there is no such directory, you need to create one.

mkdir ~/.beget/tmp
	
And come again.

cd ~/.beget/tmp/
	
Download the archive with the latest version of openssl. This package is required to run Python 3.11 and higher.

wget https://www.openssl.org/source/openssl-1.1.1l.tar.gz
	
Unpack the OpenSSL archive

tar -xvzf openssl-1.1.1l.tar.gz 
	
Now, go into the unpacked archive.

cd openssl-1.1.1l
	
Let's generate a make file

./config --prefix=$HOME/.local --openssldir=$HOME/.local/ssl '-Wl,--enable-new-dtags,-rpath,$(LIBRPATH)'
	
Compile and install the program on the server

make -j$((`nproc`/4)) && make install
Once OpenSSL is installed, you can proceed with installing python. It is important to note that Python version 2.7 is already installed on the system. But, since I personally don’t like this version, and it is also very outdated and almost no one uses it anymore, we will install Python version 3.11.0.

Installing Python

Let's go to the next directory. We are still in docker.

cd ~/.beget/tmp/
	
Download the archive with the required version

wget https://www.python.org/ftp/python/3.11.0/Python-3.11.0.tgz
Unpacking the archive

tar -xvzf Python-3.11.0.tgz 
	
Let's go to the unpacked directory

cd Python-3.11.0
Run the makefile generation script

./configure --prefix=$HOME/.local --with-openssl=$HOME/.local --with-openssl-rpath=auto --enable-optimizations --enable-loadable-sqlite-extensions LDFLAGS="-Wl,-rpath /usr/local/lib"
Compile and install Python on the server

make -j$((`nproc`/4)) && make install
	
This is a command to check the python version.

python3 -V
	

Creating a virtual work environment

Now that we have Python on the server, we can start creating a virtual environment. What is a virtual environment, and why should I even use it? You ask.
This is an isolated environment with all the necessary libraries, programs, and scripts that allow you to create applications in Python, regardless of the main system on which the application is located. I will answer.
Chevron Well, why should you do this? If you have several applications that require different versions of packages or versions of Python, then you will have to create a virtual environment for them. Because one feature of Linux systems is that the libraries on the servers are shared, it will not be possible to use anything more outdated.
Let's return to setting up the server. We are still in a Docker container.
We go to the project directory, where the site will be located. The name will be identical to that of your purchased domain.
Return to the home directory

cd ~
Go to the project directory.

cd timachuduk.beget.tech
	
Let's create a virtual environment .

~/.local/bin/python3.11 -m venv .venv
After creating the environment, don't forget to activate it !

source .venv/bin/activate
To check whether the environment is activated, run the command

which python
This command will display the path to the specified command. If the path contains the directory of the created virtual environment, we are ready to continue. Namely, we will install the required minimum packages.

pip install django==4.1 pillow
Chevron The pillow package is optional, but it is required for the ImageField model field to work. And since images are used everywhere, I decided that you needed to know this.

Uploading a Django website to hosting

Transferring a django project to beget hosting

On a local machine, that is, on your computer, create an archive and directories for your site or project.

tar -czf HowToPublishYourWebsite_moved.tar.gz HowToPublishYourWebsite
Using the scp command , we will move the archive of site files to the server.

scp HowToPublishYourWebsite_moved.tar.gz USERNAME@HOSTNAME:~/timachuduk.beget.tech/
	
timachuduk.beget.tech is the directory where we recently created a virtual environment.
Go back to the remote server (you're still in Docker) and navigate to the archive.

cd ~/ timachuduk.beget.tech
	
Start a new project with the same name as the one you want to transfer.

django-admin startproject HowToPublishYourWebsite
	
Let's create a temporary directory

mkdir trans
	
Now let's unarchive the archive ;)

tar -xzf HowToPublishYourWebsite_moved.tar.gz -C trans
	
It should be noted that I am lazy and have archived everything. Including the database and Python cache files. Let's delete them. Don't worry, I'll talk about database migration separately.

rm trans/HowToPublishYourWebsite/db.sqlite3 trans/HowToPublishYourWebsite/manage.py HowToPublishYourWebsite_moved.tar.gz
	
Now let’s transfer all the necessary files to the previously created project folder HowToPublishYourWebsite

cp -r trans/HowToPublishYourWebsite/* HowToPublishYourWebsite
	
Delete the temporary directory

rm -r trans
	
Now you will need to add configuration files and slightly edit the files on our site.

Setting up additional configuration files

Create a file, passenger_wsgi.py

touch ~/timachuduk.beget.tech/passenger_wsgi.py
	
This is what should be inside

import os, sys
sys.path.insert(0, '<полный_путь_до_каталога_с_проектом>')
sys.path.insert(1, '<полный_путь_до_Django>')
os.environ['DJANGO_SETTINGS_MODULE'] = '<название_проекта>.settings'
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
		
For example, here is the contents of my file

import os, sys
sys.path.insert(0, '/home/t/timachuduk/timachuduk.beget.tech/HowToPublishYourWebsite')
sys.path.insert(1, '/home/t/timachuduk/timachuduk.beget.tech/.venv/lib/python3.11/site-packages')
os.environ['DJANGO_SETTINGS_MODULE'] = 'HowToPublishYourWebsite.settings'
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
	
Edit the settings.py file. You need to add your domain to ALLOWED_HOSTS. In mycase,e it will be timachuduk.beget.tech.
Chevron It is not necessary to add a second version of your domain, but in the future, Google will complain, and this will affect the ranking of your site, so it is better to add a second version of the domain with www.

ALLOWED_HOSTS = ['timachuduk.beget.tech', ‘www.timachuduk.beget.tech’]
	
Also, if you have DEBUG = True, change it to False
Creating a file called .htaccess

touch ~/timachuduk.beget.tech/.htaccess
	
This is what should be inside

PassengerEnabled On
PassengerPython /home/t/timachuduk/timachuduk.beget.tech/.venv/bin/python
	
All that remains is to create the tmp directory and the restart.txt file in it

mkdir ~/timachuduk.beget.tech/tmp; touch ~/timachuduk.beget.tech/tmp/restart.txt
	
Let's check the functionality of this site. Enter the address timachuduk.beget.tech (Of course, replace my domain with yours). You will see the following if everything works.
Default looking stuff for not edited website

How to reload a Django website if you make changes to it

Let's say you've changed a couple of your templates and want to see how they look and whether they work at all. If you do nothing, the Beget servers will be updated in about 4 to 12 hours. Not cool.
For the changes to take effect immediately, you will need to recreate one file. Here's the command:

touch ~/timachuduk.beget.tech/tmp/restart.txt
	
Just don’t forget to substitute the directory where your site is located.

How to transfer a database

I created a small model and a page to replace the main one. To demonstrate connecting a database.
First, you will need to uncomment several paths. In the urls.py file in the HowToPublishYourWebsite directory, uncomment the path to the ‘Main’ application

path(‘’, include(‘Main.urls’)),
	
Reload the site (recreate the restart.txt file). And you'll see something like this.
At the start, your database will not be accessable, server error via beget hoster
Do not worry, all is fine. You just need to transfer the database from your local machine to the server. To do this, create a database on beget hosting, that is, on the website.
Beget, creating database
Remember or write down the password and database name. After that, open the settings.py file
And edit it like this.

DATABASES = {
	‘default’ : {
		‘ENGINE’: ‘django.db.backends.mysql’,
		‘NAME’: ‘NAME_OF_DATABASE’,
		‘USER’: ‘NAME_OF_DATABASE’,
		‘PASSWORD’: ‘YOUR_PASSWORD’,
		‘HOST’: ‘localhost’,
		‘PORT’: 3306,
	}
}
	
Where instead of NAME_OF_DATABASE is the name of your database.
Where instead of YOUR_PASSWORD is the password for your database.
Now that the database is created and configured, you will need to create database migrations. We go to Docker, activate the environment, and create migrations.

ssh localhost -p 222
	

cd ~/timachuduk.beget.tech/
	

source .venv/bin/activate/
	

cd HowToPublishYourWebsite
	

./manage.py migrate
	
The database has been created and is ready to be populated and transferred. If you update the site you will get something like this. The truth is not impressive, but everything works and functions, you just need to transfer the database, that is, fill your empty database with the database that is located in your project on the local machine.
Empty page, without errors beget, django
On your local machine, where you still have the database, run the following command:

./manage.py dumpdata --exclude auth.permission --exclude contenttypes > data.json
	
Move the dump to the server.

scp data.json timachuduk@timachuduk.beget.tech:~/timachuduk.beget.tech/HowToPublishYourWebsite/
	
Run the following command on the server.

./manage.py loaddata data.json
	
And voila, the database is now migrated and fully functional. But the paths to the media files are still not configured, and therefore the pictures are not loaded. See below for more information.
Page with data on it from database, without errors beget, django

How to automate the process of transferring media files

After transferring the database, you probably noticed, if you turn on the console in your browser, that it (the browser) cannot find images of our posts. And all because we need to move the media folder to the already existing public_html directory.
Chevron Of course, your folder doesn’t have to be named media; you can give it any other name in settings.py, I’m just used to it.
The situation is similar with static files. They should also be in public_html. And of course, you can’t do it manually. To automate the process, you need to:
  • Open the settings.py file of your site and modify these variables like this. That is, add public before media and static
    
    MEDIA_ROOT = os.path.join(BASE_DIR, 'public/media')
    STATIC_ROOT = os.path.join(BASE_DIR, 'public/static')
    			
  • 
    cd ~/timachuduk.beget.tech/public_html
    			
    
    ln -s ../public_html ../HowToPublishYourWebsite/public
    			
Now all new static files and media files will be redirected to public_html. Just don't forget to move old media files and collect static files.
As a result, the final page will look like this. With a working database and correct paths for media files.
Database working, on beget server using django
I hope this article was useful and sufficiently informative. And you were able to transfer your django project to the production server.

heart 0
3 connected dots 0

Comments

(0)
Avatar by default
None
Leave a comment
Leave a comment