I am currently trying to use javascript to display an extra form field if the product selected returns true on a method which checks for this. While I have the onchange part setup for the form select I am struggling to actually get access to the products methods. I’m assuming I have to use json which I have no experience with. I’m hoping to do the following which is use the return from the method in an if statement. The code I am attempting to use at the moment is (I realise it is just displaying an alert atm but my priority is to get it working):
function openingCheck(optionValue){
{% check_opening_date as json %}
var checkOpeningDateJSON = {{json|safe}};
if(checkOpeningDateJSON)
alert(optionValue);
};
Which uses:
@register.tag(name="check_opening_date")
def check_opening_date(parser, token):
"""return whether the product should show the opening date or not"""
product = Product.objects.get(pk=productID)
return serializers.serialize('json',product.show_opening_date())
The issues I am having is I’m not sure how to pass optionValue to the check_opening_date function and also how to return the value of product.show_opening_date().
Any tips will be greatly appreciated.
There are two approaches.
When rendering the page, save the result of
show_opening_date()somewhere along with the form select. That means that for every product listed, you either create a corresponding hidden input somewhere, or save the result as an attribute in the select or something. When a product is selected, you simply use javascript to check the value of this hidden input or attribute. No interaction with the server is required with the server after load. (There is one request to the server over all)Alternatively, you simply display the products. When one is selected, you use ajax to contact the server with an ID for the product. The server runs
product.show_opening_date()and returns json with the result. (There are numerous requests to the server; the initial, and everytime a user selects a product)What you have doesn’t make sense. Remember that the template (along with all your template variables and template tags) are assembled when the page is rendered, so they don’t have any concept of javascript being carried out (or onchange events etc). You seem to be a bit confused by the concept of template tags. These should be used for template logic to display information that has been aggregated in the view (generally – it’s not set in stone).