Reputation: 1
I have many buttons in my django template. Each button has a different name {{transaction.id}}. How can I refer to (submit) a single button in my view?
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)
Upvotes: 0
Views: 1640
Reputation: 1
Thank you for your answer. Here is my solution to the problem:
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)
Upvotes: 0
Reputation: 2320
def post(self,request):
It will be called when the request method is POST
so you don't need to check it
This solution depends on what I got it from the question
You don't need a form to have a close button You can handle it using javascript if you want to hide it
<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>
at the javascript file using jquery
$('.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.');
},
})
Handle closing the transaction at the view:
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
Upvotes: 1