在Django模板的AJAX中使用templatetag设置href属性

时间:2019-12-03 10:12:24

标签: javascript django ajax django-templates

我正在尝试赚钱跟踪器应用程序。有一个“交易”页面,用户可以按月查看其所有交易。默认情况下,模板以当前月份呈现,如下所示:

class TransactionsView(TemplateView):
    template_name = 'money_tracker/transactions.html'

    def get_context_data(self, *args, **kwargs):
        month, year, month_start, month_end = range_of_current_month()
        context = super().get_context_data(*args, **kwargs)
        income = sum(Transaction.objects.filter((Q(user=self.request.user) | Q(user=None)) &
                                                Q(category__expense_or_income_choices='INCOME', date__lte=month_end,
                                                  date__gte=month_start)).values_list('amount', flat=True))
        expense = sum(Transaction.objects.filter((Q(user=self.request.user) | Q(user=None)) &
                                                 Q(category__expense_or_income_choices='EXPENSE', date__lte=month_end,
                                                   date__gte=month_start)).values_list('amount', flat=True))
        income_transactions = Transaction.objects.filter((Q(user=self.request.user) | Q(user=None)) &
                                                Q(category__expense_or_income_choices='INCOME', date__lte=month_end,
                                                  date__gte=month_start))
        expense_transactions = Transaction.objects.filter((Q(user=self.request.user) | Q(user=None)) &
                                                Q(category__expense_or_income_choices='EXPENSE', date__lte=month_end,
                                                  date__gte=month_start))
        context['income'] = income
        context['expense'] = expense
        context['balance'] = income - expense
        context['month'] = month
        context['year'] = year
        context['income_transaction'] = income_transactions
        context['expense_transaction'] = expense_transactions
        return context

但是如果用户希望查看不同月份的交易,那么我想使用AJAX,我的模板如下所示(底部是AJAX):

{% extends 'money_tracker/base.html' %}

{% block body_block %}
    <section class="balance section">
        <div class="balance__sheet">
            <h3 class="header"><span class="arrow arrow_left">&#8678</span><span class="month">{{ month }}</span> <span class="year">{{year}}</span><span class="arrow arrow_right">&#8680</span></h3>
            <div>
                <h4 class="smaller__header">Balance: {{balance}}$</h4>
            </div>
            <div class="income_expense">
                Income: {{income}}$
                <div class="list_of_transactions">
                  <ul>
                    {% for trans in income_transaction %}
                        <li>{{trans.amount}}$, {{trans.date}}, {{trans.category}}, <a href="{% url 'update_expense' trans.pk %}">edit,</a><a href="{% url 'delete_transaction' trans.pk %}">delete</a></li>
                    {% endfor %}
                  </ul>
                </div>
            </div>
            <div class="income_expense">
                Expense: {{expense}}$
                <div class="list_of_transactions">
                  <ul>
                    {% for trans in expense_transaction %}
                        <li>{{trans.amount}}$, {{trans.date}}, {{trans.category}}, <a href="{% url 'update_expense' trans.pk %}">edit,</a><a href="{% url 'delete_transaction' trans.pk %}">delete</a></li>
                    {% endfor %}
                  </ul>
                </div>
            </div>
            <div style="clear:both;"></div>

        </div>
    </section>
{% endblock %}

{% block java_script %}
<script>
    function transactions_ajax(month_displayed, year_displayed){
      $.ajax({
        url: '{% url "check_transactions" %}',
        data: {
            'month': month_displayed,
            'year': year_displayed
        },
        dataType: 'json',
        success: function(data){
            document.querySelector('.smaller__header').textContent = 'Balance: ' + data['balance'] + '$';
            document.querySelectorAll('.income_expense')[0].childNodes[0].textContent = 'Income: ' + data['income'] + '$';
            document.querySelectorAll('.income_expense')[1].childNodes[0].textContent = 'Expense: ' + data['expense'] + '$';
            document.querySelectorAll('.list_of_transactions')[0].textContent="";
            document.querySelectorAll('.list_of_transactions')[1].textContent="";
            var li
            for (i=0; i<data['income_transactions'].length; i++){
                li = document.createElement('li');
                li.innerHTML = `${data['income_transactions'][i][2]}, ${data['income_transactions'][i][3]} - <strong> ${data['income_transactions'][i][1]} $ </strong><a href="{% url 'update_expense' ${data['income_transactions'][i][0]} %}">edit</a>`;
                document.querySelectorAll('.list_of_transactions')[0].appendChild(li);
            }
            for (i=0; i<data['expense_transactions'].length; i++){
                li = document.createElement('li');
                li.innerHTML = '<span class="span_category">'+data['expense_transactions'][i][1]+'</span><span class="span_money">'+data['expense_transactions'][i][2]+'$</span>';
                document.querySelectorAll('.list_of_transactions')[1].appendChild(li);
            }
        }
      });
    }


    document.querySelector('.arrow_left').onclick = () => {
        var month_year = subtractMonth();
        month_year[0] = document.querySelector('.month').textContent;
        month_year[1] = document.querySelector('.year').textContent;
        transactions_ajax(month_year[0], month_year[1]);
    }

    document.querySelector('.arrow_right').onclick = () => {
        var month_year = addMonth();
        month_year[0] = document.querySelector('.month').textContent;
        month_year[1] = document.querySelector('.year').textContent;
        transactions_ajax(month_year[0], month_year[1]);
    }
</script>
{% endblock %}

视图中的ajax函数:

def check_transactions(request):
    month = request.GET.get('month')
    year = int(request.GET.get('year'))
    month = int(month_name_to_number(month))
    month_range = calendar.monthrange(year, month)
    month_end = str(year)+'-'+str(month)+'-'+str(month_range[1])
    month_start = str(year)+'-'+str(month)+'-01'
    income = sum(Transaction.objects.filter((Q(user=request.user) | Q(user=None)) &
                                            Q(category__expense_or_income_choices='INCOME', date__lte=month_end,
                                              date__gte=month_start)).values_list('amount', flat=True))
    expense = sum(Transaction.objects.filter((Q(user=request.user) | Q(user=None)) &
                                             Q(category__expense_or_income_choices='EXPENSE', date__lte=month_end,
                                               date__gte=month_start)).values_list('amount', flat=True))
    income_transactions = list(Transaction.objects.filter((Q(user=request.user) | Q(user=None)) &
                                                Q(category__expense_or_income_choices='INCOME', date__lte=month_end,
                                                  date__gte=month_start)).values_list('pk', 'amount', 'category__name', 'date').order_by('-date'))

    expense_transactions = list(Transaction.objects.filter((Q(user=request.user) | Q(user=None)) &
                                                Q(category__expense_or_income_choices='EXPENSE', date__lte=month_end,
                                                  date__gte=month_start)).values_list('pk', 'amount', 'category__name', 'date').order_by('-date'))
    data = {
        'balance': income - expense,
        'income': income,
        'expense': expense,
        'income_transactions': income_transactions,
        'expense_transactions': expense_transactions
    }
    return JsonResponse(data)

但是我不断收到错误消息:

  

无法解析其余部分:'$ {data ['income_transactions'] [i] [0]}'   来自'$ {data ['income_transactions'] [i] [0]}'

问题在于在AJAX成功函数中设置'href'属性,当我想给用户一个选项来编辑事务,并且我需要将事务pk传递给url时,一切正常。 呈现模板时发生此错误,而不是在onclick事件期间发生。

有人知道这里有什么问题以及如何解决吗?对于这种情况,也许我的方法是完全错误的?

0 个答案:

没有答案