Function-Based Views

Loading concept...

Django Function-Based Views: Your Restaurant Kitchen Adventure! 🍳

Imagine you own a restaurant. Customers come in, tell the waiter what they want, and get their food. Django views work exactly like this! Let’s explore how to build the kitchen that serves web requests.


The Big Picture: What Are Views?

Think of Django like a restaurant:

  • Customer = Web Browser (makes requests)
  • Waiter = URLs (takes orders to the right place)
  • Kitchen = Views (prepares the response)
  • Food = HTML page, JSON data, or any response

A Function-Based View (FBV) is simply a Python function that takes a request and returns a response. Simple!

graph TD A[🌐 Browser Request] --> B[📋 URL Router] B --> C[👨‍🍳 View Function] C --> D[📦 Response] D --> A

1. FBV Fundamentals: Your First Kitchen

The Simplest View Ever

Every view is just a function with one rule: take a request, return a response.

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello!")

That’s it! Like a chef who just says “Hello!” when someone walks in.

Breaking It Down

Part What It Does
request Info about what the customer wants
HttpResponse The plate you serve back
"Hello!" The actual food/content

Connecting View to URL

# urls.py
from . import views

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

When someone visits /hello/, Django calls your hello function!


2. HttpRequest Object: Reading the Customer’s Order 📝

The request object is like a detailed order slip. It tells you EVERYTHING about what the customer wants.

What’s Inside the Request?

def show_order(request):
    # Who's ordering?
    method = request.method      # "GET" or "POST"
    path = request.path          # "/menu/pizza/"

    # What browser?
    browser = request.META.get(
        'HTTP_USER_AGENT',
        'Unknown'
    )

    # Any data sent?
    query = request.GET          # URL parameters
    form_data = request.POST     # Form submissions

    return HttpResponse(f"Got it!")

Common Request Properties

Property What It Tells You Example
request.method GET, POST, etc. "POST"
request.path URL path "/users/5/"
request.GET URL params {"page": "2"}
request.POST Form data {"name": "Jo"}
request.user Who’s logged in User object
request.COOKIES Browser cookies {"session": "abc"}

Real Example: Search Page

def search(request):
    # Get search term from URL
    # Example: /search/?q=pizza
    query = request.GET.get('q', '')

    if query:
        msg = f"Searching: {query}"
    else:
        msg = "Enter something!"

    return HttpResponse(msg)

3. Response Classes: Different Types of Plates 🍽️

Django gives you different “plates” for different types of food!

HttpResponse: The Basic Plate

from django.http import HttpResponse

def basic(request):
    return HttpResponse(
        "Plain text here",
        content_type="text/plain"
    )

JsonResponse: The JSON Plate

Perfect for APIs! Automatically converts Python to JSON.

from django.http import JsonResponse

def api_data(request):
    data = {
        "name": "Pizza",
        "price": 12.99,
        "toppings": ["cheese", "pepperoni"]
    }
    return JsonResponse(data)

Error Responses: When Things Go Wrong

from django.http import (
    HttpResponseNotFound,      # 404
    HttpResponseForbidden,     # 403
    HttpResponseBadRequest,    # 400
    HttpResponseServerError    # 500
)

def get_item(request, item_id):
    item = find_item(item_id)

    if not item:
        return HttpResponseNotFound(
            "Item not found!"
        )

    return HttpResponse(item.name)

Response Types Cheat List

Response Class Status Code When to Use
HttpResponse 200 Everything OK
JsonResponse 200 API data
HttpResponseRedirect 302 Send elsewhere
HttpResponseNotFound 404 Page missing
HttpResponseForbidden 403 Not allowed
HttpResponseBadRequest 400 Bad input

4. View Shortcuts: Kitchen Power Tools! ⚡

Django gives you shortcuts so you don’t repeat yourself. Less code, same result!

render(): The All-in-One Tool

Instead of building HTML manually, use templates!

from django.shortcuts import render

def home(request):
    context = {
        "title": "Welcome!",
        "items": ["Apple", "Banana"]
    }
    return render(
        request,
        "home.html",
        context
    )

What render() does:

  1. Loads the template file
  2. Fills in your data (context)
  3. Returns HttpResponse with HTML

redirect(): Send Them Somewhere Else

from django.shortcuts import redirect

