在我的Django项目中,我遇到了一个无法找到revers-url的问题。基本上,我在模板的{% url navLogoLinkName %}
中传递了一个上下文变量,我从页面生成的源html代码中检查了navLogoLinkName是否生成了正确的链接。然而,当点击链接时,我会得到一个NoReverseMatch错误。
在我的urls.py中,你可以看到我有一个带有name = 'hiddendimsum_nytorv'
的路径
"""website URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls.conf import re_path
from index.views import indexPage, hdnytorv, hd2900, hdbynight
from takeawayWebshop.views import TakeawayWebshopMain
from webshopCart.views import AddRemoveCartItems
from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve
admin.autodiscover()
urlpatterns = [
path('admin/', admin.site.urls),
path('', indexPage.as_view()),
path('hdnytorv', hdnytorv.as_view(), name='hiddendimsum_nytorv'),
path('hd2900', hd2900.as_view(), name='hiddendimsum_2900'),
path('hd2900_takeaway_webshop', TakeawayWebshopMain.as_view(), name="hiddendimsum_takeaway_webshop"),
path('changeItemQuantityInBasket', AddRemoveCartItems.as_view()),
#path('check-address-for-deliverable', AddressCheckForDeliverability.as_view()),
#path('changeItemQuantityInBasket', ChangeItemQuantity.as_view()),
#path('getTakeawayClosingOrderTime', lastPickupDeliveryOrderTime.as_view()),
#path('isPriceAboveDeliveryLimit', totalPriceDeliveryPossible.as_view()),
path('hdbynight', hdbynight.as_view(), name='hiddendimsum_bynight'),
#path('takeawayCheckout', TakeawayCheckout.as_view()),
#path('deliveryFormCheckout', DeliveryForm.as_view()),
#path('pickupFormCheckout', PickUpForm.as_view()),
#path('local_delivery_checkout_is_address_deliverable', localDeliveryCheckoutAddressCheck.as_view()),
#path('process_pickup_or_delivery_form', deliveryPickupFormProcess.as_view()),
#path('localDeliveryPayment', Payment.as_view(), name = 'localDeliveryPayment'),
#path('getPaymentId', getPaymentId.as_view()),
#path('paymentComplete', PaymentComplete.as_view(), name = 'paymentComplete'),
#path('paymentNotification', paymentNotificationWebhook),
#path('verifyPayment', paymentVerificationStaticPage.as_view(), name = 'verifyPayment'),
#path('backendPaymentVerification', backendPaymentVerification.as_view()),
re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
]
#When in production medida url must always be added to urlpatterns
#if settings.DEBUG:
#urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
在我的模板中,我有href="{% url navLogoLinkName %}"
,其中navLogoLinkName是从视图传递的上下文变量。
{% load static %}
<nav class="navbar navbar-expand-lg navbar-light bg-secondary" id ="navbar">
<button class="navbar-toggler m-auto" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="#navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand navbar-left" href="{% url navLogoLinkName %}" id="navbarLogoLink">
<img src="{{ navbarLogoPath }}" alt="{{ navbarLogoAlt }}" id="navbarLogo">
</a>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
{% for link in links %}
{% if link.0 == 'BOOK TABLE' %}
<li class="nav-item active" id="navbarListItem">
<a class="nav-link px-6" id ="mainNavlink" href="{{ link.1 }}" target="_blank"><h3 id="linkText">{{ link.0 }}</h3></a>
</li>
{% else %}
<li class="nav-item active" id="navbarListItem">
<a class="nav-link px-6" id ="mainNavlink" href="{{ link.1 }}"><h3 id="linkText">{{ link.0 }}</h3></a>
</li>
{% endif %}
{% endfor %}
</ul>
{% if controlReport %}
{% autoescape off %}
<a class="pull-right" href={{controlReport}} target="_blank">
<img src={% static 'media/kontrolRapport.gif' %} width="15%" height = auto>
</a>
{% endautoescape %}
{% endif %}
</div>
</nav>
在视图中,我有context['navLogoLinkName'] = 'hiddendimsum_nytorv'
。从urls.py中,您可以看到hiddendimsum_nytorv应该指向路径中的hdnytorv
。
from webshopCart.models import CartItem
from .models import TakeawayWebshop
from restaurant.models import Restaurant
# Create your views here.
from django.shortcuts import render
from django.views import View
from django.conf import settings
from website.Modules.webshopUtils import Session, getTotalItemsInCart
webshopName = 'Hidden Dimsum 2900'
class TakeawayWebshopMain(View):
def get(self, request, *args, **kwargs):
context = dict()
context['navbarLogoPath'] = 'static/media/hd2900coverLogo.png'
context['navLogoLinkName'] = 'hiddendimsum_nytorv'
context['links'] = list()
context['aboutUsRestaurant'] = Restaurant.objects.filter(name = webshopName)[0]
#Import the webshop object followed by the products
webshop = TakeawayWebshop.objects.filter(name = webshopName)
webshop = webshop[0]
products = webshop.getProducts()
#Check if session exists
session = Session(request = request)
isSessionValid = session.isSessionValid(webshopModelObject = webshop)
context['sessionValidity'] = isSessionValid
#Get product quantity if session exists
productToDisplay = list()
for product in products:
productDict = dict()
productDict['product'] = product
if isSessionValid:
cartItem = CartItem.objects.filter(session_id = request.session[settings.WEBSHOP_SESSION_KEY],
product = product)
if cartItem:
productDict['quantity'] = cartItem[0].quantity
else:
productDict['quantity'] = 0
else:
productDict['quantity'] = 0
productToDisplay.append(productDict)
context['products'] = productToDisplay
if isSessionValid:
context['totalCartItems'] = getTotalItemsInCart(request = request)
else:
context['totalCartitems'] = 0
print('from webshop main')
print(context)
return render(request, template_name="takeawayWebshopMain.html", context = context)
以下是从渲染页面生成的源html。你可以看到这个片段
<a class="navbar-brand navbar-left" href="/hdnytorv" id="navbarLogoLink">
<img src="static/media/hd2900coverLogo.png" alt="" id="navbarLogo">
</a>
这表明它指向了我的urls.py.中的正确链接
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap css-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!--social media icons-->
<link rel="stylesheet" type="text/css" href=/static/landingPage.css>
<link rel="stylesheet" type="text/css" href=/static/takeawayWebshop.css>
<title></title>
<!--SEO-->
<meta name="description" content="Hidden Dimsum 2900, Strandvejen 163, Hellerup online dimsum takeaway and local delivery webshop">
<meta name="keywords" content="Hidden Dimsum 2900, dimsum takeaway webshop, dimsum local delivery, dumplings takeaway, online ordering">
<meta name="author" content="Hidden Dimsum 2900">
<link rel="shortcut icon" type="image/png" href="/static/media/favicon_hd32x32.png"/>
<!--Font awesome-->
<script src="https://kit.fontawesome.com/efc09bd617.js" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<!--Google Analytics-->
<!-- Global site tag (gtag.js) - Google Analytics -->
<!--Easy table booking-->
<!--Easy table booking embedded-->
<script type="text/javascript">
(function() { var st=document.createElement('script'); st.type='text/javascript'; st.async=true; st.src='//book.easytablebooking.com/javascripts/widget/v2/book.js'; var sc=document.getElementsByTagName('script')[0]; sc.parentNode.insertBefore(st, sc); })();
</script>
<noscript>Your browser does not support JavaScript!</noscript>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-secondary" id ="navbar">
<button class="navbar-toggler m-auto" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="#navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand navbar-left" href="/hdnytorv" id="navbarLogoLink">
<img src="static/media/hd2900coverLogo.png" alt="" id="navbarLogo">
</a>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
</ul>
</div>
</nav>
<div class="container-fluid sticky-top" id="takeawayHeaderCartContainer">
<div class="row">
<div class="col-11" id="cartIconContent">
<a href="/takeawayCheckout">
<i class="fa" id="shoppingCartIcon"></i> <!--this code codes for the shopping cart icon-->
<span class='badge badge-warning' id='lblCartCount'>
0
</span>
</a>
</div>
</div>
</div>
<div class="container-fluid h-100">
<h1 class="contentHeader">Menu</h1>
<hr class = "titleHorisontalLine">
<div class="row row-cols-1 row-cols-md-4">
<div class="col-auto mt-5">
<div class="card h-100 text-center">
<div class="card-body">
<!--Title -->
<h5 class="card-title">Charr Siu Bao</h5>
<!--Product image with link -->
<img class="card-img embed-responsive-item" src="/media/productImages/DimsumBox.jpg" alt="">
<!--Product description-->
<p class="card-text">some descriptions here</p>
<!--Allergic note -->
<p class="card-text">allergy notes</p>
<!--Price-->
<h5 class="mt-4">100,- </h5>
<div class="input-group">
<div class="input-group-prepend">
<button class="btn btn-outline-secondary subtractItem" type="button" id="btn_subtract_charr-siu-bao" onclick="itemQuantityChangeButton(this)">
-
</button>
</div>
<input type="text" class="form-control" id="text_charr-siu-bao" placeholder="0" aria-label="ordered amount" aria-describedby="basic-addon1" readonly>
<div class="input-group-append">
<button class="btn btn-outline-secondary addOneItem" type="button" id="btn_add_charr-siu-bao" onclick="itemQuantityChangeButton(this)">
+
</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-auto mt-5">
<div class="card h-100 text-center">
<div class="card-body">
<!--Title -->
<h5 class="card-title">Product A</h5>
<!--Product image with link -->
<img class="card-img embed-responsive-item" src="/media/productImages/duckGaozi_TAI2jqx.jpg" alt="">
<!--Product description-->
<p class="card-text">product A description</p>
<!--Allergic note -->
<!--Price-->
<h5 class="mt-4">100,- </h5>
<div class="input-group">
<div class="input-group-prepend">
<button class="btn btn-outline-secondary subtractItem" type="button" id="btn_subtract_product-a" onclick="itemQuantityChangeButton(this)">
-
</button>
</div>
<input type="text" class="form-control" id="text_product-a" placeholder="0" aria-label="ordered amount" aria-describedby="basic-addon1" readonly>
<div class="input-group-append">
<button class="btn btn-outline-secondary addOneItem" type="button" id="btn_add_product-a" onclick="itemQuantityChangeButton(this)">
+
</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-auto mt-5">
<div class="card h-100 text-center">
<div class="card-body">
<!--Title -->
<h5 class="card-title">Product B</h5>
<!--Product image with link -->
<img class="card-img embed-responsive-item" src="/media/productImages/duckGaozi_BcevHBI.jpg" alt="">
<!--Product description-->
<p class="card-text">product B description</p>
<!--Allergic note -->
<!--Price-->
<h5 class="mt-4">200,- </h5>
<div class="input-group">
<div class="input-group-prepend">
<button class="btn btn-outline-secondary subtractItem" type="button" id="btn_subtract_product-b" onclick="itemQuantityChangeButton(this)">
-
</button>
</div>
<input type="text" class="form-control" id="text_product-b" placeholder="0" aria-label="ordered amount" aria-describedby="basic-addon1" readonly>
<div class="input-group-append">
<button class="btn btn-outline-secondary addOneItem" type="button" id="btn_add_product-b" onclick="itemQuantityChangeButton(this)">
+
</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-auto mt-5">
<div class="card h-100 text-center">
<div class="card-body">
<!--Title -->
<h5 class="card-title">Product C</h5>
<!--Product image with link -->
<img class="card-img embed-responsive-item" src="/media/productImages/porkGaozi_min_xa7mpZQ.jpg" alt="">
<!--Product description-->
<p class="card-text">Product C description</p>
<!--Allergic note -->
<!--Price-->
<h5 class="mt-4">300,- </h5>
<div class="input-group">
<div class="input-group-prepend">
<button class="btn btn-outline-secondary subtractItem" type="button" id="btn_subtract_product-c" onclick="itemQuantityChangeButton(this)">
-
</button>
</div>
<input type="text" class="form-control" id="text_product-c" placeholder="0" aria-label="ordered amount" aria-describedby="basic-addon1" readonly>
<div class="input-group-append">
<button class="btn btn-outline-secondary addOneItem" type="button" id="btn_add_product-c" onclick="itemQuantityChangeButton(this)">
+
</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-auto mt-5">
<div class="card h-100 text-center">
<div class="card-body">
<!--Title -->
<h5 class="card-title">pork gaozi</h5>
<!--Product image with link -->
<img class="card-img embed-responsive-item" src="/media/productImages/porkGaozi.jpg" alt="">
<!--Product description-->
<p class="card-text">here is description for pork gaozi</p>
<!--Allergic note -->
<!--Price-->
<h5 class="mt-4">50,- </h5>
<div class="input-group">
<div class="input-group-prepend">
<button class="btn btn-outline-secondary subtractItem" type="button" id="btn_subtract_pork-gaozi" onclick="itemQuantityChangeButton(this)">
-
</button>
</div>
<input type="text" class="form-control" id="text_pork-gaozi" placeholder="0" aria-label="ordered amount" aria-describedby="basic-addon1" readonly>
<div class="input-group-append">
<button class="btn btn-outline-secondary addOneItem" type="button" id="btn_add_pork-gaozi" onclick="itemQuantityChangeButton(this)">
+
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid d-flex justify-content-end">
<div class="row">
<a href="/takeawayCheckout" role="button" id="checkoutLink">
<button type="button" class="btn btn-success btn-lg">Checkout</button>
</a>
</div>
</div>
<footer class="bg-dark text-center text-white">
<div class="container p-4 mx-auto">
<a href="https://www.facebook.com/Hiddendimsum2900" target="_blank" class="footerIcon">
<i class="fa-brands fa-facebook fa-3x"></i>
</a>
<a href="https://www.instagram.com/hiddendimsum2900" target="_blank" class="footerIcon">
<i class="fa-brands fa-instagram fa-3x"></i>
</a>
</div>
<div class="container p-2 mx-auto">
<form method="post">
<input type="hidden" name="csrfmiddlewaretoken" value="nVitBexkVreopuERtPpFqceQ7iImmDAyg6WLG8rqNj7dyZCuaZwwKsOfCf3EJSjo">
<p><label for="newLetterEmailLabel" class="bodyText" id="newLetterEmailLabel">Newsletter Subscription</label></p>
<input type="email" name="subscriptionEmail" placeholder="email@example.com">
<button type="submit" name="action" class="btn btn-primary" value="emailSubscription" id="newsLetterSubmitButton">Subscribe</button>
</form>
</div>
<div class="text-center footerText p-3" id="footerAddress">
©Hidden Dimsum 2900
<br>
Strandvejen, 163, 2900, Hellerup
<br>
CVR: 38908901
<br>
Phone : +45-40388884
</div>
</footer>
<script src="/static/scripts/product_add_subtract_btn_clicked.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
</body>
</html>
仍然当点击导航栏标志图像时,我得到以下错误
Internal Server Error: /hdnytorv
...
django.urls.exceptions.NoReverseMatch: Reverse for '/' not found. '/' is not a valid view function or pattern name.
[02/Apr/2022 23:46:16] "GET /hdnytorv HTTP/1.1" 500 209584
您可以使用;URL命名空间";。添加一个";应用程序名称";在您的urls.py:
app_name = 'myAppName'
...
path('hd2900', hd2900.as_view(), name='hd2900')
...
在您的模板中,使用{% url 'myAppName:hd2900' %}
:
<a class="navbar-brand navbar-left" href="{% url 'myAppName:hd2900' %}" id="navbarLogoLink">
<img src="{{ navbarLogoPath }}" alt="{{ navbarLogoAlt }}" id="navbarLogo">
</a>