We earn commission when you buy through affiliate links.

This does not influence our reviews or recommendations.Learn more.

Django is the most used Python web development framework.

Url shortener

It is fast, reliable, and has a lot of built-in features.

For instance, a hole authentication system, that lets you focus on the main features of your app.

But lets expose some facts.Djangois such a huge framework that sometimes is challenging to get started with it.

Django demo app

So today you are going to build from scratch a totally functional Django software.

But if you dont have experience with any of these, dont worry.

The most important step is the first.

MVT pattern

All the working code will be available on thisGithub repo.

Now that you have crystal flush the previous concepts, lets get into the matter.

Project statement

In this tutorial, you are going to build a URL shortener.

Article image

Lets see it with a graphic.

Thats exactly what you are going to build today.

Structure of a Django project

Basically, a Django website is built upon a singleprojectand multiple separatedapps.

Article image

Each one of these apps has specific functionality and its able to work by itself.

Lets imagine a complex web tool likeStackoverflow.

Its functionality is based on two main aspects.

Article image

So following the Django website structure, the project would be namedStackOverflowwhich has two main apps.

Each of these apps has self-contained functionality.

That means that both contain all the code that they need to work properly.

Article image

This means that any Django app could be reused since they are able to work by themself.

It is the most efficient way to maintain a specific set of dependencies.

But its main purpose is to isolate the development packages from the global ones.

Django URL shortener success

So lets create a virtual environment with python the built-in form command.

Note:This method requires Python 3.6 or newer versions to work.

This command uses thepython -morpython modcommand.

Success Redirect

Fundamentally it runs a module or library, as a script.

So in plain language, this command means.

To assert that you have zero packages installed in the new venv, you run.

If you activated the virtual environment correctly, you wont get any output.

Thats because we havent installed anything yet.

Django is a third-party package, therefore we need to install it withPip(Pip Installs Packages).

Note:Remember that$is nothing but your shell symbol.

To peek if the installation went correctly, we check again the installed packages of our venv.

Dont worry if the versions you get are different from mine.

If Django stills on version 3.x you’re able to continue without any problem.

Do you remember what is a Django project?

Lets create one by running the following command.

Is important to emphasize thatconfigcan be any name you want.

The reason I use config as the name of this project is just because of convenience.

Its nice to switch between projects and still have the same naming convention.

So dont be afraid of using other project names whenever you want.

As you may notice now you have aconfig/folder and inside, there are many files.

Later we will see the file structure of the project.

For now, lets enter the project directory and trigger the local server.

The most important file you will be using is themanage.pyscript.

Now lets see if everything is working properly.

Creating the Url shortener app

Its time to create the main app of the project.

You are going to use themanage.pyfile to accomplish this task.

This creates a Django app, with the nameurlshortener.

If you run thetreecommand, youll get something like this.

Lets clarify the different files created until this moment.

config is the name of our project and it is named like that just for the convention.

It defines the URL paths of all the applications inside of the project.

Dont worry too much about theasgi.pyandwsgi.pyfiles.

These are files that let you configure your program in deployment.

Themanage.pyis the python script that lets you run all the available commands ofDjango-admin.

apps.pyis where the app configuration lives.

Usually, you dont mess around with it, except you are doing pretty advance stuff.

admin.pyis where you register yourmodelsto make them visible inside the Django admin panel.

models.pyis the most important one.

Youll hear more about models later.

migrations/is the folder where Django migrations are stored.

We will take an in-depth look later.

tests.pyis the file where the tests are stored.

We wont cover testing in this tutorial.

views.pyis the file that stores views.

Basically, it defines how the user will interact with all the aspects of your app.

Installing a Django app

Before continuing, open thesettings.pyfile and modify theINSTALLED_APPSvariable by adding the urlshortener app.

This is a routine process when you create an app.

So every time you do it, dont forget to install it on the project controls.

It is based on 3 main concepts.

Between that process occurs the business logic.

I know that business logic is a pretty obscure concept, so let me explain exactly what it is.

Business logic is the way data is created, stored, and deleted, thats all.

Finally, templates are text documents (Usually Html) that are shown to the users.

Its purpose is to present data as clean as possible.

First of all, lets define the shortener model inside of themodels.pyfile.

It is a pretty huge class, with a lot of weird stuff going on, but dont despair.

