0
0
Djangoframework~5 mins

Process request and process response in Django

Choose your learning style9 modes available
Introduction

Processing requests and responses lets your Django app talk to users. It handles what users send and what your app sends back.

When a user visits a webpage and you want to show content.
When a user submits a form and you want to save or check data.
When you want to send a file or download to the user.
When you want to redirect users to another page after an action.
When you want to add custom headers or cookies to responses.
Syntax
Django
from django.http import HttpResponse

def view_function(request):
    # process the request data
    # create a response
    return HttpResponse('response content')

The request object holds all info sent by the user.

The view must return a HttpResponse or similar response object.

Examples
Simple view returning a text response.
Django
from django.http import HttpResponse

def hello(request):
    return HttpResponse('Hello, world!')
Redirects user to the home page.
Django
from django.shortcuts import redirect

def go_home(request):
    return redirect('/')
Returns JSON data as a response.
Django
from django.http import JsonResponse

def api_data(request):
    data = {'name': 'Django', 'type': 'framework'}
    return JsonResponse(data)
Sample Program

This view reads a 'name' from the URL query parameters and greets the user. If no name is given, it says 'Guest'.

Django
from django.http import HttpResponse

def greet_user(request):
    name = request.GET.get('name', 'Guest')
    message = f'Hello, {name}!'
    return HttpResponse(message)
OutputSuccess
Important Notes

Request data can come from URL, form data, or headers.

Always return a response object; Django expects it.

You can customize responses with status codes, headers, and cookies.

Summary

Views receive a request and return a response.

Request holds user data; response sends content back.

Use different response types for text, JSON, redirects, or files.