Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 4 of 9 · Django Views & URL Routing
Interview question

What is the difference between render(), redirect(), and HttpResponse in Django views? Django views में render(), redirect(), और HttpResponse में क्या अंतर है?

Answer
Function/classPurposeStatus code
HttpResponse()Raw response with arbitrary content200 by default
render()Renders a template with context, returns HttpResponse200 by default
redirect()Sends the browser to a different URL302 (or 301 for permanent=True)
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse

# HttpResponse - raw response, manual content
def simple_view(request):
    return HttpResponse('Hello, World!')

def json_view(request):
    import json
    data = {'status': 'ok'}
    return HttpResponse(json.dumps(data), content_type='application/json')

# render() - combines a template + context + HttpResponse in one call
def book_list(request):
    books = Book.objects.all()
    return render(request, 'book_list.html', {'books': books})
# Equivalent to:
# from django.template import loader
# template = loader.get_template('book_list.html')
# return HttpResponse(template.render({'books': books}, request))

# redirect() - sends a 302 response with a Location header
def create_book(request):
    if request.method == 'POST':
        book = Book.objects.create(title=request.POST['title'])
        return redirect('book-detail', pk=book.pk)  # redirect to a named URL
        # or: return redirect('/books/5/')  # direct path
        # or: return redirect(book)          # uses book.get_absolute_url()
    return render(request, 'book_form.html')

# Permanent redirect (301) - for URLs that have moved permanently
def old_url_view(request):
    return redirect('new-url-name', permanent=True)

# JsonResponse - specialized HttpResponse for JSON APIs
from django.http import JsonResponse
def api_view(request):
    return JsonResponse({'title': 'Django Basics', 'price': 25.99})
Functionउद्देश्यStatus code
HttpResponse()Raw responseDefault 200
render()Template + context render करता हैDefault 200
redirect()दूसरे URL पर भेजता है302 या 301
from django.http import HttpResponse
from django.shortcuts import render, redirect

def simple_view(request):
    return HttpResponse('Hello, World!')

def book_list(request):
    books = Book.objects.all()
    return render(request, 'book_list.html', {'books': books})

def create_book(request):
    if request.method == 'POST':
        book = Book.objects.create(title=request.POST['title'])
        return redirect('book-detail', pk=book.pk)
    return render(request, 'book_form.html')

def old_url_view(request):
    return redirect('new-url-name', permanent=True)

from django.http import JsonResponse
def api_view(request):
    return JsonResponse({'title': 'Django Basics', 'price': 25.99})

Was this answer clear?