Django: Add multiple user to one group in admin interface - django

At the moment i'm settting up the permissions in my project and i assigned some permissions to one user group. Now i have to assign a large number of users to this group, so that they can us the permissions of the group.
Problem:
I have to click on every user in the admin interface, add them to the group and the same for the next ones. This takes a large amount of time. Is it possible to select anywhere all users that should belong to a group? That would be much faster...
If it's not possible with the standard admin interface, is there an app I can install and use for this (like "South" for database migration tasks)?

Use the django shell:
$ python manage.py shell
>>> from django.contrib.auth.models import User, Group
>>> the_group = Group.objects.get(name='the_name_in_admin')
>>> users = User.objects.exclude(groups__name='the_group_you_made_in_admin')
>>> for i in users:
... i.groups.add(the_group)
... i.save()
>>>
For more information on the api of the authentication system, have a read through the documentation

Related

Django groups, roles and permissions

I have a question: there's employee app in my project and I want employees to have different titles such as sales representative, manager and etc. and my views behave differently depending on employee's title. For now I have model Titles (title_code, title_name) but I feel like it could've been done with Django's builtin modules. So what do I use for building hierarchy? Groups, roles or permissions?
The django groups, role and permissions system is for allow or denay action in administration pannel, for this reason these three components work together.
If in your application all these type of user have access in admin pannel I suggestion you to use the Groups, roles and permission system
But If your users haven't the access to admin pannel you can avoid using it.
In first option you can create a different roles for every users and allow some permissions for each but if you have groups of users with same permission you can regroup they in a group. For more info view this https://docs.djangoproject.com/en/4.0/topics/auth/default/#permissions-and-authorization
If you do not need any specific privileges for each employee title, then choices would be pretty simple to implement like below
Sample Example
from django.db import models
class Employee(models.Model):
SALES_MANAGER = 1
HR_MANAGER = 2
ENGINEERING_MANAGER = 3
ROLE_CHOICES = (
(SALES_MANAGER, 'Sales Manager'),
(HR_MANAGER, 'HR Manager'),
(ENGINEERING_MANAGER, 'Manager'),
)
employee_title = models.CharField(max_length=100, choices=ROLE_CHOICES, default='Manager')
But do note that if you want to add new employee title's then a re-run of migrations would be required. If you need to avoid this then groups would be a better choice.
from django.db import models
from django.contrib.auth.models import Group
class Employee(models.Model):
employee_title = models.ManyToManyField(Group)
With groups, you would be able to create new entries without any migrations directly from admin panel.

How to create user groups for permissions within code (not in admin)

I'm wanting to create user groups for permissions and am wondering how to do this in the code as it sounds like the more proper way to do it (or not?).
I have done some searching and have found a few completely different pieces of code, but I am not even sure in which file this code should be located? Here is one example that I found:
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from api.models import Project
new_group, created = Group.objects.get_or_create(name='new_group')
# Code to add permission to group ???
ct = ContentType.objects.get_for_model(Project)
# Now what - Say I want to add 'Can add project' permission to new_group?
permission = Permission.objects.create(codename='can_add_project',
name='Can add project',
content_type=ct)
new_group.permissions.add(permission)
Thank you.

Django user roles

I m building a website in which I have 2 types of users.
For each type of user I have a corresponding django application.
I would like when I am logging into the website as type A user or type B user, to be redirected to the appropriate django app and not to be able to access the other application. For logging each user will have a corresponding form.
What is the best approach for this case ?
Try to use Django Groups Model, so you gonna create two groups: type A and type B; Each user will be in one of these groups. On your index view, check which group the user belongs to and redirect for whatever you want.
def index(request):
if request.user.groups.filter(name='type A').exists():
return redirect('/url_type_A/')
elif request.user.groups.filter(name='type B').exists():
return redirect('/url_type_B/')
Now you can create permission for each group for accessing a certain view or do some specific action. I recommend to create two apps(python manage.py startapp typeA and python manage.py startapp typeB ) so you can redirect for an entire interface dedicate for the type of user.

Whats the correct way to programmatically add permissions to a group

I want to add (already existing, defined via permissions in the meta tag) permissions to groups and looking for the correct place to do so. I have to assure that after the sync_db command all groups have the correct permissions assigned to.
I was thinking to hook up a post_syncdb signal, but the signal docs say:
It is important that handlers of this signal perform idempotent
changes (e.g. no database alterations) as this may cause the flush
management command to fail if it also ran during the syncdb command.
Thus it is probably not advisable that someone adds permissions to a group in a management command called via the sync_db_post signal.
I planned to setup the permissions like this:
class UserProfile(models.Model):
user = models.OneToOneField(User)
company = models.ForeignKey(Company, related_name='user_profiles')
department = models.ForeignKey(Department, related_name='user_profiles')
class Meta:
permissions = (
('admin_section_access', 'Access to front-end admin section'),
)
in the management command:
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand):
args = 'none'
help = 'Sets the defined group permissions'
def handle(self, *args, **options):
front_end_admin_group, created = Group.objects.get_or_create(name="Front End Admin")
#get the content type for the UserProfile model
user_profile_ct = ContentType.objects.get(app_label='organization', model='userprofile')
admin_section_access_perm = Permission.objects.get(content_type=user_profile_ct, codename="admin_section_access")
front_end_admin_group.permissions.add(admin_section_access_perm)
self.stdout.write('Successfully setup group permissions.')
You have two main options here. The first is to create a fixture for your database, as described here in the Django docs. That's the oldest way to seed data (for you, permissions xref records) into your database.
The second option, and my preferred over the first, is to use South to programmatically track and maintain changes to your database. While most commonly used for schema changes, its data migrations feature is the perfect place to handle what you want. You'd run this in your command line: ./manage.py datamigration my_app seed_permissions and then simply write the Django code required to get your permissions into place within the provided forwards function.
The main gotcha to the second option is that it requires you to run the additional command of migrate after sync_db, but this is probably unavoidable anyway as South is the truth (and slated to become core Django in 1.7).

User groups and permissions

I need to implement user rights for user groups (pretty similar to facebook groups). For example, each group can have members with rights like: can_post, can_delete, can_ban, etc. Of course, one user can be a member of many groups and group can have many different users with different rights.
What models I need for this functionality?
Django has a built in groups system. Whenever you have a question like this, I recommend searching the Django docs, which are extensive, helpful, and well written.
So long as you are using the django.contrib.auth app, you have access to groups. You can then assign permissions to those groups.
from django.contrib.auth.models import User, Group, Permission
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get(app_label='myapp', model='BlogPost')
permission = Permission.objects.create(codename='can_publish',
name='Can Publish Posts',
content_type=content_type)
user = User.objects.get(username='duke_nukem')
group = Group.objects.get(name='wizard')
group.permissions.add(permission)
user.groups.add(group)