我是Django新手和学习者,只需按照本教程操作即可,然后陷入困境。当我在django models.py中添加一个SlugField并创建一个get_absolute_url但出现反向错误时 导航栏。反向查找“ product”,未找到任何参数。尝试了1种模式:['product /(?P [^ /] +)/ $']。
在我的导航栏中,错误即将到来
navbar.html
<li class="nav-item">
<a class="nav-link waves-effect" href="{% url 'core:product' %}" target="_blank">Shop</a>
</li>
models.py
from django.db import models
from django.urls import reverse
from django.conf import settings
# Create your models here.
# Choices
CATEGORY_CHOICES = (
('S','Shirt'),
('P','Pants'),
('J','Jacket'),
('W','Watches'),
('E','Electronics'),
('SO', 'Shoes'),
)
LABEL_CHOICES = (
('P', 'primary'),
('S', 'secondary'),
('D', 'danger'),
)
class Item(models.Model):
title = models.CharField(max_length=200)
price = models.FloatField()
category = models.CharField(choices=CATEGORY_CHOICES,max_length=3)
image = models.ImageField(upload_to='images/')
slug = models.SlugField()
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('core:product', kwargs={"slug": self.slug})
class OrderItem(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
def __str__(self):
return self.item
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
item = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
orderd = models.BooleanField(default=False)
def __str__(self):
return self.user.username
urls.py
from django.urls import path
from .views import (
ItemListView,
checkout,
ItemDetailView,
)
app_name = 'core'
urlpatterns = [
path('',ItemListView.as_view(),name='item'),
path('checkout/',checkout,name='checkout'),
path('product/<slug>/', ItemDetailView.as_view(), name='product')
]
views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Item
# Create your views here.
class ItemListView(ListView):
model = Item
template_name= 'home.html'
def checkout(request):
return render(request,'checkou.html')
class ItemDetailView(DetailView):
model = Item
template_name = 'product.html'