Reputation: 123
I'm using two datepickers from the jQuery library for start and end dates. Once I have the two dates I send them to my django view via ajax. I then run the model query in my views which will return a filtered dict into my django context. My question now is how can I reload the table on the template?
Would I have to define a Javascript function to load a table and call it on ajax success? Or perhaps a better way?
html
<table class="table table-bordered">
<tr>
<th>Start Date: <input id="mail_start_date"/></th>
<th>End Date: <input id="mail_end_date"/></th>
<th><button id='btn'>Filter</button></th>
</tr>
<tr>
<th>Desk</th>
<th># of Packages</th>
</tr>
{% for desk, count in pick_dict.items %}
<tr>
<td>{{desk}}</td>
<td>{{count}}</td>
</tr>
{% endfor %}
Javascript
$(document).ready(function(){
$('#mail_start_date').datepicker({ dateFormat: "yy-mm-dd" });
$('#mail_end_date').datepicker({ dateFormat: "yy-mm-dd" });
$('#btn').click(function(){
var start = $('#mail_start_date').val();
var end = $('#mail_end_date').val();
$.ajax({
url: "/apps/centraldesk/mail/stats/",
type: "POST",
data: {
'start': start,
'end': end,
csrfmiddlewaretoken: '{{ csrf_token }}',
},
success: "SOMTHING NEEDS TO HAPPEN HRERE"
});
});
views.py
def mail_stats(request):
pick_dict = {}
if request.is_ajax():
pick_start = request.POST['start']
pick_end = request.POST['end']
pick_start = str(pick_start)
pick_end = str(pick_end)
in_date = datetime.datetime.strptime(pick_start, "%Y-%I-%d")
out_date = datetime.datetime.strptime(pick_end, "%Y-%I-%d")
pick_list = MailRecord.objects.filter(timeIn__range=(pick_start, pick_end))
for item in pick_list:
if pick_dict.has_key(item.desk.name):
pick_dict[item.desk.name] += 1
else:
pick_dict[item.desk.name] = 1
context = {
"mail_list" : mail_list,
"pick_dict" : pick_dict,
}
return render("mail_stats.html", context, context_instance=RequestContext(request, processors=[custom_proc]))
Upvotes: 0
Views: 698
Reputation: 173
Yes, you define a javascript function, like so
...
},
success: function(json) {
// Access your table here and manipulate it with the returned data from "json" (json is the dictionary given by your django view)
}
});
...
You could also add an error-function next to the success function.
Upvotes: 2