How to start an app in Django
Subscribe to my newsletter and never miss my upcoming articles
Welcome to my .py series where I take you through what I learn weekly at She Code Africa Mentorship program Cohort 2-Python track. You can check below for other episodes.
In this episode, I will be taking you through creating your first Django app.
You have started your Django project and now you are set to build a wonderful website. If you do not know how to start a project, you can check here .
In Django, a project consists of different apps (relatable term: pages) where every path is referred to as an app. Here's a difference between a project and an app in Django.
An app is a web application that does something like an about or blog. A project is a collection of configuration and apps from a particular website. A project contains multiple apps and an app can be in multiple projects.
In this article, I will be taking you through:
How to create an app in Django
The function of each built-in file in the app
Let's get started!
To create an app, run through the following steps:
- Activate your virtual environment with this command
Note: myenv is the name of the virtual environment and you might need to specify the path it was created
- cd into your django project directory
- To create app, run this command
python manage.py startapp blogs
Note: blogs is the name of the app
It automatically creates a directory with the name of the app with the following built-in files.
So let's pause on the steps and run through the function of each file in your new app.
init.py: This file tells Python to treat this app directory as a Python package.
admin.py: This file contains the settings for your admin area.
apps.py: This file contains settings for configuring your app.
models.py: In this file, you create your models( series of classes) that are converted into database tables.
tests.py: This file will contain all your test classes.
views.py: This file contains functions and classes that handle what data is displayed on the HTML templates.
So now you have a glimpse of what each file does. Back to our procedures on creating an app.
- After creating the app, you will need to specify your app name in your settings.py file under the INSTALLED_APPS section like this:
- Next up, you add the URL path for your app in the urls.py file on mysite (project name) directory. The essence of doing this is so that navigating your app with that path will be possible.
Look at this code and tweak yours to look like this:
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('blogs/', include('blogs.urls')), path('admin/', admin.site.urls), ]
Congratulations, you have created your first Django app. Following these steps, you are set to write your first model. Feel free to check in next week, I will be writing about that.
Thanks for reading!