【问题标题】:How to fix NoReverseMatch error in Django table for a delete button如何修复 Django 表中删除按钮的 NoReverseMatch 错误
【发布时间】:2020-12-05 22:55:38
【问题描述】:

Python 版本 3.7.7 和 Django 版本 2.2.3。 Github 上的代码 https://github.com/jcwill415/Stock_Market_Web_App

我想在表格的最后一列中添加一个删除按钮。当代码在表之外时,它可以从表中删除一个条目。但是当代码在表格内时,我收到一个 NoReverseMatch 错误,上面写着:

  NoReverseMatch at /add_stock.html 
  Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<stock_id>[^/]+)$']

Request Method: GET
Request URL:    http://localhost:8000/add_stock.html
Django Version: 2.2.3
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<stock_id>[^/]+)$']
Exception Location: C:\djangostock\venv\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 668
Python Executable:  C:\djangostock\venv\Scripts\python.exe
Python Version: 3.7.7
Python Path:    
['C:\\Users\\JCW\\Desktop\\Stock_Market_Web_App-master\\stock',
 'C:\\Users\\JCW\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\JCW\\AppData\\Local\\Programs\\Python\\Python37-32\\Lib',
 'C:\\Users\\JCW\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Program Files\\Python37',
 'C:\\djangostock\\venv',
 'C:\\djangostock\\venv\\lib\\site-packages']

add_stock.html

<table class="table table-striped table-hover">

  <thead class="thead-dark">
    <tr>
      <th scope="col">TICKER</th>
      <th scope="col">COMPANY</th>
      <th scope="col">STK PRICE</th>
      <th scope="col">PREV CLOSE</th>
      <th scope="col">MARKET CAP</th>
      <th scope="col">VOLUME</th>
      <th scope="col">YTD CHG</th>
      <th scope="col">52 WK HIGH</th>
      <th scope="col">52 WK LOW</th>
      <th scope="col">REMOVE STK</th>
    </tr>
  </thead>
  <tbody>
{% if ticker %}
      
            {% for list_item in output %}
                <tr>
                    <th scope="row">{{ list_item.symbol }}</th>
                    <td>{{ list_item.companyName }}</td>
                    <td>${{ list_item.latestPrice }}</td/>
                    <td>${{ list_item.previousClose }}</td>
                    <td>${{ list_item.marketCap }}</td>
                    <td>{{ list_item.latestVolume }}</td>
                    <td>{{ list_item.ytdChange }}</td>
                    <td>${{ list_item.week52High }}</td>
                    <td>${{ list_item.week52Low }}</td>
                    <td><a href="{% url 'delete' item.id %}" class="btn btn-outline-danger btn-small">Delete {{ item }}</a></br></td>          
        </tr>
        
            {% endfor %}
        
  </tbody>
</table>
{% endif %}

{% for item in ticker %}
    <a href="{% url 'delete' item.id %}" class="btn btn-outline-danger btn-small">Delete {{ item }}</a> &nbsp;
{% endfor %}

views.py

def delete(request, stock_id):
    item = Stock.objects.get(pk=stock_id) # call database by primary key for id #
    item.delete()
    messages.success(request, ("Stock Has Been Deleted From Portfolio!"))
    return redirect('add_stock')

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('about.html', views.about, name="about"),
    path('add_stock.html', views.add_stock, name="add_stock"),
    path('delete/<stock_id>', views.delete, name="delete"),
    path('news.html', views.news, name="news"),
    
]

我的尝试 我尝试过使用 for 循环:

{% for item in ticker %}
   <td><a href="{% url 'delete' item.id %}" class="btn btn-outline-danger btn-small">Delete {{ item }}</a></td>
{% endfor %}

但它会循环遍历所有代码,因此每行的表格中的所有条目都有删除按钮。如果我不使用 for 循环,我会收到 NoReverseMatch 错误。我知道有办法解决这个问题,但我一直在努力并寻找了两个多月。

我也尝试了一个 while 循环,但无法让它工作。我尝试将删除表单添加到 add_stock.html 文件中,并在 views.py 文件中添加相应的请求。

我尝试过的链接,但仍然无法解决:

ments-not-found-django

【问题讨论】:

    标签: python django django-urls django-url-reverse


    【解决方案1】:

    您在 2 个不同的地方使用 delete。首先,您引用了错误的项目:

    {% for list_item in output %}
       ...
       {% url 'delete' item.id %} 
    

    应该是

    {% url 'delete' list_item.id %}
    

    第二个是正确的:

    {% for item in ticker %}
       <a href="{% url 'delete' item.id %}"
    

    另外,delete 在很多情况下都是保留字。我不认为这里是这种情况,但仍然是一个坏习惯。到处换成delete_stock

    <a href="{% url 'delete_stock' list_item.id %}" ...>
    
    def delete_stock(request, stock_id=None):
    
    path('delete_stock/<stock_id>', views.delete_stock, name="delete_stock"),
    

    stock_id 是整数还是字符串?要找出答案,请在 add_stock() 中的循环内打印:

    api = json.loads(api_request.content)
    print(api)
    output.append(api)
    

    另外,股票 ID 会在 url 中以字符串的形式出现,所以如果是整数,请执行以下操作:

    item = Stock.objects.get(pk=int(stock_id))
    

    或使用:

    path('delete_stock/<int:stock_id>', views.delete_stock, name="delete_stock"),
    

    其他网址是否有效?

    奖励提示:

    您的网址中无需包含.html。这看起来很陈旧。更好的形式是:

    urlpatterns = [
        path('', views.home, name="home"),
        path('about', views.about, name="about"),
        path('add_stock', views.add_stock, name="add_stock"),
        path('delete_stock/<int:stock_id>', views.delete_stock, name="delete_stock"),
        path('news', views.news, name="news"),
        
    ]
    

    【讨论】:

    • 谢谢,我尝试将其更新为 {% url 'delete' list_item.id %} 并删除第二个。但我仍然收到 NoReverseMatch 错误。 urls.py文件中的url是否也有问题?
    • 要排除故障,请将其添加到 url:path('delete_stock', views.delete_stock, name="delete_stock"),path('delete_stock/', views.delete_stock, name="delete_stock"),。然后在视图中测试stock_id。这将告诉您问题是否出在模板中的{{output}}
    • 另外,print(api) 和上面的编辑一样,看看你实际得到了什么。您可能正在发送一个空列表
    猜你喜欢
    • 2021-08-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 2018-03-12
    • 2017-12-12
    • 2018-09-28
    相关资源
    最近更新 更多