Testing Views with Test Client

A snippet showing how to test views with DjangoÆs test client.


# models.py

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=120)
    body = models.TextField(blank=True)
      

# admin.py

from django.contrib import admin
from .models import Article

@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    list_display = ("title",)
      

# Result (tests/test_views.py)
from django.test import TestCase
from django.urls import reverse
from .models import Article

class ArticleViewsTest(TestCase):
    def test_list_page(self):
        Article.objects.create(title="Hello")
        url = reverse("article-list")
        res = self.client.get(url)
        self.assertEqual(res.status_code, 200)
        self.assertContains(res, "Hello")
    def test_create_post(self):
        url = reverse("article-create")
        res = self.client.post(url, {"title": "New"})
        self.assertEqual(res.status_code, 302)  # redirect after create
      
Explanation:
  • The test client simulates requests without running a server.
  • Use reverse() to resolve URLs; assert status codes and response content.
  • For POSTs, assert redirects and database changes.
  • Category Testing
  • Total Views 697
  • Last Modified 05 March, 2026
  • Tags #testing #views #client #response
Previous snippet
Basic Django Unit Test
Next snippet
Model Test Example
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.