首页 > 解决方案 > 无法将页面从主页转移到关于页面

问题描述

我正在尝试使用 django 创建一个小型 Web 应用程序,而我是新手

这是我的 index.html

<!DOCTYPE html>
<html>
<head>
  <title>Simple App</title>
<h1> Testing the simple app</h1>
</head>
<body>
  <a href="/about/">About </a>
</body>
</html>

这是我的 about.html

<!DOCTYPE html>
<html>
<head>
  <title>Simple App</title>
<h1> Testing the simple app</h1>
</head>
<body>

  This is the about page
</body>
</html>

这是我的意见.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

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

# Create your views here.

class HomePageView(TemplateView):
    def get(self, request, **kwargs):
        return render(request, 'index.html', context=None)

# Add this view
class AboutPageView(TemplateView):
    template_name = "about.html"

和 urls.py

from django.conf.urls import url
from django.contrib import admin
from homepage import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', views.HomePageView.as_view()),
    url(r'^about/$',views.AboutPageView.as_view()),
]

但是,当我单击关于按钮时,没有任何反应

标签: pythondjangodjango-templatesdjango-generic-views

解决方案


urls.py您可以直接告诉通用模板视图要使用的布局名称,如下所示:

from django.urls import include, path
from django.views.generic import TemplateView

urlpatterns = [
    path("", TemplateView.as_view(template_name="homepage.html"), name="home"),
    path("about/", TemplateView.as_view(template_name="about.html"), name="about" ]

使用命名的 url 比直接编码 url 更好,因为它们将来可能会改变。

然后在 homepage.html 中将其称为:

<a href="{% url 'about' %}">About</a>

更新:

如果您不能使用path并想使用url

url(r'^$',TemplateView.as_view(template_name="homepage.html"), name="home"),
url(r'^about/$',TemplateView.as_view(template_name="about.html"), name="about"),

推荐阅读