How do I connect a non-form button or link, written in HTML, to python code in Django? Specifically, suppose I have a button in HTML that redirects the page using href="/some-link". How do I, say, save specific info to a session (i.e., save which button was pushed) in Django when such a button is pushed?
Basically, I want to do something similar to the following in views.py:
if request.POST['form-type'] == u"purchase-button":
# save some info before redirecting the page
request.session['some-variable'] = 'the-purchase-button-was-pressed'
return redirect('some-link')
... except this isn't a form, so I can't actually do that.
Do I modify the following HTML somehow?
<a href="/some-link">Purchase</a>
I'm a bit new to Django and web development in general, so any help will be much appreciated.
(Basically, I have the exact question that was posed here in the following link, but I wasn't really satisfied with the answer: Django: How to trigger a session 'save' of form data when clicking a non-submit link )
EDIT:
I ended up using a blank form, as shown below, which let me reference which button was pressed in the python code below, without the user actually filling in information.
in HTML:
<form id="purchase" action="" method="post" name="purchase">
{% csrf_token %}
<input type="hidden" name="form-type" value="purchase" /> <!-- set type -->
<input type="hidden" name="form-id" value="{{ item.id }}" /> <!-- set item ID -->
<button name="purchase" type="submit" id="purchase-submit" data-submit="...Sending">Purchase</button>
</form>
in views.py:
if request.POST['form-type'] == u"purchase":
# this allows me to call the corresponding item by its ID
desired_item = StoreItem.objects.get(id=str(request.POST['form-id']))
# this saves information about the desired item
request.session['item_name'] = str(desired_item.title)
request.session['item_id'] = str(request.POST['form-id'])
request.session['amount'] = str(desired_item.price)
return redirect('shipping')
This allows me to get information from a button and use it in views.py, even though the user doesn't input in any other information.
I would send it as a GET request with parameters, setting the button to redirect to "/some-link/?button=PURCHASE".
So, in views.py you will have the "request.GET['button']" and it's value is going to be "PURCHASE".