Building Your First Django App
Creating a Django app is a fundamental step in building web applications with Django. In this guide, we'll walk you through the process of creating your first Django app, complete with sample code.
Before you start building your first Django app, make sure you have the following prerequisites in place:
- Django: You should have Django installed. If not, use
to install it.
pip install django
- Django Project: You should have a Django project already set up. If not, refer to the guide on creating your first Django project.
- Code Editor: Choose a code editor such as Visual Studio Code, PyCharm, or Sublime Text.
Creating a Django App
Django apps are reusable components that encapsulate specific functionality. To create your first app, open your command prompt or terminal and navigate to your Django project directory. Then, run the following command:
python manage.py startapp appname
Replace "appname" with the name of your app.
Once you've created your app, you'll find a directory structure within the app directory. Here's what the key components of an app directory contain:
- migrations/: Automatically generated database migration scripts.
- models.py: Define your app's database models here.
- views.py: Implement the logic of your app's views here.
- urls.py: Define URL routing for your app's views here.
- templates/: Create HTML templates for rendering your app's views.
Let's create a simple example of a Django app. In this case, we'll create a basic "Hello, Django!" app.
Define a model for your app in the
from django.db import models
message = models.CharField(max_length=100)
Implement a view in the
from django.http import HttpResponse
return HttpResponse("Hello, Django!")
Define a URL pattern for your view in the
from django.urls import path
from . import views
urlpatterns = [
path('hello/', views.hello, name='hello'),
Create an HTML template in the
<h1>Hello from Django!</h1>
Congratulations! You've created your first Django app. You can now add more functionality, views, and templates to build a fully-featured web application.