Using the Django URL Tag in an AJAX Call

前端 未结 2 523
醉酒成梦
醉酒成梦 2021-01-02 12:37

There are LOTS of post and pages discussing the use of Django and AJAX, and I\'ve read hundreds over the past day or so looking for the answer to this question. A quick over

2条回答
  •  一整个雨季
    2021-01-02 13:28

    It is possible to set an Ajax url on the element you are selecting using an attribute and it will behave like Django urls. Importantly, you can even access the url in Javascript file. I use it a lot HTML

    Note: the data-url attribute set on parent div JAVASCRIPT

    $(document).ready(function () {
    
    var endpoint = $("#js-products").attr("data-url");
    var defaultData = [];
    var labels = []
    $.ajax({
        method: 'GET',
        url: endpoint,
        success: function (data) {
            labels = data.labels
            defaultData = data.data_default
            setChart()
    
    
        },
        error: function (error_data) {
            console.log(error_data)
        }
    })
    
    function setChart() {
        var ctx = document.getElementById('testChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            responsive: true,
            data: {
                labels: labels,
                datasets: [{
                    label: 'Monthly Performance',
                    data: defaultData,
    
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        });
     }
    });
    

    DJANGO VIEWS Am using django rest framework class view but you can use either of function or class based view class ChartData(APIView):

    authentication_classes = []
    permission_classes = []
    
    def get(self, request, format=None):
        labels = ['Products', 'User', 'May']
        data_default = [SeedProduct.objects.all().count(),
                        User.objects.all().count(), 4]
        data = {
            'labels': labels,
            'data_default': data_default,
        }
    
        return Response(data)
    

    DJANGO URLS: import the view class from views

    path('api/chart/data', views.ChartData.as_view(), name="chart-data"),
    

提交回复
热议问题