求求你我需要你的帮助。我不能将urls从模型返回到模板。我认为这个问题存在于get_absolute_url方法中。这是我得到的错误:
NoReverseMatch at /
Reverse for 'product_list' with arguments '('saws',)' not found. 1 pattern(s) tried: ['$']代码为:
# models
class Category(models.Model):
name = models.CharField(verbose_name='Category', max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True,
unique=True)
...
def get_absolute_url(self):
return reverse('core:product_list',
args=[self.slug])urls.py
app_name = 'core'
urlpatterns = [
path('', views.ProductView.as_view(), name='product_list'),]
#url(r'^$', views.ProductView.as_view(), name='product_list'),views.py
class ProductView(generic.ListView):
queryset = Product.objects.filter(available=True)
paginate_by = 3
form_class = QuantityForm
categories = Category.objects.all()
def category_slugg(self, category_slug=None):
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
return category
def get_context_data(self, **kwargs):
context = super(ProductView, self).get_context_data(**kwargs)
context['Products'] = self.form_class
context['categories'] = self.categories
context['category'] = self.category_slugg
return contexthtml
<li {% if not category %}class="selected"{% endif %}>
<a href="{{ categories.get_absolute_url }}"All</a>
</li>
{% for c in categories %}
<a href="{{ c.get_absolute_url }}">{{ c.name }}</a> <!--if delete 'c.get_absolute_url', except escape-->
{% endfor %}发布于 2020-02-05 19:58:47
你的url path不接受任何参数,但是你给它传递了一个slug。
您需要在URL中允许该插件;
path('<slug:category_slug>/', views.ProductView.as_view(), name='product_list'),在django文档中有一个这样的例子:https://docs.djangoproject.com/en/3.0/topics/http/urls/#examples
发布于 2020-02-05 20:03:06
尝试将args=[self.slug]更改为kwargs={'slug': self.slug},然后在urls.py中:
urlpatterns = [
path('<str:slug>/', views.ProductView.as_view(), name='product_list'),
]这个想法是get_absolute_url从urls接收kwargs。
https://stackoverflow.com/questions/60075165
复制相似问题