【问题标题】:unable to shift pages from homepage to about page无法将页面从主页转移到关于页面
【发布时间】:2019-01-12 04:40:57
【问题描述】:

我正在尝试使用 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()),
]

但是当我点击关于按钮时什么都没有发生

【问题讨论】:

    标签: python django django-templates django-generic-views


    【解决方案1】:

    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"),
    

    【讨论】:

    • 当我改变它时,我得到一个 NoReverseMatch found 错误 'about.html' is not a valid view function or pattern name
    • 检查您是否在 urls.py 中添加了name="about"
    • 我没有使用路径,因为我使用的是 django
    • 谢谢。有用!现在这足以建立我的基本技能,但是我有一个任务是使用表单和数据库来存储和访问数据。如果我对此有任何问题,如果您也能帮助我,我将不胜感激。
    猜你喜欢
    • 2019-09-10
    • 2011-06-11
    • 2012-04-23
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    • 2011-02-05
    相关资源
    最近更新 更多