【问题标题】:AssertionError: No templates used to render the responseAssertionError:没有用于呈现响应的模板
【发布时间】:2022-07-18 00:11:12
【问题描述】:

我在写这个问题时解决了这个问题,但我想发布它,所以也许有人需要这个答案


朋友们好。 我是 Django 测试的新手。 在我测试我的观点时,我在某些观点中遇到了这个错误。

这是我的意见.py:

def all_programs(request):
    programs = Program.objects.all()
    return render(request, 'orders/all_programs.html', {'programs': programs})


def checkout(request, slug):
    if request.method == 'POST':
        # get data from form and save it

    program = get_object_or_404(Program, slug=slug)
    dates = ProgramDate.objects.filter(program=program)
    return render(request, 'orders/checkout.html', {'program': program, 'dates': dates})

这是 urls.py:

from django.urls import path
from django.views.generic import RedirectView
from .views import *

app_name = 'orders'

urlpatterns = [
    path('', RedirectView.as_view(url='https://www.another-website.net')),
    path('tests/', all_programs, name='all_programs'),
    path('checkout/<str:slug>/', checkout, name='checkout'),
    path('checkout/return_page/', ReturnPage.as_view(), name='return_page'),
]

这是 test_views.py:

from django.test import TestCase
from django.shortcuts import reverse


class TestViews(TestCase):
    
    def test_all_programs(self):
        response = self.client.get(reverse('orders:all_programs'))
        self.assertTemplateUsed(response, 'orders/all_programs.html')

    def test_checkout(self):    # error id here
        response = self.client.get(reverse('orders:all_programs', kwargs={'slug': 'test'}))     # I tried this  
        # response = self.client.get('http://127.0.0.1:8000/checkout/test/')    #and this
        self.assertTemplateUsed(response, 'orders/checkout.html')

【问题讨论】:

    标签: django django-views django-templates django-testing django-tests


    【解决方案1】:

    这种情况下的解决方案是:

    Django 中的测试不使用默认数据库,而是创建自己的没有任何记录的数据库(我完全忘记了),因此在开始相关的测试之前必须创建记录到数据库。 在这种情况下,我必须在测试前创建新程序:

    class TestViews(TestCase):
    
        _program = {
            'name': 'test_program',
            'price': 1000,
            'abbreviation': 'test',
            'description': 'test_program',
            'slug': 'test_program',
            'id_from_zoho': 1000,
        }
    
    
        def test_checkout(self):
            program = Program(**self._program)
            program.save()
            response = self.client.get(reverse('orders:checkout', kwargs={'slug': program.slug}))
            self.assertTemplateUsed(response, 'orders/checkout.html')
    
    

    【讨论】:

      猜你喜欢
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 2012-03-24
      相关资源
      最近更新 更多