bash-
bash-

Reputation: 6304

Should I use Django permissions checks in the template AND the view?

Is it advised or redundant to set permissions on the template AND the view?

Consider that any data manipulation to the DB is done through POST

if the following enough for permissions?

{% if perms.system.view_employee %}
     <!-- content here -->
{% else %}
     <h1>Sorry you do not have permission to access this page<h2>
{% endif %}

or should I also implement server side checking as well (is it redundant to do so or necessary)?

def my_view(request):
    if not request.user.has_perm('polls.can_vote'):
        return HttpResponse("You can't access this page")
    else:
        # do stuff
        ...

Upvotes: 0

Views: 200

Answers (1)

Bite code
Bite code

Reputation: 596623

  1. Checks in the template are server side.
  2. Permissions checks in the template and in the view do not have the same purpose:

    • Checking permissions on the view will disallow the access to the entire page. You do this when this page, and the featured it embeds, is for APO. You handle ressources access.
    • Checking permissions in the template disallow parts of the template to be displayed. You do this when you want people to be able to access the page, but there are some stuff you don't want them to see on the page. You handle display.

In your particular example, you must set the permissions checks on the view to dissallow anybody to do this manipulation. Usually, if the views is accessed using POST their are little chances you want template permission checks because POST requests are actions by essence.

You usually will want template permissions checks if you:

  • have some parts of the page the person is not allowed to see (like sensitive data)
  • want to improve usability to show elements (menu, forms, etc) that are relevant only to its level of permission. Indeed it's useless to display a link to the admin in the menu if the person doesn't have the right to access the admin.

Upvotes: 6

Related Questions