DEV Community

Douglas Cueva
Douglas Cueva

Posted on

Continuing with Django 4.0

If you've completed the first part of this tutorial series you'll have learned how to get a Django project up and running.

In this next part, I'll be showing you how to wire up a Django app so you can produce the words "Hello, World!" on your web browser. In that journey, you'll get to see a little bit of Django's ecosystem.

I can't stress this enough, Django takes some time to get used to, but it's worth it. Much of its architecture is built to facilitate rapid deployment of a web application.

Projects versus Apps

In the previous tutorial, Django created a project for you called "hello_world". If you navigate into this folder, you will see many Python files that are used to configure different aspects of a project.

A note about Projects and Apps in the Django ecosystem.

Apps are components that can use the configuration of a Project.

Apps are separate from Projects, but the former refers to the latter when needed.

A Django app, for example, could have the functionality of a blog, forum, or wiki, while the project handles the way it is served up via a URL.

Django really embraces the design philosophy of separation of concerns.

Creating an app

Before creating an app, make sure that your virtual environment is activated by running the following command:

pipenv shell

You will know it's activated if the name of the directory, hello-world-project, appears in parenthesis in your terminal.

Make sure you're in the directory where you can see the manage.py file.

Once there, run the following command to create a Django app:

python3 manage.py startapp greet

The terminal will take a couple seconds before it returns control to you, but once done, if you type in the command ls to list the directories, there should be a new folder called greet. This is your Django app.

Configuring an app

If you haven't done so already, cd into the greet directory. There should be a list of various Python files. This should look similar if you took a peak into the hello_world project folder.

Below is a rundown about what each file does.

File Description
apps.py conrols settings specific to the app
models.py database functionality
admin.py defines an admin interface related to the app
urls.py provides url routing
views.py logic and control flow for handling requests
test.py used for writing unit tests
migrations folder Django uses this for database migrations

As you can see, Django is perfect for implementing websites that make use of the MVC architecture (Model View Controller).

To configure the greet app, you'll begin by defining the View for the project.

Views

What's a View? Well, it basically handles HTTP requests and responses.

In Django this functionality is left to the views.py file. Open that file with your favorite text editor (I use Vim because it makes me feel like a ninja), and type the following:

from django.shortcuts import render
from django.views.generic import TemplateView

# Create your views here.

class HomePageView(TemplateView):

   template_name = "home.html"


Enter fullscreen mode Exit fullscreen mode

Here's a quick summary of what you've written.

The first import, render, is something that Django provides for you. The next import is the TemplateView class, which is needed to render a template from the templates directory that you will make in the next few steps.

Next, you instantiated the TemplateView class, as a HomePageView class, and provided the template name "home.html".

The home.html still hasn't been created yet.

Urls

The next step to properly configure your greet app is to create the url pattern that the hello_world project will need to use the home.html file you'll create in the next few steps.

To do so, you'll have to manually create the urls.py file. To do this, you can run the following command on your terminal:

touch urls.py

This should create an empty Python file called urls.py. Now, open that file and type the following:

from django.urls import path

from .views import HomePageView



urlpatterns = [

    path('', HomePageView.as_view(), name="home"),

        ]
Enter fullscreen mode Exit fullscreen mode

A few things to note here

  • the first argument is a regex pattern to be used that will link to this page
  • the second argument is our class based view created in the views.py
  • the third argument is optional and we're giving it the shortcut name home so we can easily refer to it when using Django templates

Alright, you've made it this far. It's time to move onto the hello_world project, where you'll be connecting the configurations you've made to the greet app.

Configuring a project

Configuring a Django project can be confusing. Things change. I remember a few years ago when you had to use the Python os module in Django to find the templates directory.

In Django 4.X that isn't necessary and that's primarily why I created this tutorial series: to have a reference, out in the wild, on how to configure a templates folder.

Project urls.py

To begin configuring the hello_world project, create a gateway to your recently created urls.py file in you greet app.

