Lesson 14 of 60 – Django Views
23%

Django Views

A View in Django is a Python function or class that receives a web request and returns a web response. Views contain the main logic that decides what should happen when a user visits a particular URL.

Note: In Django, URLs usually connect a browser request to a view, and the view returns a response such as HTML, JSON, or a redirect.

1. What is a View?

A view is a Python function or class that handles a request and returns a response.

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

Here, home() is a Django view.

2. Purpose of Views

Views are used to define what should happen when a user accesses a URL.

  • Receive the request
  • Process application logic
  • Access database data
  • Render templates
  • Return a response

3. Where are Views Written?

Views are commonly written inside a file named views.py in a Django app.

myapp/
    views.py
    models.py
    urls.py

4. Import HttpResponse

To return a simple text response, import HttpResponse from Django.

from django.http import HttpResponse

This allows a view to send text back to the browser.

5. Creating a Simple View

from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello Django")

The home() function receives the request and returns a response.

6. The request Parameter

A Django view normally receives a request object as its first parameter.

def home(request):
    return HttpResponse("Welcome")

The request object contains information about the current browser request.

7. Connecting a View with a URL

A view becomes accessible through a URL when it is connected in urls.py.

from django.urls import path
from . import views

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

8. URL and View Relationship

The basic flow is:

Browser
   ↓
URL
   ↓
URL Pattern
   ↓
View
   ↓
Response
   ↓
Browser

This is one of the most important concepts in Django.

9. About View

def about(request):
    return HttpResponse("About Us")

This view can be connected to an /about/ URL.

10. Contact View

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

A view can contain different logic depending on the requirement of the page.

11. Multiple Views

A Django application can contain many views.

def home(request):
    return HttpResponse("Home")

def about(request):
    return HttpResponse("About")

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

12. Multiple URLs for Multiple Views

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

Each URL can point to a different view.

13. Returning HTML from a View

A view can return HTML using HttpResponse.

def home(request):
    return HttpResponse("<h1>Welcome</h1>")

For larger HTML pages, Django templates are normally used.

14. Rendering Templates

Django provides the render() function for returning an HTML template.

from django.shortcuts import render

def home(request):
    return render(request, 'home.html')

15. Why Use Templates?

Templates keep HTML separate from Python view logic.

  • Better organization
  • Reusable HTML
  • Easy page design
  • Dynamic data support

16. Passing Data to a Template

def home(request):
    data = {
        'name': 'Rahul'
    }

    return render(request, 'home.html', data)

The dictionary contains data that can be used inside the template.

17. Template Variable

A value passed from a view can be displayed using a template variable.

<h1>Hello {{ name }}</h1>

If the view passes name, Django can display its value.

18. Views Can Access Models

Views can communicate with Django models to work with database information.

from .models import Student

def students(request):
    data = Student.objects.all()
    return render(request, 'students.html', {
        'students': data
    })

19. Views and Database Operations

A view can perform operations such as:

  • Reading records
  • Creating records
  • Updating records
  • Deleting records
  • Filtering records

Django ORM is commonly used for these operations.

20. Returning JSON from a View

Views can also return JSON responses, which are commonly used for APIs.

from django.http import JsonResponse

def data(request):
    return JsonResponse({
        'name': 'Rahul',
        'age': 20
    })

21. Redirecting from a View

A view can redirect a user to another page using Django's redirect() function.

from django.shortcuts import redirect

def home(request):
    return redirect('about')

22. Class-Based Views

Django supports both function-based views and class-based views.

from django.views import View
from django.http import HttpResponse

class HomeView(View):
    def get(self, request):
        return HttpResponse("Home Page")

23. Function-Based View

A function-based view is a normal Python function that receives a request.

def home(request):
    return HttpResponse("Home Page")

Function-based views are easy to understand and are useful for beginners.

24. Handling Different HTTP Methods

Views can handle different types of HTTP requests, such as GET and POST.

def student(request):
    if request.method == 'POST':
        return HttpResponse("Data submitted")

    return HttpResponse("Student Form")

25. Getting Data from a URL

A URL parameter can be passed to a view.

def student(request, id):
    return HttpResponse(f"Student ID: {id}")

The URL pattern can provide the id value to the view.

26. View with URL Parameter

path('student/<int:id>/', views.student)

For example, visiting /student/10/ can send 10 to the view.

27. Common View Workflow

A common Django page follows this workflow:

1. User visits URL
2. Django checks URL pattern
3. URL calls view
4. View processes request
5. View may access database
6. View renders template
7. Response goes to browser

28. Common View Mistakes

  • Forgetting the request parameter
  • Forgetting to import HttpResponse
  • Incorrect view name in urls.py
  • Incorrect template path
  • Forgetting to return a response
  • Using the wrong URL pattern

29. Simple Complete Example

views.py

from django.http import HttpResponse

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

def about(request):
    return HttpResponse("About Us")

urls.py

from django.urls import path
from . import views

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

30. Summary of Django Views

Views are one of the most important parts of a Django application. They connect URLs with application logic and generate responses for users.

  • Views are written in Python.
  • Views commonly receive a request object.
  • Views can return HttpResponse.
  • Views can render templates.
  • Views can access models and databases.
  • Views can return JSON responses.
  • Views can redirect users.
  • Django supports function-based and class-based views.

📌 Key Points

  • A view handles a web request.
  • Views are commonly created inside views.py.
  • HttpResponse can return a simple response.
  • render() is used to display templates.
  • Views can communicate with models and databases.
  • URLs connect users' requests to views.
  • Views can handle GET and POST requests.
  • Django supports both function-based and class-based views.

🧠 Quick Quiz

Question: What is the main purpose of a Django view?