Django message framework and login_required

前端 未结 5 1078
不知归路
不知归路 2021-02-02 10:34

I\'m using the Django Message Framework to show messages to users as well as the @login_required decorator on one of my views. So if a user tries to access a certai

5条回答
  •  天命终不由人
    2021-02-02 11:40

    This is an old question but I still have it 10 years later. Here is the solution I came up with. It's kind of hacky but it's only 7 lines of code including the decorator. You use 2 functions.

    The first is mapped to the URL path. It checks to see if the user is logged in. If the user is not logged in, it sets a message. Regardless of the user's login state, it returns with a call to the second function.

    The second function does what the standard view would have done but it has the decorator on it.

    def content(request):
        if request.user.is_anonymous:
            messages.warning(request, 'You must log in to view the course content.')
        return content2(request)
    
    @login_required
    def content2(request):
        return render(request, 'path/template.html')
    

    I am assuming that your log in template already displays messages.

    Like I said, it's a bit of a hack but it works really well.

    I am using Django version 3.0.6

提交回复
热议问题