# My app path
urlpatterns = [
path("", views.home, name="home"),
path("show_category/<slug:category_slug>/", views.show_category, name="catalog_category"),
path("<slug:product_slug>/", views.show_product, name="catalog_product")
]
def show_category(request, category_slug):
context={
"c" : get_object_or_404(Category, slug=category_slug),
"products" : c.product_set.all(),
"page_title" : c.name,
}
template_name="catalog/category.html"
return render(request, template_name, context)
# Project path
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("catalog.urls")),
path("catalog/", include("catalog.urls")),
path("cart/", include("cart.urls")),
]
除了我的主页之外,我看不到我的任何网址,我是 django 的新手,我没有看到任何关于它的文档或堆栈溢出中的任何内容。任何帮助都会很棒。 我还不想做正则表达式,试图学习如何以路径和重新路径两种方式做网址。谢谢!
你拥有的大部分东西都是不必要的,或者是错误的。修复你所拥有的一切。注意我的评论。我假设您的 html 模板位于正确的位置,因此它们可以正确呈现。
根项目:
# urls.py
urlpatterns = [
path("admin/", admin.site.urls),
path("", views.home, name="home"), # this makes yourwebsite.com/ the home page... Don't include yourwebsite.com/catalog/ twice, cause that's what you had.
path("catalog/", include("catalog.urls")),
path("cart/", include("cart.urls")),
]
# views.py
def home(request):
return render(request, 'template_name.html')
您的目录应用:
# urls.py
app_name = "catalog_app"
# all html templates linking to catalog/ must now use the following pattern: {% url 'catalog_app:name_argument' %}... examples follow...
urlpatterns = [
path("", views.catalog_home, name="catalog_home"), # goes website.com/catalog/, and must be referenced as {% url 'catalog_app:catalog_home' %} in html templates
path("show_category/<slug:category_slug>/", views.show_category, name="show_category"), # goes to website.com/catalog/show_category/category_slug/
path("<slug:product_slug>/", views.show_product, name="catalog_product")
]
# views.py
from .models import YourCategoryClassModel
def show_category(request, category_slug):
# the following .get() requires you to have an instance already created in the admin panel for it to work. Otherwise it won't work and you'll get errors.
your_model_value = YourCategoryClassModel.objects.get(id=category_slug)
return render(request, 'your_template.html', {'your_model_key': your_model_value})
# your_template.html
<p>{{ your_model_key.attribute_name }}</p>
<p>{{ your_model_key.whatever_you_called_them }}</p>
<p>{{ your_model_key.lowercaserelatedmodelname_set.any_method_or_attribute_for_that_model }}</p>
<!-- Or you can use the following -->
<p>{{ your_model_key.lowercaserelatedmodelname_set.all }}</p>
因此,对于上面的模板,如果您有一个Parent
类,并且有一个通过 ForeignKey 字段与父级相关的Child
类,则模板将如下所示:
<p>{{ your_model_key.child_set.all }}</p>
尝试将函数show_category放在 views.py 文件中,而不是 urls.py。