如何修复Django表中删除按钮的NoReverseMatch错误

2024-04-26 23:22:18 发布

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

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']

添加股票.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 %}

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

url.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 %}

但是它会循环遍历所有的ticker,因此表中每行的所有条目都有delete按钮。如果我不使用for循环,就会得到NoReverseMatch错误。我知道有一种方法可以解决这个问题,但我已经为此努力了两个多月

我还尝试了一个while循环,但无法使其工作。我尝试在add_stock.html文件中添加一个delete表单,并在views.py文件中添加相应的请求

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

没有找到django


Tags: addidforhtmlstockcolitemdelete
1条回答
网友
1楼 · 发布于 2024-04-26 23:22:18

您正在两个不同的地方使用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"),

其他URL有效吗

奖金提示:

您的URL中不需要有.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"),
    
]

相关问题 更多 >