【问题标题】:Django redirection to another page not workingDjango重定向到另一个页面不起作用
【发布时间】:2020-06-12 13:27:30
【问题描述】:

所以我正在尝试使用 Django 和 HTML 创建一个网上商店。简而言之,我的问题是,当我按下导航栏上的“产品”按钮时,它会给我一个 404 错误。 This is the error it gives me.

它还在终端中给了我错误 The error in the terminal.

在过去的一个小时里,我一直试图找出问题所在,但似乎没有任何效果。 这是我的代码;

(文件 product.html 位于名为“templates”的文件夹中)

我的views.py文件

from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Item # Skriptist models.py impordib eseme (Item'i) #


def product(request):
    context = {
        "items": Item.objects.all()
    }
    return render(request, "product.html", context)

def checkout(request):
    return render(request, "checkout.html")



class HomeView(ListView):
    model = Item
    template_name = "home.html"


class ItemDetailView(DetailView):
    model = Item
    template_name = "product.html"

我的 urls.py 文件

from django.urls import path
from django.conf.urls import include, url
from .views import (
    ItemDetailView,
    checkout,
    HomeView
)
# Skriptist views.py improdib "item_list'i" #

app_name = "core"

urlpatterns = [
    path('', HomeView.as_view(), name='home'),
    path('checkout/', checkout, name='checkout'),
    path('product/<slug>/', ItemDetailView.as_view(), name='product'),
]

最后这是我的 scripts.html 文件,其中包含所有 javascript 内容。

{% load static %}

<script type="text/javascript" src="{% static 'js/jquery-3.3.1.min.js' %}"></script>
<!-- Bootstrap tooltips -->
<script type="text/javascript" src="{% static 'js/popper.min.js' %}"></script>
<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script>
<!-- MDB core JavaScript -->
<script type="text/javascript" src="{% static 'js/mdb.min.js' %}"></script>
<!-- Initializations -->
<script type="text/javascript">
  // Animations initialization
  new WOW().init();

</script>

有谁知道如何解决这个问题?

提前致谢, 尼米图。

【问题讨论】:

  • URL 中缺少 slug 部分。所以它不是一个有效的 url 模式。
  • path('product//', ItemDetailView.as_view(), name='product//'),你是说这个吗? @WillemVanOnsem
  • 没有。我的意思是,在链接到 that 页面的页面上,它缺少 slug。
  • 那么是在views.py 还是在我的导航栏文件中? (我现在可能听起来很愚蠢,但我很困惑)
  • @Nimetu 您需要在重定向到该页面的 URL 中设置 。我认为来自导航栏文件或您调用此视图的 HTML 文件

标签: html django url


【解决方案1】:

您收到的错误是因为您访问的 URL 与 urls.py 中的任何模式都不匹配。您正在访问的 http://127.0.0.1:8000/product 无效,因为您的模式有一个尾部斜杠,然后是 slug,尽管该定义也是错误的。

你的网址格式应该是

urlpatterns = [
    path('', HomeView.as_view(), name='home'),
    path('checkout/', checkout, name='checkout'),
    path('product/<slug:slug>/', ItemDetailView.as_view(), name='product'),
]

然后就可以访问如下网址了:

如果你想让http://127.0.0.1:8000/product 工作,那么你需要添加一个新条目并决定它应该显示什么,例如 ListView

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-14
    • 2018-04-29
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 2016-11-02
    • 2014-02-22
    相关资源
    最近更新 更多