Search code examples
djangoviewlimitextend

Limit a view in Django


I have a problem in my Django project. I extend the Django user with a new 1-to-1 relationship in a named WebUser model. I have normal users and users with this new relationship. How can I limit the same views to only show them to the users, so they have the relation with Webusers?


Solution

  • Without knowing a specific Django solution I can help you with a Python solution. If you use decorators you can limit the access to the webuser view:

    # Decorator for limit access when user dont have relation with WebUser
    def webuser_required(f):
        def trace(*args, **kw):
            try:
                login = isinstance(request.user.webuser, WebUser)
                return f(*args, **kw)
            except:
                return ....
        return trace
    

    You can use it:

    @webuser_required
    def yourview(....):
        yourcode