In this tutorial, we will learn how to get started with Django, a high-level Python web framework. Our goal is to set up a Django project and create a simple web application.
By the end of this tutorial, you should be able to:
Prerequisites:
pip install Django
django-admin startproject myproject
This will create a new Django project named "myproject."
cd myproject
python manage.py runserver
You should see a message saying that the server is running and you can view the website at http://localhost:8000.
python manage.py startapp myapp
myapp/views.py
, add this:from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
This simple view returns "Hello, Django!" when it gets a web request.
Let's look at some code examples:
myapp/urls.py
, add this:from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
This code maps the URL of the homepage ('') to the home
view.
myproject/urls.py
, add this:from django.urls import include, path
urlpatterns = [
path('', include('myapp.urls')),
]
This code includes the URLs of 'myapp' in the project.
In this tutorial, we've learned how to install Django, start a new project, start the server, create an app, and create a view. The next step is to learn about Django's database models.
Resources:
Solution: Follow the steps in the 'Starting a new project' and 'Starting the server' sections.
Exercise 2: In the 'exercise1' project, create a new app named 'myexerciseapp' and create a view that returns "Hello, Exercise!".
Solution: Follow the steps in the 'Creating a new app' and 'Creating a view' sections, but return "Hello, Exercise!" instead of "Hello, Django!".
Exercise 3: Map the view from Exercise 2 to the URL of the homepage.
Tips for further practice: