Django view not rendering after Ajax redirect

こ雲淡風輕ζ 提交于 2019-12-29 09:12:14

问题


The main page of my website has multiple buttons at the top. Whenever one of these buttons is pushed, a get request is sent to a django view, which is redirected and a queryset of django models is filtered and eventually displayed on the web page. I know that my ajax works because the terminal says the request is redirected properly. The function it redirects to also seems to be working, as it is quite simple and has not thrown any errors. However, my view remains the same and I'm not sure why.

urls.py

url(r'ajax_filter/', views.ajax_filter, name='ajax_filter'),
url(r'filter=(\w+)/$', views.filtered_index, name='filtered_index'),

views.py

def filtered_index(request, filter):
    clothes = Clothes_Item.objects.filter(gender=filter)
    if request.user.is_authenticated():
        favorite_clothes_ids = get_favorite_clothes_ids(request)
        return render(request, 'test.html', {'clothes': clothes, 'favorite_clothes_ids': favorite_clothes_ids})
    else:
        return render(request, 'test.html', {'clothes': clothes, })

def ajax_filter(request):
    if request.is_ajax():
        gender_filter = request.GET.get('gender_filter') #filter type
        if gender_filter is not None:
            return HttpResponseRedirect(reverse('filtered_index', args=[gender_filter]))
    return HttpResponse('')

回答1:


You can not use Django redirect in your case. When you send an ajax request you usually expect a json response, and based on that you can redirect the user via your JavaScript code.

$.ajax({
  // You send your request here
}).done(function(data) {
  // You can handle your redirection here
});

Here is how you can handle a redirect with your setup, you pass back a JsonResponse from django with the next page that you want to go to:

from django.http import JsonResponse

def ajax_filter(request):
    if request.is_ajax():
        gender_filter = request.GET.get('gender_filter') #filter type
        if gender_filter is not None:
            return JsonResponse({
                'success': True,
                'url': reverse('filtered_index', args=[gender_filter]),
            })
    return JsonResponse({ 'success': False })

In JS, you use done (or success) function to grab the URL from the passed back JsonResponse and redirect to that URL using window.location.href:

$.ajax({
  // You send your request here
}).done(function (data) {
    if (data.success) {
        window.location.href = data.url;
    }    
});


来源:https://stackoverflow.com/questions/41273295/django-view-not-rendering-after-ajax-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!