Django表格内DELETE按钮直接删除功能实现求助
问题:点击表格中DELETE按钮直接执行删除,无需跳转页面
当前add_stock.html模板表格中的DELETE按钮点击后会跳转到delete_stock.html页面,需求是点击按钮直接完成删除操作并返回add_stock页面,推测问题出在delete_stock.html模板,寻求解决线索。
相关代码
add_stock.html
{% extends 'base.html' %} {% block content %} <div class="card-body"> <div class="table-responsive"> <table class="table align-middle table-hover table-bordered" id="example" style="text-align: center" > <thead class="table-dark thead-default" style="align-items: center"> <tr> <th scope="col">Symbol</th> <th scope="col">Previous Close</th> <th scope="col">Price</th> <th scope="col">Change $</th> <th scope="col">Change %</th> <th scope="col">52Wk Low</th> <th scope="col">52Wk High</th> <th scope="col">YTD %</th> <th scope="col">Market Cap</th> <th scope="col"></th> <th scope="col">Company Name</th> </tr> </thead> <tbody> {% if ticker %} {% for list_item in output %} <tr> <th>{{ list_item.companyName }}</th> <td>{{ list_item.symbol }}</td> <td>$ {{ list_item.previousClose }}</td> <td>$ {{ list_item.latestPrice }}</td> <td>$ {{ list_item.change }}</td> <td>{{ list_item.changePercentage }} %</td> <td>$ {{ list_item.week52Low }}</td> <td>$ {{ list_item.week52High }}</td> <td>{{ list_item.ytdChange }} %</td> <td>$ {{ list_item.marketCap }}</td> <td> <a class="btn btn-danger" href="{% url 'delete_stock' %}" ><i class="fa-regular fa-trash-can" aria-hidden="true"></i ></a> </td> </tr> {% endfor %} {% endif %} </tbody> </table> </div> </div> {% endblock %}
delete_stock.html
{% extends 'base.html' %} {% block content %} <h1>Delete Stock</h1> <br /><br /> {% if ticker %} {% for item in ticker %} <a href="{% url 'delete' item.id %}" class="btn btn-secondary" >Delete {{ item }}</a > <br /><br /> {% endfor %} {% else %} You don't have any stocks... {% endif %} {% endblock %}
urls.py
from django.urls import path from . import views urlpatterns = [ path("", views.home, name="home"), path("add_stock.html", views.add_stock, name="add_stock"), path("delete/<stock_id>", views.delete, name="delete"), path("delete_stock.html", views.delete_stock, name="delete_stock"), ]
views.py
def home(request): import requests import json if request.method == 'POST': ticker = request.POST['ticker'] api_request = requests.get("https://cloud.iexapis.com/stable/stock/" + ticker + "/quote?token=<YOUR_KEY>") try: api = json.loads(api_request.content) except Exception as e: api = "Error..." return render(request, 'home.html', {'api': api}) else: return render(request, 'home.html', {'ticker': "Enter a Ticker Symbol Above or Stock Quote..."}) def add_stock(request): import requests import json if request.method == 'POST': form = StockForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, ("Stock added successfully!")) return redirect('add_stock') else: ticker = Stock.objects.all() output = [] for ticker_item in ticker: api_request = requests.get("https://cloud.iexapis.com/stable/stock/" + str(ticker_item) + "/quote?token=<YOUR_KEY>") try: api = json.loads(api_request.content) output.append(api) except Exception as e: api = "Error..." return render(request, 'add_stock.html', {'ticker': ticker, 'output': output}) def delete(request, stock_id): item = Stock.objects.get(pk=stock_id) item.delete() messages.success(request, f"{item} deleted successfully!") return redirect("add_stock") def delete_stock(request): ticker = Stock.objects.all() return render(request, "delete_stock.html", {"ticker": ticker})
页面截图
- add_stock.html页面:

- delete_stock.html页面:

解决方法
问题根本不在delete_stock.html,而是add_stock.html里的删除按钮链接错误,当前指向的是delete_stock视图(跳转到中间页面),需要直接指向delete视图并传递对应股票的ID。
修改步骤:
- 在
add_stock视图中,将Stock模型的ID关联到API返回的数据中:
def add_stock(request): import requests import json if request.method == 'POST': form = StockForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, ("Stock added successfully!")) return redirect('add_stock') else: tickers = Stock.objects.all() output = [] for ticker_item in tickers: api_request = requests.get("https://cloud.iexapis.com/stable/stock/" + str(ticker_item) + "/quote?token=<YOUR_KEY>") try: api = json.loads(api_request.content) # 把Stock模型ID加入返回数据 api['stock_id'] = ticker_item.id output.append(api) except Exception as e: api = "Error..." return render(request, 'add_stock.html', {'tickers': tickers, 'output': output})
- 修改
add_stock.html中的删除按钮链接,直接调用delete视图并传递stock_id:
<td> <a class="btn btn-danger" href="{% url 'delete' list_item.stock_id %}" ><i class="fa-regular fa-trash-can" aria-hidden="true"></i ></a> </td>
- 可选安全优化:使用POST请求执行删除(避免GET误操作),将链接替换为表单:
<td> <form method="POST" action="{% url 'delete' list_item.stock_id %}" style="display:inline;"> {% csrf_token %} <button type="submit" class="btn btn-danger" onclick="return confirm('确定要删除该股票吗?')"> <i class="fa-regular fa-trash-can" aria-hidden="true"></i> </button> </form> </td>
同时在delete视图中限制仅处理POST请求:
def delete(request, stock_id): if request.method == 'POST': item = Stock.objects.get(pk=stock_id) item.delete() messages.success(request, f"{item} deleted successfully!") return redirect("add_stock")
修改完成后,点击DELETE按钮会直接执行删除操作并返回add_stock页面,无需经过delete_stock.html中间页。
内容的提问来源于stack exchange,提问作者Zika13
相关产品推荐
相关产品推荐

