How do I set a default group with django-authopenid? - python

I have a django app that uses django-authopenid as the sole registration method. I have registration in my installed apps, which django-authopenid uses. An ideal solution would allow me to run arbitrary code on the user object when they register. I can't directly modify the code for django-authopenis or registration.
Let me know if I need to add any more details.

On models.py you could bind the post_save signal:
from django.contrib.auth.models import User, Group
from django.db.models.signals import post_save
def default_group(sender, instance, created, **kwargs):
if created:
instance.groups.add(Group.objects.get(name='your default group name'))
post_save.connect(default_group, sender=User)
If in doubt, read the signals documentation.

Related

How to create multiple objects with django transactions?

I have to retrieve M objects from a list of Q objects and then maps the M objects to an User. To achieve this, I need to run the code inside a transaction and roll back the DB in the case 1 of M objects are not created:
def polls(request, template_name='polls/polls.html'):
question_list = random.sample(list(Question.objects.all()), 3)
try:
with transaction.atomic():
for question in question_list:
UserToQuestion.objects.create(
user=request.user.id,
question=question.id
)
except IntegrityError:
handle_exception()
How I can achieve this? How the exception should be handled? The django documentation doesn't show a real example.
Is also possible perform this task during the user registration overriding the save method in way each registered user is mapped to N questions?
You need to use django signals while doing user registration.
Also you do not need with transaction.atomic(): part. You need to use
bulk create
First of all, we create a signal, in order to map the related questions to an user when the user is registered. The signal is triggered from post_save() and the call-back function retrieve N random questions and map it to the user. The signal must be connected, to do it, we use the decorator #receiver. We also need to use a transaction, cause of bulk_create() method.
signals.py
import random
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.db import transaction
from django.db.models.signals import post_save
from polls.models import Question, UserToQuestion
#transaction.atomic
#receiver(post_save, sender=User)
def sig_user_registered(instance, **kwargs):
question_list = random.sample(list(Question.objects.all()), 3)
UserToQuestion.objects.bulk_create([
UserToQuestion(user=instance, question=question) for question in question_list
])
The signal must be imported. To do it, we use the method ready().
apps.py
from django.apps import AppConfig
class AccountConfig(AppConfig):
name = 'account'
def ready(self):
import account.signals
Finally, we load the application
settings.py
INSTALLED_APPS = [
# Django apps
# ...
# Third-party apps
# ...
# Your apps
'account.apps.AccountConfig',
# ...
]

Django Rest Framework Tokens Are Not Being Automatically Generated

I am (trying) to use Django Rest Framework's Token-based authentication. I have the following in my app's models.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
Whenever I create a new account (either through 'createsuperuser' or by using my registration form), the user is correctly added to the 'auth_user' table. However, although the 'authtoken_token' table is created, there is nothing added to it. This leads me to believe that my #reciever may not be working properly.
I can however manually create tokens using the Django shell. Those tokens will be properly added to the authtoken_token table.
Any help on this would be greatly appreciated,
Thanks
Things to check:
Is the receiver even running? Add a print or log inside to check that it is called in the first place
If AUTH_USER_MODEL is not defined, you may need to use get_user_model() instead
Make sure that this code is inside the models.py file of an app that is in settings.INSTALLED_APPS
I've used DRF for several years and never had this problem. One of the above is likely your culprit.

Custom user_logged_in signal BEFORE django updates last_login

