Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 3 min read

Django Tutorial #3: Understanding URLs and Views in Django | A Beginner's Guide

Django Tutorial #3: Understanding URLs and Views in Django | A Beginner's Guide If you are learning Django, understanding URLs and Views is one of the most important steps in building your first web application. In th

Django Tutorial #3: Understanding URLs and Views in Django | A Beginner's Guide

If you are learning Django, understanding URLs and Views is one of the most important steps in building your first web application.

In the previous tutorials, we explored Django and its basic concepts. Now, let's understand how Django receives a user's request and displays the appropriate response.

In this tutorial, we will learn:

  • What are URLs in Django?
  • What are Views in Django?
  • How URL routing works.
  • How to connect URLs with Views.
  • How to create dynamic URLs.
  • Practical examples with Python code.

1. What Are URLs in Django?

URL stands for Uniform Resource Locator.

In Django, URLs determine which view should handle a particular browser request.

For example:

  • / β†’ Home page
  • /about/ β†’ About page
  • /contact/ β†’ Contact page

Django uses a URL configuration file called urls.py to map URLs to their corresponding views.

2. What Are Views in Django?

A View is a Python function or class that receives an HTTP request and returns an HTTP response.

In simple words:

URLs decide where the request should go, and Views decide what response should be returned.

Django supports two main types of views:

  1. Function-Based Views (FBV)
  2. Class-Based Views (CBV)

For beginners, we will start with Function-Based Views.

3. Understanding Django URL and View Architecture

Here is how a request travels through Django:

       User / Browser
              |
              v
        HTTP Request
              |
              v
         urls.py
       (URL Routing)
              |
              v
          views.py
       (View Function)
              |
              v
        HTTP Response
              |
              v
       User / Browser

4. Creating Your First Django View

First, open your Django application and navigate to views.py.

Write the following code:

from django.http import HttpResponse

def home(request):
    return HttpResponse("Welcome to My Django Website!")

Explanation:

  • HttpResponse is used to return a response to the browser.
  • home() is a function-based view.
  • request contains information about the incoming request.
  • The function returns a message to the user.

5. Connecting URLs with Views

Now open your application's urls.py file.

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
]

Explanation:

  • path() defines a URL pattern.
  • '' represents the application's root URL.
  • views.home connects the URL to the home view.
  • name='home' gives the URL a reusable name.

Now run your development server:

python manage.py runserver

Open your browser and visit:

http://127.0.0.1:8000/

You will see:

Welcome to My Django Website!

Congratulations! You have created your first Django URL and View.

6. Creating Multiple Pages

Let's create Home, About, and Contact pages.

views.py

from django.http import HttpResponse

def home(request):
    return HttpResponse("Welcome to Home Page!")

def about(request):
    return HttpResponse("This is the About Page.")

def contact(request):
    return HttpResponse("Contact Us!")

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('about/', views.about, name='about'),
    path('contact/', views.contact, name='contact'),
]

Now your website has three different pages.

7. Understanding Dynamic URLs

Django also allows us to create dynamic URLs.

For example, suppose we want to display a different profile page for each user.

We can use URL parameters.

views.py

from django.http import HttpResponse

def profile(request, username):
    return HttpResponse(f"Welcome, {username}!")

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('profile/<str:username>/', views.profile, name='profile'),
]

Now visit:

http://127.0.0.1:8000/profile/rahul/

Output:

Welcome, rahul!

Here, <str:username> captures the username from the URL and passes it to the view.

8. Difference Between URLs and Views

URLs Views
Define URL patterns Handle user requests
Located in urls.py Usually located in views.py
Connect URLs to views Generate HTTP responses
Control URL routing Contain application logic

9. Conclusion

URLs and Views are essential components of Django development.

URLs help Django identify which view should handle a request, while views process that request and return the appropriate response.

Understanding these concepts will help you build more organized and interactive Django applications.

This is another step forward in my Django learning journey, and I hope this tutorial helps other beginners understand the basics too!

What's Next?

In Django Tutorial #4, we will explore Django Templates and learn how to create dynamic HTML pages using the Django Template Language (DTL).

If you found this tutorial helpful, feel free to share your thoughts in the comments!

Happy Coding! πŸš€

β€” SP Randhawa

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.