Adding user to group on creation in Django

2024/10/8 0:32:24

I'm looking to add a User to a group only if a field of this User is specified as 'True' once the User is created. Every User that is created would have a 'UserProfile' associated with it. Would this be the correct way to implement such a thing?

models.py:

def add_group(sender, instance, created, **kwargs):if created:sender = UserProfileif sender.is_in_group:from django.contrib.auth.models import Groupg = Group.objects.get(name='Some Group')g.user_set.add(sender)post_save.connect(add_group, sender=UserProfile)

Thanks in advance!

Answer

Another option is using a post_save signal

from django.db.models.signals import post_save
from django.contrib.auth.models import User, Groupdef add_user_to_public_group(sender, instance, created, **kwargs):"""Post-create user signal that adds the user to everyone group."""try:if created:instance.groups.add(Group.objects.get(pk=settings.PUBLIC_GROUP_ID))except Group.DoesNotExist:passpost_save.connect(add_user_to_public_group, sender=User)

Only trouble you will have is if you use a fixture ... (hence the DoesNotExists .. )

https://en.xdnf.cn/q/70181.html

Related Q&A

imgradient matlab equivalent in Python

I am searching for an imgradient MATLAB equivalent in Python. I am aware of cv2.Sobel() and cv2.Laplacian() but it doesnt work as imgradient works in MATLAB. If I could get source code of imgradient.m…

Error: astype() got an unexpected keyword argument categories

df = pd.DataFrame([A+, A, A-, B+, B, B-, C+, C, C-, D+, D],index=[excellent, excellent, excellent, good, good, good, ok, ok, ok, poor, poor])df.rename(columns={0: Grades}, inplace=True)dfI am trying to…

python: regular expression search pattern for binary files (half a byte)

I am using the following regular expression pattern for searching 0xDEAD4FAD in a binary file:my_pattern = re.compile(b"\xDE\xAD\x4F\xAD")but how do I generalize the search pattern for search…

pandas: selecting rows in a specific time window

I have a dataset of samples covering multiple days, all with a timestamp. I want to select rows within a specific time window. E.g. all rows that were generated between 1pm and 3 pm every day.This is a…

How to visualize (dendrogram) a dictionary of hierarchical items?

This is my first time of doing visualization from hierarchical data in dictionary format with Python. Last part of the data looks like this:d = {^2820: [^391, ^1024], ^2821: [^759, w, ^118, ^51], ^2822…

How to unfocus (blur) Python-gi GTK+3 window on Linux

What I want to do and whyI want my window to unfocus, so the previous focused window is selected.Why? I want to interact with the previously selected window (from other programs). My current plan is: …

SyntaxError: multiple exception types must be parenthesized

I am a beginner and have a problem after installing pycaw for the audio control using python, on putting the basic initialization code for pycaw, i get the following error:- Traceback (most recent call…

Python find difference between file paths

I have a bunch of file paths, such as:path1 = "./base/folder1/subfolder" path2 = "./base/folder2/"I am trying to write a function that can give me the relative difference between th…

Update range of colorbar in matplotlib

I want to update a contourf plot within a function, which works fine. However, the range of the data changes and I therefore also have to update the colorbar. That is where I fail to do so.Please see f…

Anaconda - arrow keys not work well in python shell

I installed Anaconda3 on manjaro (with i3wm and Urxvt). When I go into python interpreter, it is OK to type python script and execute. But when key arrows are pressed to call up history, everything mes…