dimanche 3 mai 2015

Passing parameters from one django view to another using JSON/AJAX

I'm trying to pass the category variable that a user has selected into the "category_id" variable in the BudgetJson view. The BudgetJson view is being called via a javascript AJAX call that's inside the expenses/detail.html template.

This is the view that renders when a user selects what expense they want more details on:

class ExpenseDetail(
    braces.PrefetchRelatedMixin,
    generic.DetailView
):
    model = models.ExpenseCategory
    prefetch_related = ('expenseCategory',)
    http_method_names = ['get']
    template_name = 'expenses/detail.html'


    def get(self, request, *args, **kwargs):
        self.object = self.get_object(kwargs.get('pk'))
        self.category = self.object.category
        self.category_id = self.object.expenseCategory.get_queryset.im_self.values()[0]['category_id']
        return super(ExpenseDetail, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ExpenseDetail, self).get_context_data(**kwargs)
        return context

    def get_queryset(self):
        queryset = super(ExpenseDetail, self).get_queryset()
        return queryset

This is the javascript in the template to fetch the data (a JSON object)

$(document).ready(function() {
        $('#expenses').DataTable( {
            "ajax": '{% url "property:budget:budget_json" %}'
    });
});        

This is the view that the AJAX url calls to get the JSON object. What I want to know how is to get the category_id from the first view into this view (what is currently set to 1)

def BudgetJson(request)
    out_list = []
    category_id = 1
    resultset = models.Expense.objects.filter(category_id=category_id)
    for model in resultset:
        temp_dict = {'expense_period': model.expensePeriod, 'expense_name':model.expenseName, 'expense_amount':model.expenseAmount }
        out_list.append(temp_dict)
    data = {'data' : out_list }
    return JsonResponse(data)

Aucun commentaire:

Enregistrer un commentaire