Django | Part 3 | Important Django concepts
In the previous article, we successfully installed the Django project. Before further editing the project, I will run through some fundamental Django concepts and components. These will make up how your Django project will be organised, how the backend server will manage data, and ultimately how it will communicate to the frontend client.
In this article, I will be focusing specifically on seven components:
- The project
- Apps
- Models
- Views
- Templates
- Forms
- URLs
1. The Project This is the overarching collection of the above seven components. These ultimately all tie together to make up your web application. We created the web project directory when we ran the following command in the last article.
#Create a Django project
django-admin startproject blog_website
Within the project directory, there are a couple of key files. The first one is the manage.py file. This is Django’s command line utility that allows you to take care of administrative tasks. These include the runserver command we used to start the server locally in the last article. We will go through more of these commands as we progress through this project.
The second file is the settings.py file, which we also adjusted. This file contains all of the core settings for your Django project, including the database to connect to, debugging settings and the directory of your static files.
2. Django Apps
The Django project’s root directory contains the different apps and their corresponding directories. Each app directory generally has models, views, URLs, and templates that make up the separate functionalities of the website. Technically, the website only needs one app to function. However, breaking out the different core functionalities into individual modular apps when designing the website’s backend is good practice. This makes it easier to debug and continuously develop your website as you add more features.
You can create a new app for your project by interfacing with the Django manage.py command line interface using the following command. Once done, you must register your app in the settings.py file under the INSTALLED_APPS array.
#Create a new app in the Django project
python manage.py startapp {APP_NAME}
In this project, we will create two separate apps: the main “blog” and one called “members”. The latter will act as an add-on to the default Django user’s app, controlling authentications and logins.
3. Django Models
Models are a key feature of any Django web project. They will ultimately be what makes your website dynamic, allowing you to continuously add content without having to redeploy every time. Websites do this through constantly interacting with a transactional database to either retrieve records that populate pages when they load, add, or edit records when a visitor interacts with a web page. The models are what define the structures and schemas of these databases.
Each Django project comes with some default models. One such model is user, which keeps track of user details such as username and password that can then be used to enable a logged-in state for your website. In addition to default models, you can also build custom models specific to your website’s functionality. In this project, there will be several custom models, including; “articles”, “categories”, and “comments”.
In a Django project, each app’s models are managed through a file called models.py. This file will contain the different models that make up the app, the fields that make up the database schemas, and their corresponding data types. It is also possible to link two models together based on a shared field. For example, in this blog each article will have an “author”, which will also be a “user”. These linkages are generally done on a one-to-one basis through a “Foreign Key” or on a many-to-many basis using a “ManyToManyField”.
Once you are finished editing the models.py file, it is essential to migrate all these changes to your database before you start up the server again. If you do not, your new model edits will not be applied, and your website will not work as intended. To do this, you must use the manage.py command line interface to run the following two commands.
#Migrate your model changes to the project database
python manage.py makemigrations
python manage.py migrate
4. Django Views
Django views are essentially how your website’s backend server will collect and organise the data, as defined by your models, before pushing it to the frontend client to display. They can range from a generic one size fits all view that renders a template, to something much more intricate that serves personalised content to users based on their logged-in state and the page they are requesting.
In Django, views are managed through the views.py file under each app. They are made up of either python classes, or functions that take the request from the client before returning a response, generally HTTP.
Whilst there will be many views throughout this project, the most commonly used view will be for blog articles. This view will parse the request for the specific article the visitor is trying to access. After which, it will take the article data defined by the model and render it in the template.
5. Django Templates
Instead of having individual HTML files for every page, Django projects consist of HTML templates. These templates generally represent many different pages that all follow the same format, but have different content. Each template will contain all the HTML required to format the page, but core content will have placeholder values to be filled with the data gathered from the view. Therefore, a new HTML file does not need to be created for every new page when developing the website, only new templates representing new page types.
A specific template that will be used throughout this project will be the “article detail” template. This will represent each blog post that is created. However, instead of making a new file for each new post, there will be a {{article_body}} placeholder that the view will fill with the content from the database.
6. Django Forms
Django forms are a specific class used to make HTML forms within your project. These forms are a convenient way to take and validate specific user inputs before completing a backend action. These can range from logging into your website, to liking and commenting on an article.
In Django, forms are managed through a file called forms.py. This file contains the different form classes and the specific input fields that are required for the form to be submitted successfully. They can also include specific details around the widgets and their formatting to be rendered in the HTML templates.
In this project, an essential form we will build is “add article”. This model form will allow you, as an author, to submit new articles to your website. On successful submission, the backend will take the input and interact with your article’s model, creating a new record for the article.
7. Django Urls
In its simplest form, each website comprises a series of URLs that act as a file directory, with each path pointing to a specific HTML file representing a specific page. Django URLs will point to a view to load, instead of a particular HTML file. The Django view will determine the HTML for the client to render based on the HTML template and model. This means the project will consist of URL patterns instead of specifying individual URLs and HTML files for every page. URL patterns are groups of URLs populated by a pattern. The pattern is generally a unique slug, or key pulled from a model field.
Managed as an array that sits in the urls.py file under each app, each pattern will consist of the three fields:
- Path: either a fixed field for pages like the homepage, or dynamic fields like a slug for article pages.
- View: referencing the Django view to render.
- Friendly Name: used in the templates to represent the page path.
An example URL pattern used in this project is “article detail”, representing the page for each article written in the blog. The example below of the URL pattern, will include a dynamic slug, the “article detail” view to point to, and the friendly name “article_detail”.
#Url pattern for the articles themselves.
path('articles/<slug:slug>/', ArticleDetailView.as_view(), name='article_detail')
While there are many other components within the Django ecosystem, these are the ones that will be most critical to the successful deployment of your blog website. Over the coming articles, these components will be fleshed out further as we begin to apply them to this project when building the core website functions.