python - 无法将页面从主页转移到关于页面
问题描述
我正在尝试使用 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()),
]
但是,当我单击关于按钮时,没有任何反应
解决方案
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"),
推荐阅读
- python - 使用 Scrapy 解压缩文件列表并读取到 csv 的问题
- javascript - 向右移动推荐朋友和姓名按钮
- function - 更改列数据后插入空白行
- c++ - std::spanstream 通常如何在 C++ 中使用?
- python - 使用 pyserial 构建接收器时我做错了什么?
- mysql - 需要在 MySQL 中建立报表
- sql - Oracle 视图:如何仅显示未来几天?
- json - 使用 react-json-view-compare npm 包的问题
- c# - 如何在 .net 5 上与身份建立关系?
- android - MRTK Unity Android 通过触摸输入滚动太慢