Search code examples
pythondjangodjango-1.7django-permissions

Django - Create "hard-coded" groups and permissions


I need to define some permissions and groups that are used in the models and the views. I know how to do it with permissions (define them in the "Meta" of some models), but it is not clear to me how to do it with groups. Maybe the right thing to do is not to use the groups provided in Django's Auth, but to create some new models to handle these "constant" groups.

I also tried to create these groups as "initial data" (https://docs.djangoproject.com/en/1.7/howto/initial-data/), but this solution does not seem very clean to me.


Solution

  • There is no way of creating hard coded groups within code (without modifying Django source) as the groups are stored witin auth.group table within your database. Possible methods of getting your groups into this table would be:

    1. Initial data, as you have already done (recommended as thats what it is designed for)
    2. Create a data migration that contains the groups
    3. Add it in code which is abit nasty

      from django.contrib.auth.models import Group
      p, created = Group.objects.get_or_create(name = 'Administrators')