Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. In this guide, we will walk through the initial steps of setting up a Django project and creating your first app.
1. Create a Project
First, install Django and start a new project. A "Project" in Django is the container for your settings and database configuration.
pip install django
django-admin startproject myproject
2. Verify the Installation
Enter the project directory and run the development server to ensure everything is working correctly.
cd myproject
python manage.py runserver
3. Create an App
A Django "App" is a web application that does something, like a blog system or a poll app. A project can contain multiple apps.
python manage.py startapp myapp
4. Register the App
Tell the project that your new app exists. Open settings.py and add your app configuration to the INSTALLED_APPS list.
INSTALLED_APPS = [
# ...
'myapp.apps.MyappConfig',
]
5. Create a View
Open myapp/views.py and create a simple view that renders a template.
from django.shortcuts import render
def home(request):
return render(request, 'myapp/index.html')
6. Configure URLs
You need to map a URL to that view. First, create myapp/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
]
Finally, include your app's URLs in the main project's urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
