Your First Django App: Creating Views and URLs

3D isometric diagram of Django architecture showing the connection between URLs and Views in a web application.

In our previous guide, you set up an empty Django project. Now it’s time to delve into Django Views and URLs to make it do something.

In Django, a “Project” is the whole website. An “App” is a specific piece of functionality (like a blog, a forum, or a user profile system). A project can have many apps, each potentially with its own configuration for Views and URLs in Django applications.

Step 1: Create an App

Make sure your virtual environment is active. We’ll create an app called pages to handle simple static pages (like a homepage) and map these to specific Django URLs.

python manage.py startapp pages

You’ll see a new pages/ folder appear next to config/, containing files crucial for Django Views and URLs setup.

Step 2: Install the App

You must tell Django that this new app exists. Open config/settings.py and find the INSTALLED_APPS list. Add 'pages', to the bottom, integrating it into the Django URLs processing.

# config/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    # ... other default apps ...
    'pages',  # <-- Add your new app here!
]

Step 3: Write a View

A View is just a Python function that takes a web request and returns a web response. Open pages/views.py to begin creating a Django view function that enhances the connection between Views and URLs.

# pages/views.py
from django.http import HttpResponse

def home_page_view(request):
    return HttpResponse("Hello, World! This is my first Django page.")

Step 4: Connect the URL

Now we need to tell Django: “When someone visits the homepage, use the home_page_view function.”

We do this in two steps using Django URLs.

A. Create pages/urls.py This file doesn’t exist yet. Create it and add this code:

# pages/urls.py
from django.urls import path
from .views import home_page_view

urlpatterns = [
    path('', home_page_view, name='home'),
]

This means: “If the URL path is empty (''), call home_page_view.”

B. Update the main config/urls.py Now, point the main project URLs to your app URLs by establishing Django Views and URLs connectivity throughout your project.

# config/urls.py
from django.contrib import admin
from django.urls import path, include  # Import 'include'

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('pages.urls')),  # Add this line!
]

Step 5: Test It!

Run the server again:

python manage.py runserver

Visit http://127.0.0.1:8000/. Instead of the rocket ship, you should now see: “Hello, World! This is my first Django page.” This demonstrates the successful setup of using URLs and Views within Django.

Similar Posts

Leave a Reply