Django

Django Views

Create views

Django Views

A view function, or view for short, is a Python function that takes a web request and returns a web response. This response can be the HTML contents of a web page, a redirect, or an error.

Function-Based Views

The simplest way to create a view is to write a function. Create a view in views.py:

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

Class-Based Views

Django also provides class-based views which are more powerful and reusable:

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

class MyView(View):
    def get(self, request):
        return HttpResponse("Hello, world!")

Template Views

To render HTML templates, use the render function:

from django.shortcuts import render

def index(request):
    return render(request, 'myapp/index.html', {'name': 'Django'})

Passing Data to Templates

You can pass data to templates using a context dictionary:

def detail(request, question_id):
    context = {
        'question_id': question_id,
        'message': 'This is a detail view'
    }
    return render(request, 'myapp/detail.html', context)

Request Methods

Views can handle different HTTP methods:

def my_view(request):
    if request.method == 'POST':
        # Handle POST request
        return HttpResponse("POST request")
    else:
        # Handle GET request
        return HttpResponse("GET request")