我试图在ListView上测试我的自定义get_context_data()方法,我一直遇到这个错误:AttributeError: 'Home' object has no attribute 'object_list'
视野很好。测试视图是否响应200个状态代码工作正常。我似乎无法测试我的自定义get_context_data方法。
测试
import pytest
from mixer.backend.django import mixer
from django.test import RequestFactory
from django.urls import reverse
from tracker.views import *
from tracker.models import Peak
pytestmark = pytest.mark.django_db
@pytest.fixture
def factory():
return RequestFactory()
def test_number_of_peaks_completed(factory):
mixer.cycle(7).blend(Peak, complete=True)
mixer.cycle(10).blend(Peak)
path = reverse('home')
request = factory.get(path)
view = Home()
view.setup(request)
context = view.get_context_data()
assert context['number_of_peaks_completed'] == 7
查看
from django.views.generic import ListView
from tracker.models import *
class Home(ListView):
model = Peak
template_name = 'tracker/home.html'
context_object_name = 'peaks'
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(**kwargs)
context['number_of_peaks_completed'] = Peak.objects.filter(complete=True).count()
return context
错误跟踪
FAILED [ 16%]
tracker/tests/test_views.py:24 (test_number_of_peaks_completed)
factory = <django.test.client.RequestFactory object at 0x7efbfb8093a0>
def test_number_of_peaks_completed(factory):
mixer.cycle(7).blend(Peak, completed=True)
mixer.cycle(10).blend(Peak, completed=False)
path = reverse('home')
request = factory.get(path)
view = Home()
view.setup(request)
> context = view.get_context_data()
tracker/tests/test_views.py:33:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
tracker/views.py:19: in get_context_data
context = super().get_context_data(**kwargs)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <tracker.views.Home object at 0x7efbfb630d00>, object_list = None
kwargs = {}
def get_context_data(self, *, object_list=None, **kwargs):
"""Get the context for this view."""
> queryset = object_list if object_list is not None else self.object_list
E AttributeError: 'Home' object has no attribute 'object_list'
venv/lib/python3.8/site-packages/django/views/generic/list.py:115: AttributeError
2条答案
按热度按时间pkmbmrz71#
问题是你没有使用标准的
as_view()
函数。如果你想手动设置,你需要自己设置
self.object_list
(这发生在主view
函数中,例如get
)。试试这个:
您也可以将这一行移动到您自己的
get_context_data
。参考:https://github.com/django/django/blob/master/django/views/generic/list.py#L142
3phpmpom2#
对于遇到
AttributeError: 'YourView' object has no attribute 'kwargs'
的人