简体   繁体   中英

login_required decorator in Django: open modal instead of redirecting to another page

I have a django app which has certain sections which are reserved for registered users. I have the views annotated with login_required decorator which redirects the user to a login page.

However, I would like to keep the user on the same page and open up a modal dialog prompting user to sign in(like on the website: http://www.fashiolista.com/ ). To achieve this, I thought I could setup a middleware(instead of using login_required) and return a response like below:

   return HttpResponse("<script>"
       "showLogin()"
       "</script>")

When I try to do this, I realised that this renders a page with only the script tag, which obviously doesnt work.

I am using Bootstrap for showing modal dialogs.

Middleware link: http://onecreativeblog.com/post/59051248/django-login-required-middleware

Any ideas?

Instead it should be an ajax call to happen in real time, and add the modal to your base.html.

Django View:

def login_required_ajax_view(request):
    if request.is_ajax():
        if request.user.is_authenticated():
            return JsonResponse(data={'logged_in', True})
        return JsonResponse(data={'logged_in', False})
    return HttpResponse("not ajax")  # Add something if the call isn't ajax

Then in your javascript

// Javascript / Jquery
function login_required() {
    $.ajax({
       url: 'url goes here',
       data: data
       success: success  //on success call a function checking logged_in is 
                                   //true or false then open modal to log in.
    })
}

If it returns true allow them to click the button and move on to the next page.

On a side note:

If you're routing all of your urls through django and not javascript, then the modal will not appear if they go directly to a url in the browser. If this is a one page app then there is alot more to be done to get any of this to work. You need javascript libraries, a router, etc,

Just accomplish this in your template

<html>
    ...
    {% if user.is_authenticated %}

    <div class="reserved-section">...</div>

    {% else %}

    <script> modal(); </script>

    {% endif %}

Alternatively, render different templates via your view

def some_page(request):
    if request.user.is_authenticated():
        return render(request, "template_a.html")
    else:
        return render(request, "template_b.html")

Update

Use javascript logic in your template if you need to make an action

<script>
    function actionOnClick() {
        var logged_in = {% if user.is_authenticated %}true{% else %}false{% end %};
        if(logged_in){
            ..
        }
        ..
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM