我的django模板中有很多按钮。每个按钮都有一个不同的名称{{transaction.id}}。如何在我的视图中参考(提交)单个按钮?
base.html文件
<h3>Open transactions</h3>
{% for transaction in transactions_open %}
{{ transaction.id }} {{transaction.timestamp}} {{ transaction.currency }} {{ transaction.sell_or_buy }} {{ transaction.bid }} {{ transaction.date_add }}
<form action="" method="POST">
{% csrf_token %}
<button type="submit" name={{ transaction.id }} value="close">Close</button>
</form>
</p>
{% endfor %}
views.py
class MainView(View):
def get(self, request):
transactions_open = DealModel.objects.filter(open_or_closed='OPEN')
transactions_closed = DealModel.objects.filter(open_or_closed='CLOSED')
content_dict = {'transactions_open': transactions_open,
'transactions_closed': transactions_closed}
return TemplateResponse(request, 'base.html', content_dict)
def post(self,request):
if request.method == 'POST':
transactions_open = DealModel.objects.filter(open_or_closed='OPEN')
transactions_closed = DealModel.objects.filter(open_or_closed='CLOSED')
if request.POST.get('name???') == 'close':
content_dict['answer'] = "Closed!!!"
return TemplateResponse(request, 'base.html', content_dict)
答案 0 :(得分:1)
def post(self,request):
当请求方法为POST
时,系统会调用它,因此您 需要检查
此解决方案取决于我从问题中得到的内容
您不需要表单来关闭按钮如果您想隐藏它,可以使用javascript处理它
<ul>{% for transaction in transactions_open %}
<li class="close_button" data-pk="{{ transaction.id }}">{{ transaction.id }} {{transaction.timestamp}} {{ transaction.currency }} {{ transaction.sell_or_buy }} {{ transaction.bid }} {{ transaction.date_add }}
<a type="submit" value="close">Close</a>
</li>
{% endfor %}</ul>
使用jquery
在javascript文件中$('.close_button a').onclick(function(){
$(this).parent(".close_button").hide(); // something like that
$.ajax{
url: "{% url 'app_label:view_name' %}",
data: {'data':$(this).data("pk")},
method: "POST",
success: function (result,status,xhr) {
alert('closed Successfully.');
},
})
处理在视图处关闭交易:
class MyView(View):
def post(self, request, *args, **kwargs):
if request.is_ajax():
id = request.post.get("pk")
Transaction.objects.get(id=id).close() #develop close method at your model classes
答案 1 :(得分:0)
感谢您的回答。以下是我解决问题的方法:
class MainView(View):
def post(self,request):
if 'close' in request.POST.values():
for key, value in request.POST.items():
if value == 'close':
deal_id = key # deal_id is the value of {{transaction.id}} in template file.
if request.POST.get(deal_id) == 'close':
closing_deal = DealModel.objects.get(id=deal_id)
closing_deal.open_or_closed = 'Closed'
closing_deal.save()
content_dict['answer'] = "Closed!!!"
return TemplateResponse(request, 'base.html', content_dict)