I am using Django on a large project and am struggling with determining the best pattern for a common situation. For instance, I have a Django model and in my HTML I need to use the one field of the model in a SELECT element and when a selection is made from that element, I need to autofill another value from the model in an INPUT field via JQuery.
I have a Django model, HTML template and Javascript like:
models.py
class StockSignoutMessage(models.Model):
msg_name = models.CharField(max_length=32)
msg_text = models.CharField(max_length=255, blank=True)
signout.html
<select name="stock_msgs" id="stock_msgs">
{% for msg in all_stock_signout_msgs %}
<option value="{{ msg.pk }}">{{ msg.msg_name }}</option>
{% endfor %}
</select>
<input type="text" size="50" name="comment" id="comment" />
signout.js
$(document).ready(function() {
$("#stock_msgs").click(stock_msg_builder);
});
stock_msg_builder = function() {
var outfield = $("#comment");
var selected_msg_index = $("#stock_msgs").val();
var add_msg = stock_msgs[selected_msg_index];
outfield.val(outfield.val() + add_msg );
outfield.focus();
}
In my HTML I need to use the msg_name in a SELECT element and when a selection is made from that element, I need to use the value to add the msg_text to a INPUT field via JQuery.
I have tried doing this a couple of different ways:
(1) I pass just the model to the template and create the SELECT and Javascript object in the template:
views.py
all_stock_signout_msgs = StockSignoutMessage.objects.all()
return render_to_response("signout.html",
{'all_stock_signout_msgs': all_stock_signout_msgs,},
context_instance=RequestContext(request))
signout.html
<script type="text/javascript">
var stock_msgs = [];
{% for msg in all_stock_signout_msgs %}
stock_msgs[{{ msg.pk }}] = "{{ msg.msg_text }}";
{% endfor %}
</script>
(2) I pass the model to use in creating the SELECT and I also pass a JSON version of the model to create the Javascript object.
views.py
all_stock_signout_msgs = StockSignoutMessage.objects.all()
json_stock_signout_msgs = serializers.serialize("json", all_stock_signout_msgs)
return render_to_response("signout.html",
{'all_stock_signout_msgs': all_stock_signout_msgs,
'json_stock_signout_msgs': json_stock_Signout_msgs,},
context_instance=RequestContext(request))
signout.html
var stock_msgs = "{{ json_stock_signout_msgs }}";
signout.js
$(document).ready(function() {
$("#stock_msgs").click(stock_msg_builder);
});
stock_msg_builder = function() {
var outfield = $("#comment");
var selected_msg_index = $("#stock_msgs").val();
var add_msg = stock_msgs[selected_msg_index];
outfield.val(outfield.val() + add_msg );
outfield.focus();
}
So is it better to pass less data to the template but have more code in the template to format it, or to pass the same data multiple times in different formats but use more Javascript to process it. This is a simple model, but other parts of my project are much more complicated so I'd like to settle on one pattern for these use cases.