Writing Your First Django App
Introduction
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. In this tutorial, you will learn how to create a simple Django app from scratch.
Setting Up Your Environment
Before we start building our Django app, we need to set up our development environment. Follow these steps to install Django:
1. Create a virtual environment:
2. Activate the virtual environment:
3. Install Django:
Creating a Django Project
Next, we will create a new Django project. A project is a collection of configurations and apps for a web application. Run the following command to create a new project:
This will create a directory named myproject
with the necessary files and directories.
Creating a Django App
Now that we have a Django project, we can create our first app. An app is a web application that does something, such as a blog, a forum, or a poll system. Navigate to the project directory and run the following command:
This will create a directory named myapp
with the necessary files and directories.
Configuring the App
To include our app in the project, we need to add it to the INSTALLED_APPS
list in the settings.py
file:
INSTALLED_APPS = [ ... 'myapp', ]
Creating a View
A view function is a Python function that takes a web request and returns a web response. Create a view in myapp/views.py
:
from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the myapp index.")
Mapping URLs
To call the view, we need to map it to a URL. Create a urls.py
file in the myapp
directory:
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ]
Then include this URLconf in the project’s urls.py
file:
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('myapp/', include('myapp.urls')), path('admin/', admin.site.urls), ]
Running the Server
Now, we can run the development server to see our app in action. Run the following command:
Open a web browser and go to http://127.0.0.1:8000/myapp/
. You should see the message "Hello, world. You're at the myapp index."
Conclusion
Congratulations! You have created your first Django app. This tutorial covered the basics of setting up a Django project, creating an app, and configuring URLs and views. From here, you can explore more advanced features of Django to build powerful web applications.