Navigate to your hello_world project folder and open the urls.py file in your favorite text editor (again, I use Vim because it makes me feel great).

There's a lot going on in this file. You can spend time reading up on it later. For now, type the following into the file.

from django.contrib import admin

from django.urls import path, include



urlpatterns = [

    path('admin/', admin.site.urls),

    path('', include('greet.urls'))

]
Enter fullscreen mode Exit fullscreen mode

A few things to take note here:

  • first argument uses regex (regular expressions) to find the URL
  • include method allows for your urls.py within your story app to be wired up and used.
  • greet.urls is basically this: greet (folder) -> urls.py (file)

Understanding how the project links to your app is important. If you need to go back, do so; you'll have less migraines later.

Settings.py

This is the nucleus of your Django project. Everything needs to be declared here.

When you open this file for the first time, you will be overwhelmed with the amount of configuration that can be done. Again, you can read up on what can be done here at the Django Project's website.

What are you going to be doing here?

First, you're going to add the greet app to the list of applications Django uses.

Last, you'll be configuring the path for the templates folder that you will create later.

Begin by adding the following line, greet.apps.GreetConfig under INSTALLED_APPS

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',



    'greet.apps.GreetConfig',

]
Enter fullscreen mode Exit fullscreen mode

What is this? This is a call to a file in your greet app folder called apps.py. In that file you'll see there's a class called GreetConfig, that's instantiating AppConfig from django.apps.

Next, under TEMPLATES, establish the path the templates directory under 'DIRS'.

TEMPLATES = [

    {   

        'BACKEND': 'django.template.backends.django.DjangoTemplates',

        'DIRS': [BASE_DIR / 'templates'],

        'APP_DIRS': True,

        'OPTIONS': {

            'context_processors': [

                'django.template.context_processors.debug',

                'django.template.context_processors.request',               

                'django.contrib.auth.context_processors.auth',              

                'django.contrib.messages.context_processors.messages',  

            ],

        },

    },

]
Enter fullscreen mode Exit fullscreen mode

You're almost done!

What did you just write? BASE_DIR / 'templates'

This is telling Django to look for a folder called templates in the area where your manage.py file is. There is much debate on where to create your templates folder, but I've gone with the single-project level approach to make things easy.

Templates

The templates folder will hold your HTML files.

To properly create this folder, make sure you're at the directory level where you can see the manage.py file. Then, type the following into your terminal:

mkdir templates 
touch templates/home.html
Enter fullscreen mode Exit fullscreen mode

Next, navigate into the templates folder, and open the home.html file in your favorite text editor (I use Vim because it makes me feel productive).

Type the following into the home.html file.

<p>Hello, world!</p>
Enter fullscreen mode Exit fullscreen mode

Save your changes and head back to the directory level where the manage.py file is.

Hello, world!

You've made it this far. Give yourself a pat on the back.

Before producing the words "Hello, world!" on your browser, there's something that needs to be done first.

Remember the 18 migrations that needed to be done when you first created this app? Well, you're going to run a migration to eliminate that warning from appearing.

Make sure you're in the directory level where the manage.py file is and run the following in your terminal.

`python3 manage.py migrate

Next, type the following:

python3 manage.py makemigrations

Your terminal should say that there are no changes detected.

And finally, type this into your terminal:

python3 manage.py runserver

Navigate to your local server at http://127.0.0.1:8000

Felicitaciones! Congrats!

Your browser should say "Hello, world!"

Conclusion

You've gone through the various steps of configuring a Django app and a Django project. You also made a templates folder, and an html file, to produce the words "Hello, world!" on your local server.

What's next?

There's much this tutorial didn't cover, like models. There's also much to write about how to use templates.

You can also read more about Django on their website

Why not give William Vincent's blog a read? He goes more in depth with Django, and is an authoritative voice in the community.

One of my favorite things to do is to check out the latest Awesome Django projects

Top comments (0)