使用p的Django URL模式

2024-05-19 09:14:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用最新版本的python3和Django2,尝试创建一个动态的URL模式,并针对每个不同的变量进行更改,下面是代码:

网址.py

path('categories/<int:item_category>/', views.item_category, name="item_category"),

视图.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})

型号.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])

主页.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>

当我试图打开主页时,它给了我一个错误:

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

Tags: pyselflocaltabledev3itemusersappdata
1条回答
网友
1楼 · 发布于 2024-05-19 09:14:50
Reverse for 'item_category' with arguments '('',)' not found. 1 pattern(s) tried: ['categories\\/(?P<item_category>[0-9]+)\\/$']

在错误消息中,with arguments '('',)'告诉您,url标记中的参数计算为空字符串''。你知道吗

看看你的模板,你在{% for cat in all_cats %}中循环,然后在循环中使用item_category.pk。你可能想要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 %}

相关问题 更多 >

    热门问题