1

When using {% url 'query' %} inside an AJAX get call is returning a string but when I put a static url it works properly.

I'm using Django-Filters and Django-rest-framework in installed apps.

url.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^query/$', 'my_app.views.app_function', name='query')
]

app.js

$(document).ready(function(){

// LOAD COOKIE
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');


function callServer () {
    $.ajax({
        type: 'GET',
        url: "{% url 'query' %}",
        success: function (json) {
            console.log(json)

        },
        error: function(x, t, m) {
            if(t==="timeout") {
                alert("got timeout");
            } else {
                alert(t);
            }
        },
        headers: {
            'X-CSRFToken': csrftoken
        }
    });
}

$("#query").click(function () {
    $('#sub').submit(function (e) {
        e.preventDefault();
    });
    return callServer();
});



});

views.py

class AppFilter(django_filters.FilterSet):
    class Meta:
        model = Post
        fields = ['first', 'second']


@api_view(['GET'])
def app_function(request):
    qs = Post.objects.all()
    f = AppFilter(request.GET, queryset=qs)
    serializer = PostSerializer(f, many=True)
    return Response(serializer.data)

forms.py

class QueryForm(forms.Form):
    first = forms.TypedChoiceField(
        widget=forms.Select, 
        choices=choice_dict1
    )
    second = forms.TypedChoiceField(
        widget=forms.Select, 
        choices=choice_dict2
    )

Any help before I burn the place?

0

2 Answers 2

2

Django would not be able to resolve {% url 'query' %} in JS file, since that's client side stuff. reverse url is resolved at the time of html file rendering.

What you can do is, pass that url as init() function of that JS module from html file:

<!-- In your Template file -->
<script>
$(function(){
    app.init("{% url 'query' %}");
});
</script>

And export the app module from js file. Set that url as a variable, and use it in ajax call.

Sign up to request clarification or add additional context in comments.

4 Comments

could add that bit of JS to the template file as well
Dang it...you typed faster than me :-)
@dietbacon That script tag will go in the template file only.
What does "export the app module from js file." mean? How do you export a Javascript file named app.js to a Django template?
1

The problem is that your javascript file (app.js) is probably not the template. You don't show it, but I assume you have an HTML file that is loading the app.js file. The HTML file is where the template variables and such will get expanded. The simplest way to resolve this is to embed the javascript code into your HTML file inside a <script> tag.

There is a library for Flask called Flask-JSGlue that solves this problem and lets you use template variables in your javascript files, but I cannot find a similar library for Django.

1 Comment

Thank you both guys, for your answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.