Skip to main content
Course/Module 5/Topic 2 of 5Intermediate

Form Handling in Views

Explore how to process and validate forms in Django views to create interactive web applications.

65 minBy Priygop TeamLast updated: Feb 2026

Processing Forms in Views

Django views handle form processing, validation, and data saving. Understanding form handling is crucial for building interactive web applications.

Form Processing Examples

Example
# views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import ContactForm, PostForm, CommentForm
from .models import Post, Comment

# Contact form view
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process the form data
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            
            # Send email or save to database
            # send_contact_email(name, email, subject, message)
            
            messages.success(request, 'Thank you for your message!')
            return redirect('contact')
    else:
        form = ContactForm()
    
    return render(request, 'blog/contact.html', {'form': form})

# Post creation view
@login_required
def post_create(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            messages.success(request, 'Post created successfully!')
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()
    
    return render(request, 'blog/post_form.html', {'form': form, 'title': 'Create Post'})

# Post update view
@login_required
def post_update(request, pk):
    post = get_object_or_404(Post, pk=pk)
    
    # Check if user is the author
    if post.author != request.user:
        messages.error(request, 'You can only edit your own posts.')
        return redirect('post_detail', pk=pk)
    
    if request.method == 'POST':
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            form.save()
            messages.success(request, 'Post updated successfully!')
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm(instance=post)
    
    return render(request, 'blog/post_form.html', {
        'form': form, 
        'title': 'Edit Post',
        'post': post
    })

# Comment form view
@login_required
def add_comment(request, post_pk):
    post = get_object_or_404(Post, pk=post_pk)
    
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.author = request.user
            comment.save()
            messages.success(request, 'Comment added successfully!')
            return redirect('post_detail', pk=post_pk)
    else:
        form = CommentForm()
    
    return render(request, 'blog/post_detail.html', {
        'post': post,
        'comment_form': form
    })

# File upload view
@login_required
def file_upload(request):
    if request.method == 'POST':
        form = FileUploadForm(request.POST, request.FILES)
        if form.is_valid():
            # Handle file upload
            uploaded_file = form.cleaned_data['file']
            # Save file and create database record
            messages.success(request, 'File uploaded successfully!')
            return redirect('file_list')
    else:
        form = FileUploadForm()
    
    return render(request, 'blog/file_upload.html', {'form': form})

# AJAX form handling
from django.http import JsonResponse

def ajax_contact(request):
    if request.method == 'POST' and request.is_ajax():
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process form data
            return JsonResponse({'success': True, 'message': 'Message sent successfully!'})
        else:
            return JsonResponse({'success': False, 'errors': form.errors})
    
    return JsonResponse({'success': False, 'message': 'Invalid request'})

Additional Resources

Recommended Reading

  • Django Forms Documentation
  • Django Authentication Documentation
  • Django security Best Practices

Online Resources

  • Django Form Validation
  • User Authentication Tutorial
  • security Best Practices Guide
Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep