When I am using the get_url function in the SubCategroy model it gives an error like this.
NoReverseMatch at /products/category/fiction/ Reverse for 'products-by-sub-category' with arguments '('fantasy-fiction',)' not found. 1 pattern(s) tried: ['products/\^category/\(\?P(?P<category_slug>[-a-zA-Z0-9_] )\[\-\\W\]\ \)/\(\?P(?P<sub_category_slug>[-a-zA-Z0-9_] )\[\-\\w\]\ \)/\$\Z']
there are no errors when I am not using {{sub_category.get_url }} in my HTML. but I want to use the URLs of each sub-category in the HTML. what did I do wrong?
the way I used sub-categories maybe not be a good idea. if there are any good suggestions please add to your answer.
also, I want to use language as also another categorizing criterion. is there a better or alternate way to implement this?
My html
{% if category_links %}
{% for category in category_links %}
<li >
<a href="" data-bs-toggle="dropdown">{{ category.category_name }}</a>
<ul >
{% if sub_category_links %}
{% for sub_category in sub_category_links %}
{% if sub_category.category_id == category.pk %}
<li><a href="{{ sub_category.get_url }}"> {{ sub_category.subcategory_name }} </a></li>
{% endif %}
{% endfor %}
{% endif %}
<li><a href="{{ category.get_url }}"> View All </a></li>
</ul>
</li>
{% endfor %}
{% endif %}
urls.py
urlpatterns = [
path('', views.products, name="products"),
path('category/<slug:category_slug>/', views.products, name='products-by-category'),
path('category/<slug:category_slug>/<slug:sub_category_slug>/', views.products, name='products-by-sub-category'),
path('language/<slug:language_slug>/', views.products_by_language, name='products-by-language'),
]
views.py
def products(request, category_slug=None, sub_category_slug= None):
categories = None
sub_categories = None
products = None
if category_slug is not None:
if sub_category_slug is not None:
sub_categories = get_object_or_404(SubCategory, slug=sub_category_slug)
products = Products.objects.filter(sub_category=sub_categories, is_available=True)
else:
categories = get_object_or_404(Category, slug=category_slug)
sub_categories = SubCategory.objects.filter(category=categories)
products = Products.objects.filter(sub_category__in=sub_categories, is_available=True)
else:
products = Products.objects.all().filter(is_available=True)
context = {
'products' : products
}
return render(request, 'products/products.html', context)
def products_by_language(request, language_slug=None):
language = None
products = None
if language_slug is not None:
language = get_object_or_404(Language, slug=language_slug)
products = Products.objects.filter(language=language, is_available=True)
else:
products = Products.objects.all().filter(is_available=True)
context = {
'products' : products
}
return render(request, 'products/products.html', context)
models.py
class Category(models.Model):
category_name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=100, unique=True)
description = models.TextField(max_length=255, blank=True)
image = models.ImageField(upload_to='images/categories', blank=True)
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'
def get_url(self):
return reverse('products-by-category', args=[self.slug])
def __str__(self):
return self.category_name
class SubCategory(models.Model):
subcategory_name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=100, unique=True)
category = models.ForeignKey('Category', on_delete=models.CASCADE)
description = models.TextField(max_length=255, blank=True)
image = models.ImageField(upload_to='images/subcategories', blank=True)
class Meta:
verbose_name = 'sub category'
verbose_name_plural = 'sub categories'
def get_url(self):
return reverse('products-by-sub-category', args=[self.slug])
def __str__(self):
return self.subcategory_name
class Language(models.Model):
language_name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=100, unique=True)
description = models.TextField(max_length=255, blank=True)
image = models.ImageField(upload_to='images/subcategories', blank=True)
class Meta:
verbose_name = 'language'
verbose_name_plural = 'languages'
def get_url(self):
return reverse('products-by-language', args=[self.slug])
def __str__(self):
return self.language_name
context_processors.py
from .models import Category, SubCategory, Language
def category_links(request):
links = Category.objects.all()
return dict(category_links=links)
def sub_category_links(request):
links = SubCategory.objects.all()
return dict(sub_category_links= links)
def language_links(request):
links = Language.objects.all()
return dict(language_links= links)
full error
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/products/category/fiction/
Django Version: 4.1
Python Version: 3.10.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
'administrator',
'categories',
'products']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /Users/Jauhar/Web development/django/ecom project/templates/include/navbar.html, error at line 82
Reverse for 'products-by-sub-category' with arguments '('fantasy-fiction',)' not found. 1 pattern(s) tried: ['products/\\^category/\\(\\?P(?P<category_slug>[-a-zA-Z0-9_] )\\[\\-\\\\W\\]\\ \\)/\\(\\?P(?P<sub_category_slug>[-a-zA-Z0-9_] )\\[\\-\\\\w\\]\\ \\)/\\$\\Z']
72 : <a href="{% url 'products' %}">Best Sellers</a>
73 : </li>
74 : {% if category_links %}
75 : {% for category in category_links %}
76 : <li >
77 : <a href="" data-bs-toggle="dropdown">{{ category.category_name }}</a>
78 : <ul >
79 : {% if sub_category_links %}
80 : {% for sub_category in sub_category_links %}
81 : {% if sub_category.category_id == category.pk %}
82 : <li><a href=" {{ sub_category.get_url }} "> {{ sub_category.subcategory_name }} </a></li>
83 : {% endif %}
84 : {% endfor %}
85 : {% endif %}
86 : <li><a href="{{ category.get_url }}"> View All </a></li>
87 : </ul>
88 : </li>
89 : {% endfor %}
90 : {% endif %}
91 :
92 : <li >
Traceback (most recent call last):
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Jauhar/Web development/django/ecom project/products/views.py", line 34, in products
return render(request, 'products/products.html', context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/shortcuts.py", line 24, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/backends/django.py", line 62, in render
return self.template.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 175, in render
return self._render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/loader_tags.py", line 157, in render
return compiled_parent._render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/loader_tags.py", line 208, in render
return template.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 177, in render
return self._render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/defaulttags.py", line 322, in render
return nodelist.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/defaulttags.py", line 238, in render
nodelist.append(node.render_annotated(context))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/defaulttags.py", line 322, in render
return nodelist.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/defaulttags.py", line 238, in render
nodelist.append(node.render_annotated(context))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/defaulttags.py", line 322, in render
return nodelist.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 1064, in render
output = self.filter_expression.resolve(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 715, in resolve
obj = self.var.resolve(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 847, in resolve
value = self._resolve_lookup(context)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/template/base.py", line 914, in _resolve_lookup
current = current()
File "/Users/Jauhar/Web development/django/ecom project/categories/models.py", line 34, in get_url
return reverse('products-by-sub-category', args=[self.slug])
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/urls/base.py", line 88, in reverse
return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
File "/Users/Jauhar/Web development/django/ecom project/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 803, in _reverse_with_prefix
raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /products/category/fiction/
Exception Value: Reverse for 'products-by-sub-category' with arguments '('fantasy-fiction',)' not found. 1 pattern(s) tried: ['products/\\^category/\\(\\?P(?P<category_slug>[-a-zA-Z0-9_] )\\[\\-\\\\W\\]\\ \\)/\\(\\?P(?P<sub_category_slug>[-a-zA-Z0-9_] )\\[\\-\\\\w\\]\\ \\)/\\$\\Z']
CodePudding user response:
The products-by-sub-category
url is waiting for two slug arguments, category_slug
and sub_category_slug
, but you are passing just one to reverse()
.
You can try this:
class SubCategory(models.Model):
. . .
def get_url(self):
return reverse(
'products-by-sub-category',
args=[self.category.slug, self.slug]
)