首页 > 解决方案 > 如何使用 django 中的模板标签在另一个应用程序中调用视图?

问题描述

我收到一个错误,找不到“question_list”的反向。“question_list”不是有效的视图函数或模式名称。在模板中使用模板标签“collab_app:question_list”后。

主页.html:

{% extends "_base.html" %} 
{% load static %}
{% load socialaccount %}
{% block title %}Home{% endblock title %} 
{% block content %}
<h1>Homepage</h1>
<a href="{% url 'collab_app:question_list' %}">Ask Question Here</a>
<img class="collabimage" src="{% static 'images/collab.jpg' %}" ><br>
{% if user.is_authenticated %}
  Hi {{ user.email }}
  <p><a href="{% url 'account_logout' %}">Log Out</a></p>
{% else %}
  <p>You are not logged in</p>
  <!--Github-->
  <a href="{% provider_login_url 'github' %}" ><p class="git">Github</p></a>
  <a href="{% url 'account_login' %}">Login</a>
  <a href="{% url 'account_signup' %}">Sign Up</a>
{% endif %}
{% endblock content %}

视图.py:

class HomePageView(generic.TemplateView):
    template_name = "home.html"

用户应用程序中的 urls.py:

from django.urls import path, include
from .views import SignupPageView
from .views import HomePageView

app_name = "users"

    urlpatterns = [
        path("", HomePageView.as_view(), name="home"),
        path("signup/", SignupPageView.as_view(), name="signup"),
    ]

项目中的 urls.py:

from django.contrib import admin
from django.urls import path, include
from users.views import HomePageView


urlpatterns = [
    path("", include("users.urls")),
    path("collab/", include("collab_app.urls"),),  # , "collab_app")),
]

collap_app 中的 urls.py:

from django.contrib import admin
from django.urls import path, include
from collab_app import views
from users.views import HomePageView

app_name = "collab_app"

urlpatterns = [
    path("", views.QuestionListView.as_view(), name="question-list"),
]

collab_app 中的 view.py:

class QuestionListView(ListView):
    model = Question
    template_name = "collab_app/question_list.html"

标签: djangodjango-templatesdjango-views

解决方案


您将网址命名为question-list并且您正在引用question_list;这只是一个错字。

改为使用{% url 'collab_app:question-list' %}


推荐阅读