You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django测试报错:Board matching query does not exist求助

Django Test Error: Board matching query does not exist

Hey there, let’s work through this test error you’re hitting. The root problem here is that your test is trying to access a Board object that doesn’t exist in Django’s test database—remember, Django spins up a fresh, empty database for every test run, so any boards you created in your dev database won’t be available here.

First, let’s recap the error you shared:

System check identified 1 issue (0 silenced). ...E............

ERROR: test_board_topics_view_not_found_status_code (boards.tests.BoardTopicsTests)

Traceback (most recent call last):
File "/home/sysadmin/Documents/belajar_python/Django/mysite/boards/tests.py", line 41, in test_board_topics_view_not_found_status_code
response = self.client.get(url)
.... .... ....
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 380, in get
self.model._meta.object_name DoesNotExist: Board matching query does not exist.

What’s causing this

Your test test_board_topics_view_not_found_status_code is either:

  • Trying to fetch a Board with an ID that hasn’t been created in the test database, or
  • Your view is using Board.objects.get(...) instead of a method that handles missing objects gracefully, so when the test hits a non-existent board ID, it throws an error instead of returning a 404.

How to fix it

Here are two key fixes to resolve this:

1. Create test objects in setUp()

Add a setUp() method to your BoardTopicsTests class to create a test Board before every test runs. This ensures your tests have the data they need:

from django.test import TestCase
from .models import Board

class BoardTopicsTests(TestCase):
    def setUp(self):
        # Create a test Board that will be available for all tests in this class
        self.board = Board.objects.create(name='Test Board', description='A test board for our tests')
    
    # Your existing test methods go here...

2. Use get_object_or_404 in your view

If this test is meant to verify that accessing a non-existent board returns a 404 status code, your view needs to handle missing objects properly. Replace Board.objects.get(...) with get_object_or_404—this will automatically return a 404 response instead of throwing a DoesNotExist error:

from django.shortcuts import render, get_object_or_404
from .models import Board

def board_topics(request, pk):
    board = get_object_or_404(Board, pk=pk)
    return render(request, 'board_topics.html', {'board': board})

Since you’re following the Simple is Better Than Complex tutorial, double-check the test setup section—they almost certainly cover creating test data in setUp() to avoid exactly this kind of error.

内容的提问来源于stack exchange,提问作者aji stack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:11:10