I'd like to show a notification to user with some stats (e.g how many items have been sold since last time he logged in)
#receiver(user_logged_in)
def notify_user_on_login(sender, request, user, **kwargs):
items = Item.objects.filter(status=Item.HISTORY_STATUS, seller=user, when_trading__gte=user.last_login)
However, in this signal last_login has already been updated.
According to the source at django.contib.auth django also connects signal with function that updates last_login:
user_logged_in.connect(update_last_login)
Is it possible to call my function BEFORE updating? Or get same result without adding custom field or doing some strange magic?
The last_login is also updated with a handler to that signal, which is surely registered and executed before yours. You might be able to solve your issue by moving your app over django.contrib.auth in INSTALLED_APPS.
Signal handlers depending on order doesn't seem like a good idea though. So I would probably replace Django's handler with your own:
from django.contrib.auth.models import update_last_login
def notify_user_on_login(user):
items = Item.objects.filter(status=Item.HISTORY_STATUS, seller=user, when_trading__gte=user.last_login)
#receiver(user_logged_in)
def after_user_logged_in(sender, user, **kwargs):
notify_user_on_login(user)
update_last_login(sender, user, **kwargs)
user_logged_in.disconnect(update_last_login)

Send Custom Parameters to Django Signals

I am working on Django Signals to handle data in Redis whenever any change happens in the Postgres database. But, I am unable to send custom parameters to Signal Receiver. I have gone through a lot of questions, but I am not able to understand how to send extra custom parameters to Signal Receiver.
Usually I do,
#receiver(post_save, sender=post_data)
def addToRedis(sender, instance, **kwargs):
But I want to do,
#receiver(post_save, sender=post_data)
def addToRedis(sender, instance, extra_param=extra_param_data **kwargs):
# Get `extra_param`
Here, I want to read extra_param to store the data in Redis.
I am using Django Rest Framework. And post_save is directly called after serializer.save()
It'll be great if someone can help me out in this.
You can send any additional parameters in a signal as keyword arguments:
#receiver(post_save, sender=post_data)
def addToRedis(sender, instance, **kwargs):
# kwargs['extra_param']
How to send:
my_signal.send(sender=self.__class__, extra_param='...')
If you have no access to the signal send function (eg REST framework internals), you can always use a custom signal.
This Answer the with Respect to Django Rest:
in your views.py
my_obj = Mymodel()
my_obj.your_extra_param = "Param Value" # your_extra_param field (not Defined in Model)
my_obj.save()
post_save.connect(rcver_func,sender=Mymodel,weak=False)
and define a signal.py with following
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Mymodel
#receiver(post_save,sender=Mymodel)
def rcver_func(sender, instance, created,**kwargs):
if created:
received_param_value = instance.your_extra_param # same field as declared in views.py

Using Pre_delete Signal in django

In my app I want to keep a track of all the questions that are being deleted. And so I have created a class(table) as such in my models file.
class Deleted(models.Model):
question = models.IntegerField(null=True, blank=True)#id of question being deleted
user = models.IntegerField(null=True, blank=True)#id of user deleting the question
dt = models.DateTimeField(null=True, blank=True)#time question is deleted
When a user tries to delete a question This delete function is called:
def delete_questions(request, user, questions):
for q in questions:
q.delete()
My doubt is how can i make a pre_delete signal of django to populate the new table I have created.
~newbie trying hefty task~
Thanks in advance:)
You start off by defining the receiver you want to use:
def log_deleted_question(sender, instance, using, **kwargs):
d = Deleted()
d.question = instance.id
d.dt = datetime.datetime.now() # consider using auto_now=True in your Deleted definition
# not sure how you'd get the user via a signal,
# since it can happen from a number of places (like the command line)
d.save()
Then define your receiver decorator:
from django.db.models.signals import pre_delete
from django.dispatch import receiver
#receiver(pre_delete, sender=Question, dispatch_uid='question_delete_log')
Add it altogether:
from django.db.models.signals import pre_delete
from django.dispatch import receiver
#receiver(pre_delete, sender=Question, dispatch_uid='question_delete_signal')
def log_deleted_question(sender, instance, using, **kwargs):
d = Deleted()
d.question = instance.id
d.dt = datetime.datetime.now()
d.save()
You can put this function in your models.py file, as you know it'll be loaded and connected up correctly.
The problem though, is that you don't get the user requesting the delete. Since a delete can be triggered from the django api (command line, shell, etc), which doesn't have a request associated with it. For this reason, you might want to avoid using signals if it's absolutely critical that you store the user along with the delete.

Categories

Resources