Building Your First Django App
Introduction
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.
Prerequisites
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
pip install django
to install it. - 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.
App Structure
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.
Sample Code
Let's create a simple example of a Django app. In this case, we'll create a basic "Hello, Django!" app.
models.py
Define a model for your app in the models.py
file:
from django.db import models
class Greeting(models.Model):
message = models.CharField(max_length=100)
views.py
Implement a view in the views.py
file:
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello, Django!")
urls.py
Define a URL pattern for your view in the urls.py
file:
from django.urls import path
from . import views
urlpatterns = [
path('hello/', views.hello, name='hello'),
]
templates
Create an HTML template in the templates/
directory:
<h1>Hello from Django!</h1>
Conclusion
Congratulations! You've created your first Django app. You can now add more functionality, views, and templates to build a fully-featured web application.