Hello World Basic Django App

PURPOSE

To create a Web App that focuses on scalabality & securtiy, "Django" is the go to framework in Python. It's a feature rich solution that enforces best practices from the ground up.

The Author assumes that you have some basic understanding of working with Python 3.

Step 0: [Optional] Creating a virtual environment and activating it.

If you're on Windows, open command prompt and type:

Step 1. Initial Setup:

Installing Django framework using pip

Creating a new project

  • Take a look at your project directory. Why so many files, I wonder?
  • Visit localhost:8000 on your browser. Oh look, it's Django, saying hello to you!

Creating an app inside the project

  • Take a look at your directory structure again. Wonderful, isn't it? Confusing, but wonderful!

Step 2: Let's some write code:

Open your project in your favorite text editor Vim!

Inside your first_app folder, you will see a views.py file

Open it, and modify the code so it looks like this:

  • The comments can be ommited, they are for explanatory purposes only.

Create & Open first_app\urls.py

Add the following to it:

We must add first_app app's urls to our learning_django app's urls.py file

Open learning_django\urls.py:

Modify it to:

  • A separate urls file for each app adds clarity.
  • We can scan through all the urls files to know what all endpoints are there
  • To understand the routes, we don't need to view the internal logic (i.e. views) and vice-versa.
  • It is also easier to mantain and update paths this way.

Open learning_django\settings.py

Add first_app to your installed apps:

Step 3: Now, run the server again and visit localhost:8000\first_app

  • You would be greeted with the Hello World message that you wrote in your views.

Voila! You have successfully hosted a Django Web App on your local machine and served your own response on an endpoint!

Thank the author. Fork this blog.


Tagged in django