Jand
Jand

Reputation: 2727

How to define permissions in Django without staff status?

I'd like to give permissions to certain users to create articles, without assigning them staff status.

The reason is that I don't want any user to reach admin panel to authenticate, as happens when one adds @staff_member_required to a view. Instead I just want to add a /add/article link to the profile of users who have such permission.

How can I achieve that?

Upvotes: 2

Views: 384

Answers (1)

Serafeim
Serafeim

Reputation: 15084

If you are using traditional functional views, you could do something like this:

def add_article(request):
    if not request.user.has_perm('articles.add_article'):
        return HttpResponseForbidden()
    # Now only users that have the permission will reach this 
    # so add your normal view handling

However, I propose instead of the above, to use the django.contrib.auth.decorators.permission_required decorator:

@permission_required('articles.add_article')
def add_article(request):
    # your normal view handling

If you are using CBVs instead, you should either decorate the as_view() method of your CBV (in your urls.py) or use the PermissionRequiredMixin from django-braces (http://django-braces.readthedocs.org/en/latest/access.html#permissionrequiredmixin) - or just do your own checks in the dispatch() method of the CBV.

Also, in your template put your add_article url inside a perms check, like this:

{% if perms.articles.add_article %}
     Show url for article editing only to users that have the rpmission
{% endif %}

Upvotes: 2

Related Questions