0

Let's say I have an app called Blog which contains Posts. I want a user to be able to add and change posts, but not delete them.

The Django docs have this example

from myapp.models import BlogPost
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.create(codename='can_publish',
                                       name='Can Publish Posts',
                                       content_type=content_type)

I don't see how it's actually defining anything here, it just gives it a name and content type.

Django also has basic permission checking

Assuming you have an application with an app_label foo and a model named Bar, to test for basic permissions you should use:

add: user.has_perm('foo.add_bar')
change: user.has_perm('foo.change_bar')
delete: user.has_perm('foo.delete_bar')

In my app they would become:

add: user.has_perm('blog.add_post')
change: user.has_perm('blog.change_post')
delete: user.has_perm('blog.delete_post')

How do I create and add such permissions to a user (in code, not the admin)?

user2787904
  • 517
  • 2
  • 7
  • 18
  • Why not create a Group with add and change permissions, but not delete. For every user that registers, it is assigned to that group. – Jason Nov 08 '13 at 16:52
  • I would but I still need to know how to create (or add them to the group, since it looks like they already exist) these permissions. – user2787904 Nov 08 '13 at 17:09
  • This is a little old but may help you: http://web.archive.org/web/20130205133031/http://parand.com/say/index.php/2010/02/19/django-using-the-permission-system/ – Jason Nov 08 '13 at 17:46

1 Answers1

0

Defining custom permissions in code can be done via a model's meta (see duplicate):

class BlogPost(models.Model):
    class Meta:
        permissions = (('can_publish', 'Can Publish Posts'),)

Per user permissions should not be added in code for the most part, but may however be added as part of a migration if using south or the built-in django migrations if your version is high enough.

python manage.py schemamigration $appname $migration_description --empty
class Migration(SchemaMigration):

    def forwards(self, orm):
        daemon = orm.User.objects.get(username='daemon')
        daemon.user_permissions.add($permission)
        daemon.save()

    def backwards(self, orm):
        daemon = orm.User.objects.get(username='daemon')
        daemon.user_permissions.remove($permission)
        daemon.save()
Community
  • 1
  • 1
Alex Riina
  • 801
  • 7
  • 11