如果查询匹配,则使用Django在Ajax调用后重定向

时间:2019-02-19 18:09:55

标签: python ajax django

我知道这段代码无法正常工作,因为请求在某种程度上是不够的,但是我不确定如何去纠正它。我正在尝试对其进行配置,以便如果ajax数据与用户名匹配,它将重定向到home.html。任何帮助将倍受珍惜! (PS:打印调用有效-如果用户存在,它会打印“ else”语句,反之亦然。尽管如此,重定向仍然不起作用!)

views.py

 def profile(request):
        profname = request.GET.get('profname', None)
        obj = User.objects.filter(username=profname)
        if not obj:
            print("I need this time to redirect to error page")

        else:
            print ("I need this to redirect home")
            return redirect('home')
        return render(request, 'profile.html')

html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
<h1>jkkk</h1>
     <a id="butt" href="#">Get Data</a>
 </body>
 <script>


$(document).ready(function(){
  $("#butt").click(function(){

           $.ajax({
           type: "get",
           url: 'profile',
           datatype:'json',
            data: {
            'profname': 'jillsmith',
            },

       }); 
  });
});
</script>

urls.py

urlpatterns = [
     path('', views.explore, name='explore'),
     path('happening/profile/', views.profile, name='profile'),
     path('happening/', views.happening, name='happening'),
     path('home/', views.home, name='home'),
     path('happening/test/', views.test, name='test'),
     path('home/likes/', views.likes, name='likes'),



]

1 个答案:

答案 0 :(得分:1)

只需在您的重定向调用前放置return语句,它就会返回HttpResponse对象,并且需要将其返回给调用方。

编辑:OP已更新并添加了收益,但是,这应该是一个很好的解决方案。请尝试传递URL和布尔值,指示是否应该重定向。 Django AJAX Redirect