【问题标题】:How to link html files together using Django?如何使用 Django 将 html 文件链接在一起?
【发布时间】:2020-06-08 11:56:32
【问题描述】:

我正在使用 django 3.0 和 python 3.8。我是编码新手。下面是我的项目层次结构。我想通过单击下面的 html 代码的继续按钮将我的“主页”页面连接到下一个 html“teoco”页面

myproject.urls-

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('', include('training_review.urls')),
    path('teoco', include('training_review.urls')),
    path('admin/', admin.site.urls),
]

home.urls-

from django.urls import path

from . import views
urlpatterns = [
    path('',views.home, name='home'),
    path('teoco',views.teoco, name='teoco')
]

home.views-

def home(request):
    return render(request, 'home.html')


def teoco(request):
    return render(request, 'teoco.html')

【问题讨论】:

  • 可以直接在href中使用{% url 'teoco' %}

标签: python django python-3.x django-views django-templates


【解决方案1】:

您可以使用 Django 的内置 URL 标签。见here

返回一个绝对路径引用(没有域名的 URL) 匹配给定的视图和可选参数。任何特殊字符 在生成的路径中将使用 iri_to_uri() 进行编码。

这是一种在不违反 DRY 原则的情况下输出链接的方式 必须在模板中对 URL 进行硬编码:

{% url 'some-url-name' v1 v2 %}

因此,在您的按钮中将此设置为 href 属性,例如:

<input class="btn btn-success" type="button" value="New Line" onclick="location.href="{% url 'addrow' %}""  />

上面的代码将导航到你的url中定义的views.py,你可以在该方法中呈现任何你喜欢的html页面。

【讨论】:

  • 感谢您的解释。我试着把下面的代码,但仍然显示“;”预计在行尾..请帮助
  • 你能不能试着把它改成&lt;input type="button" value="Continue" onclick="window.location.href="{% url 'teoco' %}"" /&gt;
  • 非常感谢,它起作用了..现在我也想做相反的事情..我的意思是我想在我的第二个“teoco”页面中添加一个按钮,比如“转到主页” ”。如何向 base.htm 添加一个地址以及如何从“teoco”页面调用它。下面是我的 base.html {% block content %} {% endblock %}
【解决方案2】:

你可以像这样创建一个 HTML 文件:

home.html

<html>
<a href="/teaco" > Go to teaco page</a> or
<a href="{% url 'teoco' %}"> Go to teaco page </a>

</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2016-12-01
    • 2014-04-18
    相关资源
    最近更新 更多