Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django fixtures for permissions

I'm creating fixtures for permissions in Django. I'm able to get them loaded the way it's needed. However, my question is..say I want to load a fixture for the table auth_group_permissions, I need to specify a group_id and a permission_id, unfortunately fixtures aren't the best way to handle this. Is there an easier way to do this programmatically? So that I can get the id for particular values and have them filled in? How is this normally done?

like image 718
KVISH Avatar asked Jul 04 '12 19:07

KVISH


2 Answers

As of at least Django >=1.7, it is now possible to store permissions in fixtures due to the introduction of "natural keys" as a serialization option.

You can read more about natural keys in the Django serialization documentation

The documentation explicitly mentions the use case for natural keys being when..

...objects are automatically created by Django during the database synchronization process, the primary key of a given relationship isn’t easy to predict; it will depend on how and when migrate was executed. This is true for all models which automatically generate objects, notably including Permission, Group, and User.

So for your specific question, regarding auth_group_permissions, you would dump your fixture using the following syntax:

python manage.py dumpdata auth --natural-foreign --natural-primary -e auth.Permission

The auth_permissions table must be explicitly excluded with the -e flag as that table is populated by the migrate command and will already have data prior to loading fixtures.

This fixture would then be loaded in the same way as any other fixtures

like image 92
jonpa Avatar answered Oct 18 '22 02:10

jonpa


The proper solution is to create the permissions in the same manner the framework itself does.

You should connect to the built-in post_migrate signal either in the module management.py or management/__init__.py and create the permissions there. The documentation does say that any work performed in response to the post_migrate signal should not perform any database schema alterations, but you should also note that the framework itself creates the permissions in response to this signal.

So I'd suggest that you take a look at the management module of the django.contrib.auth application to see how it's supposed to be done.

like image 9
Filip Dupanović Avatar answered Oct 18 '22 04:10

Filip Dupanović