Django: Tweaking @login_required decorator

后端 未结 4 1312
长情又很酷
长情又很酷 2020-12-24 15:17

I want to begin a private Beta for my website. I have a splash page where a user can enter a code to then access the rest of the site. Currently, all the other site pages (

4条回答
  •  鱼传尺愫
    2020-12-24 15:25

    HOW to re-use (tweak) internal Django login_required

    For example, you need to allow access to page for only users who passed login_required checks and also are Coaches - and (save) pass coach instance to you view for further processing

    decorators.py

    from django.contrib.auth.decorators import login_required
    from django.core.urlresolvers import reverse
    from django.http import HttpResponseRedirect
    
    from profiles.models import CoachProfile
    
    
    def coach_required(function):
        def wrapper(request, *args, **kwargs):
            decorated_view_func = login_required(request)
            if not decorated_view_func.user.is_authenticated():
                return decorated_view_func(request)  # return redirect to signin
    
            coach = CoachProfile.get_by_email(request.user.email)
            if not coach:  # if not coach redirect to home page
                return HttpResponseRedirect(reverse('home', args=(), kwargs={}))
            else:
                return function(request, *args, coach=coach, **kwargs)
    
        wrapper.__doc__ = function.__doc__
        wrapper.__name__ = function.__name__
        return wrapper
    

    views.py

    @coach_required
    def view_master_schedule(request, coach):
        """coach param is passed from decorator"""
        context = {'schedule': coach.schedule()}
        return render(request, 'template.html', context)
    

提交回复
热议问题