Páginas

quinta-feira, agosto 29, 2013

Creating Django permissions using South Datamigrations.

After a long time away I'm back to post (for my own information and for everybody who needs it) how to create django permissions using South datamigrations. For understanding what is Django, South and Python, follow the links in the end of this post.

First step, create a Data Migration:
python manage.py datamigration app_name name_describing_your_permission_creation

This command will generate a file like XXXX_name_describing_your_permission_creation.py. Open and edit this file. It will have a "fowards" method. Change it to be like this:

     def forwards(self, orm):
        ct = orm['contenttypes.ContentType'].objects.get(
            model='model_name', app_label='app_label')
        orm['auth.permission'].objects.get_or_create(
            content_type=ct, codename='permission_codename',
            defaults=dict(name=u'Permission Label')
        )

After create this, run this command:
python manage.py migrate your_app_name

It will apply your data migration creating permissions. You can add the backwards for your datamigration deleting the permissions:

    def backwards(self, orm):
        ct = orm['contenttypes.ContentType'].objects.get(
            model='nome_do_model', app_label='label_da_app')
        orm['auth.permission'].objects.filter(
            content_type=ct, codename='permission_codename',
        ).delete()

I found it on this page on Stack Overflow:
http://stackoverflow.com/questions/1742021/adding-new-custom-permissions-in-django

More interesting links:
[1] http://south.aeracode.org/
[2] https://www.djangoproject.com/
[3] http://www.python.org.br/wiki
[4] https://docs.djangoproject.com/en/dev/ref/django-admin/#syncdb
[5] https://docs.djangoproject.com/en/dev/topics/auth/

Nenhum comentário: