Lutaaya Huzaifah Idris
Lutaaya Huzaifah Idris

Reputation: 4020

Send a queryset from Django views to JQuery

I want to send a JsonResponse of a queryset from Django views to JQuery but I am not getting any data from the JQuery side.

This is my views file add_field_views.py :

from django.http import JsonResponse

def drop_down_requests(request):
    text = request.POST['text']
    print("---->", text)
    from captiq.financing_settings.models import ChoiceGroup
    response = ChoiceGroup.objects.get(slug="Ja/Nein")
    output = JsonResponse(response,safe=False)
    print("output -", output)
    return output

this is where I declared the URL in urls.py inorder for the Jquery to GET the data from the views :

urlpatterns = [
   
    path('my-ajax-test/', add_field_views.drop_down_requests, name='ajax-test-view'),
]

project urls.py:

frontend_urls = []
for module_name, module_data in FRONTEND_MODULES.items():
    frontend_urls.append(re_path(
        module_data['url'],
        XFrameSameOriginView.as_view(template_name=module_data['view']),
        name=module_name))

urlpatterns = i18n_patterns(
    path('admin/', admin_site.urls),
    path('admin/log_viewer/', include(
        ('log_viewer.urls', 'log-viewer'), namespace='log-viewer')),
    path('admin/docs/', include('docs.urls')),
    path('_nested_admin/', include('nested_admin.urls')),
    path('accounts/', include(
        ('accounts.urls', 'accounts'), namespace='accounts')),
    path('api-auth/',
         include('rest_framework.urls', namespace='rest_framework')),

)

api_v1_patterns = [
    path('financing/', include(
        ('financing.urls', 'financing'), namespace='financing')),
    path('financing-settings/', include(
        ('financing_settings.urls', 'financing_settings'),
        namespace='financing_settings')),
    path('partners/', include(
        ('partners.urls', 'partners'), namespace='partners')),
    path('accounts/', include(
        ('accounts.urls', 'accounts'), namespace='accounts')),
    path('customers/', include(
        ('customers.urls', 'customers'), namespace='customers')),
]

urlpatterns += [
    path('api/v1/', include((api_v1_patterns, 'api'), namespace='api')),
    path('', RedirectView.as_view(url='loan-application/auth')),
    path('notifications/', include(
        'notifications.urls', namespace='notifications')),
] + frontend_urls

if settings.ENABLE_ROSETTA:
    urlpatterns += i18n_patterns(
        path('admin/rosetta/', include('rosetta.urls')),
    )

if settings.DEBUG:
    urlpatterns += static(
        settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

then is my JQuery which is waiting for the queryset data or JSON data :

window.addEventListener('load', function () {
    (function ($) {
        "use strict";
        $(document).ready(function () {

            $("#id_depending_field").change(function (event) {
                console.log("am here man");
                const valueSelected = this.value;
                $.ajax({
                    type: "POST",
                    url: 'my-ajax-test/',
                    data: {
                        csrfmiddlewaretoken:
                        document.getElementsByName('csrfmiddlewaretoken')[0].value,
                        text: valueSelected
                    },
                    success: function callback(response) {
                        console.log("____________", response)
                    }
                });
            })

        });
    })(django.jQuery);
});

With the code above am not able to get JSON data in JQuery, Instead I get a weird HTML output below :

<link rel="stylesheet" type="text/css" href="/static/css/notifications.css">

.
                
            

What am I doing wrong here ?

Upvotes: 0

Views: 188

Answers (2)

Andrey Maslov
Andrey Maslov

Reputation: 1466

when you use relative path it is easy to lead your urls to wrong place. at your page your ajax will call for /en/admin/financing_settings/field/add/my-ajax-test/.

you can save exact url on your html page with data-* attribute. In your example add data-ajax_url attribute to your #id_depending_field (or any other element)

data-ajax_url="{% url "api:financing_settings:ajax-test-view" %}" - url must be like this as i understand your routing

and then in your ajax code instead of url: 'my-ajax-test/', use url: $(#id_depending_field).data('ajax_url')

this will always give you exact url from any page where you load your .js file. And later if you decide to refactor your project and change url path it will keep all changes for you without changing html or js code

Upvotes: 1

GProst
GProst

Reputation: 10237

Use absolute URL when sending AJAX request:

$.ajax({
  type: "POST",
  url: '/my-ajax-test/',
  data: {
  ...
})

Apparently, you were sending it to /en/admin/financing_settings/field/add/my-ajax-test/ cause it was relative

Upvotes: 0

Related Questions