Python > Web Development with Python > Web Frameworks (Overview) > Introduction to Web Frameworks
Django 'Hello, World!' Example
Django
is a high-level Python web framework that encourages rapid development and clean, pragmatic design. This snippet illustrates creating a basic Django project and app, along with a simple view to display 'Hello, World!'.
Project and App Setup (Conceptual - requires command line execution)
These commands are executed from the command line. First, django-admin startproject myproject
creates a new Django project named 'myproject'. Next, we navigate into the 'myproject' directory. Then, python manage.py startapp myapp
creates a Django application named 'myapp' within the project.
# Create a Django project:
django-admin startproject myproject
cd myproject
# Create a Django app:
python manage.py startapp myapp
View (myapp/views.py)
This code defines a view function named hello_world
in the 'myapp/views.py' file. It takes a request object as input and returns an HttpResponse object containing the string 'Hello, World!'. This is what will be displayed in the browser.
from django.http import HttpResponse
def hello_world(request):
return HttpResponse('Hello, World!')
URL Configuration (myapp/urls.py)
Create a file named urls.py
inside the myapp
directory. This code defines a URL pattern that maps the root URL ('/') to the hello_world
view function. When a user visits the root URL, Django will execute the hello_world
view.
from django.urls import path
from . import views
urlpatterns = [
path('', views.hello_world, name='hello_world'),
]
Project URL Configuration (myproject/urls.py)
This code configures the project-level URL patterns. It includes the URL patterns defined in the 'myapp/urls.py' file. The line path('', include('myapp.urls'))
means that any URL that doesn't match the 'admin/' path will be handled by the URL patterns defined in 'myapp.urls'.
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
Settings Configuration (myproject/settings.py)
In the myproject/settings.py
file, you need to add your app (myapp
) to the INSTALLED_APPS
list. This tells Django that your app is part of the project.
# Add 'myapp' to INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp', # Add your app here
]
Run the Development Server
Execute this command in the project's root directory (where manage.py
is located) to start the Django development server. You can then access the 'Hello, World!' page by visiting http://127.0.0.1:8000/
in your browser.
python manage.py runserver
Concepts Behind the Snippet
Key concepts illustrated by this snippet include: 1. MVC Architecture: Django follows the Model-View-Template (MVT) architectural pattern, which is a variation of MVC. Views handle the logic, models interact with the database, and templates handle the presentation. 2. URL Routing: Mapping URLs to specific views using URL patterns. 3. Request/Response Cycle: Django handles the entire request/response cycle, from receiving the request to generating the response. 4. Django's ORM: Although this example doesn't directly use it, Django's ORM (Object-Relational Mapper) allows you to interact with databases using Python code instead of writing raw SQL.
Real-Life Use Case
This 'Hello, World!' example is the basis for more complex Django applications. It demonstrates how to define views, configure URL patterns, and render content. You can build upon this to create web applications with user authentication, database interactions, and dynamic content.
Best Practices
Interview Tip
Be prepared to explain Django's architecture (MVT), the role of manage.py
, and the difference between a Django project and a Django app. Also, understand how Django handles URL routing and request/response processing.
When to use Django
Django is a good choice for building complex, database-driven web applications. It's particularly well-suited for projects that require user authentication, content management, and a robust set of features out-of-the-box.
Memory Footprint
Django generally has a larger memory footprint than microframeworks like Flask because it includes more built-in features and components.
Alternatives
Alternatives to Django include:
Pros
Cons
FAQ
-
What is the difference between a Django project and a Django app?
A Django project is a collection of settings and apps that make up a complete website. A Django app is a self-contained module that performs a specific function within the project, such as handling user authentication or managing blog posts. A project can contain multiple apps. -
How do I create a database model in Django?
You define database models in your app'smodels.py
file. Each model is a Python class that inherits fromdjango.db.models.Model
. You define the fields of the model as class attributes, using Django's field types (e.g.,CharField
,IntegerField
,DateTimeField
). Then you can use Django's ORM to interact with the database based on the defined models.