Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Custom permissions in Django but without models

3,548 views
Skip to first unread message

Peter Bengtsson

unread,
Oct 25, 2013, 7:48:48 PM10/25/13
to dev-w...@lists.mozilla.org
In Socorro, we use Django but we don't use any models (other than things
like django.contrib.auth.models.User) but we want to have fine-grained
permissions.

For example::

{% if request.user.has_perm('can_view_url') %}
<a href="{{ crash.url }}">{{ crash.url }}</a>
{% endif %}


However, Django's permission system is highly tied to django content
types and that we don't have any.

What do you suggest? That I fake the content types?

Or that instead change to depend on groups. Something like::

{% if in_group(request.user, groups.URL_VIEWERS) %}
<a href="{{ crash.url }}">{{ crash.url }}</a>
{% endif %}


Peter

Josh Mize

unread,
Oct 25, 2013, 10:28:56 PM10/25/13
to pet...@mozilla.com, dev-w...@lists.mozilla.org
ContentType objects only have an indirect relation to models, so you can create
an arbitrary ContentType object in the db and use that for your custom Permission:


url_content_type = ContentType.objects.create(
name='url permission', app_label='crashstats', model='unused')

can_view_url = Permission.objects.create(
name='can view url', content_type=url_content_type,
codename='can_view_url')

user = User.objects.get(username='example_user', is_superuser=False)
user.user_permissions.add(can_view_url)
user = User.objects.get(id=user.id) # refresh permissions cache
assert user.has_perm('crashstats.can_view_url')


Hope that helps,
Josh
_______________________________________________
dev-webdev mailing list
dev-w...@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-webdev

Peter Bengtsson

unread,
Oct 26, 2013, 1:33:30 PM10/26/13
to Josh Mize, dev-w...@lists.mozilla.org, pet...@mozilla.com
model='ununsed'
Ha! You're a smart cookie.

Luke Crouch

unread,
Oct 27, 2013, 9:49:23 AM10/27/13
to Josh Mize, pet...@mozilla.com, dev-w...@lists.mozilla.org
post to djangosnippets.org? :)

-L

Josh Mize

unread,
Oct 27, 2013, 12:49:29 PM10/27/13
to Luke Crouch, dev-w...@lists.mozilla.org
Good suggestion, Luke. I was about to do just that, but it looks like
someone already posted an example that illustrates the same concept:

https://djangosnippets.org/snippets/334/
0 new messages