def old_page(request):
    # Moved! Go here instead
    return redirect('new_page')

def after_login(request):
    # Go to specific URL
    return redirect('/dashboard/')

get_object_or_404(): Find It or Show Error

from django.shortcuts import (
    get_object_or_404
)
from .models import Product

def product(request, product_id):
    # Gets product OR shows 404
    item = get_object_or_404(
        Product,
        id=product_id
    )
    return render(
        request,
        'product.html',
        {'item': item}
    )

get_list_or_404(): Same but for Lists

from django.shortcuts import (
    get_list_or_404
)

def category(request, cat_name):
    items = get_list_or_404(
        Product,
        category=cat_name
    )
    return render(
        request,
        'list.html',
        {'items': items}
    )

Shortcuts Summary

Shortcut What It Does
render() Template + Context → Response
redirect() Send user to another URL
get_object_or_404() Get one item or 404
get_list_or_404() Get list or 404 if empty

5. Request Methods: Different Ways to Order 📬

Customers can order in different ways. Each HTTP method has a purpose!

The Main Methods

Method Purpose Example
GET Get/view data View a page
POST Send/create data Submit a form
PUT Update data Edit profile
DELETE Remove data Delete account

Handling Different Methods

def contact(request):
    if request.method == 'POST':
        # Handle form submission
        name = request.POST.get('name')
        msg = request.POST.get('msg')
        # Save to database...
        return redirect('thanks')

    # GET - show the form
    return render(
        request,
        'contact.html'
    )

Using require_http_methods Decorator

from django.views.decorators.http import (
    require_http_methods,
    require_GET,
    require_POST
)

@require_GET
def view_only(request):
    # Only GET allowed here
    return render(request, 'view.html')

@require_POST
def submit_only(request):
    # Only POST allowed here
    return HttpResponse("Submitted!")

@require_http_methods(["GET", "POST"])
def form_page(request):
    # GET or POST only
    if request.method == 'POST':
        return HttpResponse("Got it!")
    return render(request, 'form.html')

Complete Example: A Simple Form

from django.shortcuts import render
from django.shortcuts import redirect
from django.views.decorators.http import (
    require_http_methods
)

@require_http_methods(["GET", "POST"])
def signup(request):
    if request.method == 'POST':
        username = request.POST.get(
            'username'
        )
        email = request.POST.get('email')

        # Validate
        if not username or not email:
            return render(
                request,
                'signup.html',
                {'error': 'Fill all!'}
            )

        # Create user...
        return redirect('welcome')

    # GET - show signup form
    return render(request, 'signup.html')

Putting It All Together 🎯

Here’s a complete view showing everything:

from django.shortcuts import (
    render,
    redirect,
    get_object_or_404
)
from django.http import JsonResponse
from django.views.decorators.http import (
    require_http_methods
)
from .models import Task

@require_http_methods(["GET", "POST"])
def task_view(request, task_id=None):
    # POST: Create new task
    if request.method == 'POST':
        title = request.POST.get('title')
        Task.objects.create(title=title)
        return redirect('task_list')

    # GET with ID: Show one task
    if task_id:
        task = get_object_or_404(
            Task,
            id=task_id
        )
        return render(
            request,
            'task.html',
            {'task': task}
        )

    # GET without ID: Show all
    tasks = Task.objects.all()
    return render(
        request,
        'tasks.html',
        {'tasks': tasks}
    )

def api_tasks(request):
    # API endpoint returning JSON
    tasks = list(
        Task.objects.values(
            'id', 'title', 'done'
        )
    )
    return JsonResponse(
        {'tasks': tasks}
    )

Quick Reference Flow

graph TD A[Request Arrives] --> B{Check Method} B -->|GET| C[Show Data/Form] B -->|POST| D[Process Form] C --> E[render template] D --> F{Valid?} F -->|Yes| G[Save & redirect] F -->|No| H[Show errors] E --> I[HttpResponse] G --> I H --> I

You Did It! 🎉

Now you know:

  • FBV Fundamentals - Functions that handle requests
  • HttpRequest - Reading what users want
  • Response Classes - Different ways to respond
  • Shortcuts - render, redirect, get_object_or_404
  • Request Methods - GET, POST, and how to handle them

Remember: A view is just a function. Request in, response out. That’s the whole secret!

Happy coding! 🚀

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.