1

I grasp that this code isn't working because the request is somehow insufficient, but I'm uncertain as to how to go about correcting it. I'm trying to configure it so that, if the ajax data matches the username, it will redirect to home.html. Any help would be so greatly cherished! (PS: the print calls are working - if the user exists, it prints the "else" statement and vice versa. Nevertheless, the redirect still doesn't work!)

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'),



]
Jay
  • 1,289
  • 3
  • 11
  • 22
  • You're not going to get a redirect in the front-end by returning a redirect response from the Ajax request. That's simply not how Ajax works. Also you're not doing anything with the response, whatever it is, since you have no `success` callback. – Robin Zigmond Feb 19 '19 at 18:18
  • How would I go about rectifying this? – Jay Feb 19 '19 at 18:24
  • Since it appears you want a redirect in both cases, I don't see how Ajax is the right tool. It looks like you can achieve the desired effect without any Javascript, just make your button into a link to the url you're using now, that will then check the database and do the appropriate server side redirect – Robin Zigmond Feb 19 '19 at 18:28
  • Yes, but in the final project I am going to send the text of the button to the back end, seeing if the user exists, and then redirect to a page with that user's particular info. – Jay Feb 19 '19 at 18:31
  • Then you either need a parameter in the URL, or to send the data in a form – Robin Zigmond Feb 19 '19 at 18:44
  • Or try one of the solutions in the question @TheodoreHowell links to in his edit. Looks like your question is actually a duplicate of that – Robin Zigmond Feb 19 '19 at 18:48
  • Possible duplicate of [Redirecting after AJAX post in Django](https://stackoverflow.com/questions/29137910/redirecting-after-ajax-post-in-django) – Robin Zigmond Feb 19 '19 at 18:50
  • I can redirect via window.location in javascript, but how would I go about passing the info --- in this case, 'jillsmith' -- to the page I redirect to? – Jay Feb 19 '19 at 19:20
  • The same way you always pass information to a view in Django - with parameters in the URL. – Robin Zigmond Feb 19 '19 at 19:25
  • Jeez, I get that. How do I do it using the solution you just recommended --- $.ajax({ type: "get", url: 'profile', datatype:'json', data: { 'profname': 'jilsmith', }, success: function(data) { if(data.status == 0){ alert("error page"); window.location = data.url } – Jay Feb 19 '19 at 19:29
  • I didn't actually recommend a particular solution - I wouldn't do that because I'm still unaware of exactly what you're trying to do. But if you're doing it that way, you can just put the logic in the backend to ensure the `data.url` is correct. – Robin Zigmond Feb 19 '19 at 19:33
  • the link I am clicking has the word 'jillsmith' in it. I want to send 'jillsmith' to back end, check if 'jillsmith' is a user, and then redirect to a page with her info if she is in fact a user. I've done this using the answer you provided, window.location via javascript. However, in this case I don't know how to call the link with a parameter. – Jay Feb 19 '19 at 19:37
  • I didn't provide an answer, I just linked to a previous question that was very similar, whose existence I was only alerted to by another poster. I think there are a few different solutions suggested there, this is only one (and my preference would be to just use a link and do it all via the backend, as I did suggest earlier). Anyway, I'm not sure how familiar you are with Django but see here for how to use URL parameters: https://docs.djangoproject.com/en/2.1/topics/http/urls/#example – Robin Zigmond Feb 19 '19 at 19:45

1 Answers1

1

Simply put a return statement in front of your call to redirect, it returns an HttpResponse Object and that needs returned to the caller.

EDIT: OP updated and added return, however this should be a good fix. Please try to pass URL and Boolean indicating whether you should redirect or not. Django AJAX Redirect

Theodore Howell
  • 419
  • 3
  • 12
  • And if you are using a app_name in url conf dont forget to use 'app_name:home' – Theodore Howell Feb 19 '19 at 18:12
  • That was a typo in the code I posted. The issue is that it still doesn't redirect, yet it prints. – Jay Feb 19 '19 at 18:14
  • Can you try to use reverse_lazy()? use this from django.urls import reverse_lazy – Theodore Howell Feb 19 '19 at 18:15
  • and just replace that for redirect, I cannot see all of your code and sometimes this can be an issue depending on where your statements are placed – Theodore Howell Feb 19 '19 at 18:16
  • 1
    After re-reading it, you also might want to take care of the redirect from the JS, pass data with the url to redirect to and a boolean indicating if you should redirect, and use JS to redirect once that AJAX returns. I think that might be the real issue – Theodore Howell Feb 19 '19 at 18:18
  • No. I get this error. response = get_response(request) File "C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\deprecation.py", line 93, in __call__ response = self.process_response(request, response) File "C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: '__proxy__' object has no attribute 'get' – Jay Feb 19 '19 at 18:18
  • 1
    Hey man, one more question if you don't mind ... How would I go about sending the 'profname' variable to the page I redirect to? I need this info to pull from the backend files in regards to what will load on the page. – Jay Feb 19 '19 at 19:13
  • @Jay if you are using Django >= 1.2 please look into django messages. You can pass context via the backend to redirected pages just like you are trying to do. Its in the docs and super easy to use. If you need helping finding more let me know! – Theodore Howell Feb 19 '19 at 20:47
  • I am trying to pass from the frontend to redirected pages, not the backend. – Jay Feb 19 '19 at 20:50
  • If you are wanting to take data from that ajax response, that you are using to redirect, you can pass the data in the redirect call as a POST method to that page, or you can use messages to do the same thing. Messages will do what you need and bring the data from frontend, to backend, to frontend. – Theodore Howell Feb 19 '19 at 21:21