【问题标题】:NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'home' not found. 'home' is not a valid view function or pattern nameNoReverseMatch(msg) django.urls.exceptions.NoReverseMatch:找不到“家”的反向。 'home' 不是有效的视图函数或模式名称
【发布时间】:2020-09-30 09:12:14
【问题描述】:

我是使用 Django 的新手,我正在尝试为我的页面应用程序编写测试,但在测试主页 url 名称时我不断收到相同的错误

urls.py

from django.urls import path
from pages.views import HomePageView

app_name = 'pages'

urlpatterns = [
     path('', HomePageView.as_view(), name='home'),
]

test.py

from django.test import SimpleTestCase
from django.urls import reverse

class HomePageTest(SimpleTestCase):

    def test_homepage_url(self):
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)

    def test_homepage_name(self):
        url = reverse('home')
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

    def test_homepage_template(self):
        response = self.client.get('/')
        self.assertTemplateUsed(response, 'home.html')

views.py

from django.shortcuts import render
from django.views.generic import TemplateView

class HomePageView(TemplateView):
    template_name = 'pages/home.html'

pages/home.html

{% extends 'base.html' %}


{% block title %}Home{% endblock title %}


{% block content %}
  Welcome
{% endblock content %}

【问题讨论】:

    标签: html python-3.8 django-3.1


    【解决方案1】:

    您没有指定,但我认为是 test_homepage_name 给出了错误?

    尝试包含应用名称:

    url = reverse('pages:home')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-01
      • 2021-05-18
      • 2018-03-29
      • 2019-06-07
      • 2019-04-21
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      相关资源
      最近更新 更多