简体   繁体   中英

How to add user group in django?

I can't find a clear instruction about adding my own group in django. I can do that in the admin page. But that doesn't seems right.

I googled it and someone said put this

from django.contrib.auth.models import Group, Permission

different_users = Group(name='Different Users')
different_users.save()
outstanding_users = Group(name='Outstanding Users')
outstanding_users.save()

int to __init__.py

That doesn't work for me. Here is the error I got.

django.db.utils.IntegrityError: (1062, "Duplicate entry 'Different Users' for key 'name'")

Anyone know the correct way to create different groups in django?? I can't find any in django documentation.

It's perfectly fine to add groups using the admin interface - in fact that's what the admin interface is for.

Putting that code in __init__.py makes absolutely no sense. That file is run every time it's module is imported (or the first time in each request, don't know the exact mechanics). So then you would try to create the same group during each separate request.

However, that code can be used in a python shell - just execute it once and the groups are created in the database. Just invoke a Django-specific Python shell using manage.py shell , and start typing. However, it might be easier to add the right permissions through the admin interface. If you don't care about permissions and just want users grouped together, this way is just as fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM