Creating Your First App

A project comprises an app (that performs certain tasks) along with its configuration settings. Here, we will be developing a simple voting app.

Ensure you are inside the project directory having manage.py file and run the command below:

python manage.py startapp votes

Understanding the App Structure

In Django, an app is a self-contained module that performs a specific function within your project. A project can contain multiple apps, and an app can be included in multiple projects. Here’s a typical app structure:

python image
  • apps_name/: Directory containing the app.
    • migrations/: Stores migration files, which track changes to models and database schema.
    • __init__.py: An empty file that tells Python this directory should be considered a package.
    • admin.py: Register models with the Django admin site.
    • apps.py: Configuration for the app.
    • models.py: Define the data models (database schema) for the app.
    • tests.py: Write tests for the app.
    • views.py: Define the views (the logic behind the web pages).
    • urls.py (optional): Define URL patterns for the app.
    • templates/ (optional): Store HTML templates for the app.
    • static/ (optional): Store static files (CSS, JavaScript, images) for the app.

Creating a New Django App

Ensure you are in your Django project directory (where manage.py is located). Run the following command to create a new app, replacing votes with your desired app name:

python manage.py startapp votes

This will create a new directory named votes with the structure described above.

Integrating the App with the Project

Add the app to INSTALLED_APPS: Open the settings.py file in your project’s directory. Then, find the INSTALLED_APPS list and add your new app to it:


INSTALLED_APPS = [
...
'votes',
]

Create URL Patterns for the App: In your app directory (votes), create a new file named urls.py.

Define the URL patterns for your app. For example:


from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'),
]

Include App URLs in Project URLs: Open the urls.py file in your project directory and include the app’s URLs in the project’s URL configuration.


from django.contrib import admin
from django.urls import include, path

urlpatterns = [
path('admin/', admin.site.urls),
path('votes/', include('votes.urls')),
]