gpt4 book ai didi

django - 当一切看起来都正确时,为什么我的 django 项目中出现错误 404?

转载 作者:行者123 更新时间:2023-12-04 07:45:29 30 4
gpt4 key购买 nike

我的 Django 项目中有两个应用程序:篮子店铺 .在根 url 文件中,我配置了 urls.py 像这样:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls', namespace='store')),
path('basket/', include('basket.urls', namespace='basket')),
store/urls.py :
from django.urls import path

from . import views

app_name = 'store'

urlpatterns = [
path('', views.all_products, name='all_products'),
path('<slug:slug>/', views.product_detail, name='product_detail'),
path('category/<slug:category_slug>/',
views.category_list, name='category_list')
]
篮子/urls.py :
from django.urls import path

from . import views

app_name = 'basket'

urlpatterns = [
path('', views.basket_summary, name='basket_summary'),
path('add/', views.basket_add, name='basket_add'),
]
我收到一个错误:
找不到页面(404)
请求方式:GET
请求网址:http://127.0.0.1:8000/basket/
提出者:store.views.product_detail
这是我的 商店/views.py :
from django.shortcuts import get_object_or_404, render
from .models import *

def product_detail(request, slug):
product = get_object_or_404(Product, slug=slug, in_stock=True)
context = {
'product': product,
}

return render(request, 'store/products/detail.html', context)
请帮我解决这个问题我已经坚持了很长时间。

最佳答案

如果您想避免 404 错误,请尝试这种方式

from django.shortcuts import get_object_or_404, render
from .models import *

def product_detail(request, slug):
try:
product = Product.objects.get(slug=slug, in_stock=True)
context = {
'product': product,
}
except Product.DoesNotExist:
raise ValidationError('Product Does not exist ')

return render(request, 'store/products/detail.html', context

)

关于django - 当一切看起来都正确时,为什么我的 django 项目中出现错误 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67215329/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com