Reputation: 4391
I'm using the latest version of python3 and Django2, trying to do an URL pattern that is dynamic and changes for every different variable, Here are the codes:
urls.py
path('categories/<int:item_category>/', views.item_category, name="item_category"),
views.py
def item_category(request, pk):
item_category = get_object_or_404(Categories, pk=pk)
return render(request, 'items_modal.html', {'item_category': item_category})
models.py
class Categories(models.Model):
category_name = models.CharField(max_length=30)
def __str__(self):
return self.category_name
def item_category(self):
return reverse('item_category', args=[self.pk])
home.html
<div class="table-responsive">
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<th scope="col"><h2 align="center"> محتويات المخزن</h2></th>
</tr>
</thead>
<tbody>
{% for cat in all_cats %}
<tr>
<th scope="row"><a href="{% url 'item_category' item_category.pk %}"" data-toggle="modal" data-target="#exampleModal">{{ cat }}</a></th>
</tr>
{% endfor %}
</tbody>
</table>
</div>
when I try to go to open the home page it gives me the error :
NoReverseMatch at /
Reverse for 'item_category' with arguments '('',)' not found. 1 pattern(s) tried: ['categories\\/(?P<item_category>[0-9]+)\\/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 2.0.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'item_category' with arguments '('',)' not found. 1 pattern(s) tried: ['categories\\/(?P<item_category>[0-9]+)\\/$']
Exception Location: C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632
Python Executable: C:\Users\Dev3\AppData\Local\Programs\Python\Python36-32\python.exe
Python Version: 3.6.5
Python Path:
['C:\\python\\Django\\nothing',
'C:\\Users\\Dev3\\AppData\\Local\\Programs\\Python\\Python36-32\\python36.zip',
'C:\\Users\\Dev3\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs',
'C:\\Users\\Dev3\\AppData\\Local\\Programs\\Python\\Python36-32\\lib',
'C:\\Users\\Dev3\\AppData\\Local\\Programs\\Python\\Python36-32',
'C:\\Users\\Dev3\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages']
Server time: Tue, 24 Apr 2018 09:39:46 +0000
Upvotes: 0
Views: 204
Reputation: 308849
Reverse for 'item_category' with arguments '('',)' not found. 1 pattern(s) tried: ['categories\\/(?P<item_category>[0-9]+)\\/$']
In the error message, with arguments '('',)'
is telling you that the argument in the url
tag evaluated to the empty string ''
.
Looking at your template, you loop through {% for cat in all_cats %}
but then you use item_category.pk
inside the loop. You probably want cat.pk
:
{% for cat in all_cats %}
<tr>
<th scope="row"><a href="{% url 'item_category' cat.pk %}" data-toggle="modal" data-target="#exampleModal">{{ cat }}</a></th>
</tr>
{% endfor %}
Upvotes: 2