Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7655215
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T12:27:19+00:00 2026-05-31T12:27:19+00:00

Consider this Django view which will get a list of items associated to the

  • 0

Consider this Django view which will get a list of items associated to the current user:

@login_required
def list_items(request, page_number=0):
    items = Paginator(request.user.items, 5).page(page_number).object_list
    return HttpResponse(cjson.encode(items))

Obviously, it wants to use the login_required decorator, to restrict access to the view for logged-in users.

What does login_required do when a non-authenticated user tries to access the view? It returns a HttpResponseRedirect toward settings.LOGIN_URL.

Consider this JavaScript code, which calls the view:

var getPage = function(pageNumber) {
    $.ajax({
        url: "/list_items/" + pageNumber + "/",
        success: function(data) {
            $("#list_container").html(formatData(data))
        }
    });
};

Suppose settings.SESSION_COOKIE_AGE = 60 seconds.

If a user goes to page 1, reads it for 61 seconds, then clicks on the button for page 2, Django’s login_required decorator will detect that the session is no longer active, and will return a HttpResponseRedirect(settings.LOGIN_URL), which will cause the success callback to get a HTML login page instead of the JSON-encoded list.

This is where it happens.
It’s called by user_passes_test here.

What’s the best way to handle this?

Here’s a few things I’ve thought of:

1. The success callback should check the response, and see if it gets a login page, by whatever means (check if content-type is html, check contents, etc). But this means that we have to wrap all AJAX calls with a callback wrapper like so:

    $.ajax({
        url: "/list_items/" + pageNumber + "/",
        success: sessionExpiryCallbackWrapper(function(data) {
            $("#list_container").html(formatData(data))
        })
    });

But this is ugly, and developers might forget to do this everywhere.

2. Use $.ajaxComplete to handle all requests.

    $.ajaxComplete(globalCompleteCallback);
    $.ajax({
        success: successCallback,
        complete: completeCallback
    });

But this is the call order:

    successCallback(); // success is called before complete
    completeCallback();
    globalCompleteCallback(); // this is called after the local callback

So we only catch the redirect, after successCallback has failed, and possibly with JS errors due to the invalid data it received.

3. If login_required would return 403 on AJAX requests:

    if not user.is_authenticated():
        if request.is_ajax():
            # send 403 to ajax calls
            return HttpResponse403("you are not logged in")
        else:
            # regular code path
            return HttpResponseRedirect(settings.LOGIN_URL)

But login_required just uses user_passes_test which doesn’t do this.

user_passes_test has a lot of functionality in there, so it’s not such a good idea to reimplement it.

What’s the best way to handle the timeouts for AJAX calls?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T12:27:21+00:00Added an answer on May 31, 2026 at 12:27 pm

    I would handle it by having your session timeout method check whether or not it is being requested with AJAX. If it is ajax, return a 401 not authorized(or 403 forbidden or whatever status makes sense) status code with an empty json string. Next, in your javascript, bind a global ajaxError handler that checks for that status code and handles it appropriately.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider the following Django models: class Host(models.Model): # This is the hostname only name
Consider this problem: I have a program which should fetch (let's say) 100 records
Consider this Python program which uses PyGtk and Hippo Canvas to display a clickable
consider this code block public void ManageInstalledComponentsUpdate() { IUpdateView view = new UpdaterForm(); BackgroundWorker
In my django app's index.html (which I consider as the home page of the
Consider this simplified model in Django: class Item(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField()
Consider this part of a repository of mine: / myproject django -> django/master (django/django
I want to do contextal form validation in django. Consider this case: PLACE_TYPES =
Consider this url: www.anysite.com/get_count/?sex=5&sex=6&city=5&city=7&job=7&job=8...... For using in dynamic query in view: model = anyModel.objects.filter(sex=5).filter(sex=6).filter(city=5)....
Consider this code... using System.Threading; //... Timer someWork = new Timer( delegate(object state) {

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.