Ill go step by step on each important thing.

Model explanation

First of all, we import themodelsmodule.

This module contains all of the functionality we need to create a Django model.

Taking a look at the Shortener model, the first thing to note is that it extendsmodels.Model.

In fact, any model in any Django app must be a subclass of themodels.Modelclass.

Then we define all the fields the model will have on the database.

We use the argumentauto_now_add=Truebecause we want the field to only be altered when the instance is created.

The second fieldtimes_followedrefers to the times the shortened URL has been used.

It is aPositiveIntegerFieldand we specify a default of zero.

That means that every time an instance has created thetimes_followedfield, Django will fill out that field with 0.

On the other hand,long_urlrefers to the URL the user inputs.

The last field isshort_url, and it has interesting details.

The__str__method tells how the model must be printed.

Now its time to look up a way to save the short link in a random way.

Creating shortening functionality

We are going to create 2 custom functions.

To do this, create a file utils.py inside the urlshortener app.

Inside of this file, we are going to use the choose function from the random built-in module.

This facilitates the task of choosing random characters to create the code.

Lets do some math.

So we can forget about getting out of random shortened URLs.

This is a problem since we set up theshortened_urlfield to be unique.

Thats why the following function is so useful.

Lets see whats happening here.

The function takes as an argument a Shortener model instance.

First, the function generates a random code using thecreate_random_code.

Then it gets the modelclassand checks if there is any other object that has the sameshort_url.

If it does it runs itself one more time, but if everything is fine it returns the random_code.

Later you will interact with the shell, to make it take a look at this function closely.

After creating the utility function, lets use it to create random codes in the shortener model.

The save method is being overwritten, which means you are introducing new functionality to a pre-existing parent method.

Running migrations

Now its time to make and execute the migrations of the Shortener model.

To do that fire off the following commands in the root project folder.

For now, you dont have to worry about what migrations are.

Lets create some objects with the Django shell.

Thats pretty much how all shortener objects will work.

So lets see how to create a hello world view.

Basic template response

Inside of urlshortener/views.py file create a functionhome_view.

aa

It returns a simple message Hello world.

Later you will see how it looks in the net surf tool.

Now create a urls.py, there will stand all the URL patterns of the app.

touch urls.py

Add the following code.

Theappnamevariable declares (as its name suggests) the namespacing of the urlshortener app.

Thenameattribute is the namespace of the path, that can be called inside templates if necessary.

Now, lets modify the overall project URLs.

Now lets execute the server again.

If you trigger the server, youll get a simple Hello world message.

This is because you are including the urlpatterns from the URL shortener app, into the overall project.

This is just a starting point.

Now its time to create a form to let the user create Shortened URLs by themselves.

Creating forms

In Django, aformis a simple class that allows getting input from the User.

You are going to create a forms.py file.

It is a convention to store all the forms of the app in that file.

Inside of that file you are going to create a class ShortenerForm which extends from ModelForm.

It is a model form since its purpose is to create a model object from the user input.

This is because we are going to stylize the app withbootstraplater.

Navigate to theviews.pyfile inside the shortener app, and modify thehome_viewview.

you could check out theGithub repoat this moment to get an idea of how the project structure looks like.

You will need to import the Shortener model and form.

You still using a function since I want you to understand all the data flow of the view.

Also, youll be using the path for a template (Which is not created yet).

Later youll see how to implement the error display in the template.

Redirect view

Theredirect_url_view, is a little bit simpler.

It is a detailed view which means, the view only works with an object.

This function takes as parameters, the users request and theshortened_partof the URL.

We protect the view with atry/exceptstatement, in case the shortened part isnt found in the database.

Creating templates

You are almost there.

The only thing that separates you from having built this app is the user interface.

For that, we use Django templates.

Templates are used to render a clean interface to the app user.

Base template

Django allows template inheritance.

Home template

The home template, inherence from the base.html file.

That means that this template includes all the HTML from the parent file.

Ill quickly explain the data flow of this template:

Final tool

Congratulations!

Youve built a complete functional URL shortener app with Django.

Here are some screenshots of how the program looks like.

When you are done, send a pull request and ping me onTwitterto showcase your achievements.

Youve reached the end of this tutorial.

Believe it or not, you just reviewed all the main aspects of creating a Django project.

I hope you found it extremely useful.