Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the simplest way to define default groups and permissions?

The goal

Being able to automatically create few groups with predefined permissions (including permissions created automatically by django.contrib.auth.signals).

My Struggle

Apparently there are two ways to do this:

  1. fixtures
  2. signals

The problems with going with the first option are:

  • You can't possibly know, before hand (except maybe by running the script once and noting the IDs on paper), what are the IDs of the predefined permissions (add_, delete_, change_). -
  • If you decide to create your own permissions you also don't know how to populate the "pk" field in the fixture, giving that some permissions have already been created.

The problem with going with the second option is:

  • Apparently your signals are run before any other signals, including django.contrib.auth.signals, therefore you are not able to call its predefined permissions and add them to your groups.

Not only that, but with a simple:

def create_initial_groups(**kwargs):
    staff_group     = Group(name = 'Staff')
    clients_group   = Group(name = 'Clients')

    staff_group.save()
    clients_group.save()

and:

signals.post_syncdb.connect(
    create_initial_groups,
    dispatch_uid = 'unique_app_identifier.listeners.create_initial_groups'
)

I get an:

django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_group_name_key" DETAIL: Key (name)=(Staff) already exists.

Even with a clean database (running drop schema public cascade; create schema public; on psql before python manage.py syncdb).

Question

So, what's the cleanest way, if any exists, to prepopulate the database with few groups and permissions?

like image 731
Shoe Avatar asked Jan 25 '26 04:01

Shoe


1 Answers

If you can associate those custom permissions with your models, try defining them under the permissions attribute inside model's Meta class.

Create fixtures for your custom groups, but use natural keys when serializing them, so that they refer to related permissions by their name rather than pk.

like image 168
knaperek Avatar answered Jan 27 '26 17:01

knaperek