milandjukic88
milandjukic88

Reputation: 1115

Django wont redirect me on another view from view

I will try to describe problem: In HTML i have some AJAX call to, lets say, URL getMetaData (this is function in views.py). I that function I check POST dictionary to check is all values there. If not i want to redirect to main page ("main.html"). This main.html is rendered in function main(request) in same views.py file. When i do this:

def main(request):
    return render(request,'main.html')

def getMetaData(request):
    if dictionary not valid:
        return main(request)

This not working... main function is called but page stays the same.

Upvotes: 1

Views: 109

Answers (2)

RemcoGerlich
RemcoGerlich

Reputation: 31250

The problem is that you do this with an AJAX call. Your Python code should work (at least, with this little example I don't see why it wouldn't), but the HTML of your home page will be the data returned to your AJAX call. There is no reason why your browser would then show it as the current page.

If you want to do something different depending on the result of the AJAX call, you should do it in Javascript. Can you show us that?

Upvotes: 0

aquavitae
aquavitae

Reputation: 19114

A redirect in an ajax call will not necessary change the page, and in any case it's not a good idea to mix POST and GET like that. I suggest that you handle it all in the ajax call and redirect there instead, so your django view would be something like:

def getMetaData(request):
    if is_invalid(request.POST):
        return redirect_url
    else:
        return None

And the jquery:

$.post(post_url, data, function(new_url) {
    if (new_url== null)
        do_stuff();
    else
        window.location.replace(new_url);
});

Upvotes: 1

Related Questions