Introduction

Django is a powerful Python web framework that simplifies the process of building web applications. In this guide, we'll explore how to create a basic Python web application with Django. We'll provide sample code to demonstrate the process.


Prerequisites

Before you start building a Python web application with Django, ensure you have the following prerequisites:

  • Python and Django installed on your system.
  • Basic knowledge of Python and web development.

Creating a Python Web Application with Django

Let's create a basic Python web application using Django that displays a "Hello, World!" message on a web page.

# 1. Create a new Django project
django-admin startproject myproject
# 2. Change directory to your project
cd myproject
# 3. Create a new Django app
python manage.py startapp myapp
# 4. Define a view in myapp/views.py
from django.http import HttpResponse
def hello_world(request):
return HttpResponse("Hello, World!")
# 5. Configure URL patterns in myproject/urls.py
from django.urls import path
from myapp.views import hello_world
urlpatterns = [
path('hello/', hello_world, name='hello_world'),
]
# 6. Create a template for the hello_world view (myapp/templates/hello.html)
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
# 7. Update myapp/views.py to use the template
from django.shortcuts import render
def hello_world(request):
return render(request, 'hello.html')

Running the Web Application

After setting up the project and creating a view, you can run your Django web application and access it in a web browser.

# 8. Run the Django development server
python manage.py runserver

Open a web browser and visit http://localhost:8000/hello/ to see your "Hello, World!" web page.


Conclusion

Creating a Python web application with Django is a powerful way to build web-based projects. This basic example is just the beginning; Django offers many features and libraries for creating robust and feature-rich web applications.