Django signals duplicate with unique dispatch id - python

I have a problem with duplicate signals. I have looked-up the relevant part of Django docs and a similar question on Stackoverflow but I still can't get it working right - i.e. the action that I have planned (creation on an ActivityLog entry) is actually happening 4 times :/
I have added the dispatch_uid and the problem still persists, so I guess I'm doing something wrong. Can you please hint me to the error?
Here's my code:
signals.py
from patient.models import Patient
from .models import ActivityLog
#receiver(pre_save, sender=Patient)
def create_new_patient(sender, instance, **kwargs):
ActivityLog.objects.create(
user=instance.created_by_user,
event='created a new patient',
patient_id=instance.patient_id
)
and this is it's usage in the patient.apps module:
from django.apps import AppConfig
from django.db.models.signals import pre_save
app_name = "patient"
class PatientConfig(AppConfig):
name = 'patient'
verbose_name = "Patients"
def ready(self):
from activity_logger.signals import create_new_patient
print('Patient APP is ready!')
pre_save.connect(create_new_patient, sender='patient.Patient', dispatch_uid='patient')
The print Patient APP is ready! does appear twice, and the object gets created 4 times, despite setting the dispatch_uid. What have I misunderstood?

The #receiver(Signal,...) decorator is a shortcut for Signal.connect(...), so you indeed register your create_new_patient handler twice (once thru #receiver when importing your signals module, the second time with pre_save.connect().
Solution : in your App.ready() method, you should just import your app's signal.py module. This will trigger the registration of the handlers decorated with #receiver.

Related

Django Signals - creating folder on model create

I got a model where I would like to create a folder when a model is created:
The model:
class Drive(models.Model):
user = models.ManyToManyField(User)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
path = models.CharField(max_length=150, editable=False,
default='C:/Users/User/Desktop/Python/RavNet/media/storage/drives/{}'.format(str(id)))
def save(self):
super().save()
I am trying to use signals, but I must admit this is my first ever attempt at making a signal not following a tutorial on point, and even after reading the documentation I am having a tough time.
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Drive
import os
#receiver(post_save, sender=Drive)
def create_drive(sender, instance, created, **kwargs):
if created:
os.mkdir(Drive.path)
Nothing happens when I create a new drive model via the django admin. I have tested out my code in the shell and using a placeholder path (C:/Users/User/Desktop/Python/RavNet/media/storage/drives/test) that I know works in the signal in a try to debug, and have gotten as far as realising I am having two issues.
The first: When calling the Drive.path in the shell, I am getting the path:
'C:/Users/User/Desktop/Python/RavNet/media/storage/drives/<django.db.models.fields.UUIDField>'
Instead of a path with the actual id as I hoped for. How do I solve this?
Secondly, my signal isn't working. It's like it isn't getting called. What am I doing wrong?
You must import your signals in app.py. Please check your app.py. It must be like this:
from django.apps import AppConfig
class YourAppConfig(AppConfig):
name = '...'
def ready(self):
import your_project.your_app.signals
Also your app/__init__.py must include this code:
default_app_config = 'your_project.your_app.apps.YourAppConfig'
In case you have many signals and don't want the app.py defined in your app.
you could do so:
signals are in folder app/signals/__init__.py signal1.py signal2.py
import all files in __init__.py
from .signal1 import *
from .signal2 import *
from app.signals import * inside of app/views/__init__.py

Using Django signals to identify a present user session

i want to use django signals to identify if a user is logged-in twice and if so, revoke his first session so that only one user session can be present at once.
i used the following example but it seems that my signals.py does not even gets reconcnized and i dont know why.
Example:
How to prevent multiple login in Django
accounts/signals.py
from django.contrib.auth import user_logged_in
from django.dispatch.dispatcher import receiver
from django.contrib.sessions.models import Session
from .models import UserSession
#receiver(user_logged_in)
def remove_other_sessions(sender, user, request, **kwargs):
# remove other sessions
Session.objects.filter(usersession__user=user).delete()
# save current session
request.session.save()
# create a link from the user to the current session (for later removal)
UserSession.objects.get_or_create(
user=user,
session=Session.objects.get(pk=request.session.session_key)
)
accounts/models.py
# Model to store the list of logged in users
class UserSession(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
session = models.OneToOneField(Session, on_delete=models.CASCADE)
accounts/apps.py
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = 'Accounts'
def ready(self):
import Accounts.signals
but for some reason nothing gets written onto the database for that table.
do i maybe miss something here, this is the very first time i get in touch with signals so i might missed something at the configuration.
Try this,
default_app_config = 'Accounts.apps.AccountsConfig'
Add this line in __init__.py file of your apps.py file directory.

notify user if similar model created _Django

I have a model.that I need to if any model with specific field created in database.send a Email to user for notify.I did some search too many apps are there for handling the notify. thats not my concern .I dont know how deploy this structure.any guide or example for this.for example :
if x = book.objects.create(title="book1") :
print("the book created")
if this action happend do something.
If you need to monitor object creation globally the best thing to use is signals
Like so:
from .models import Book
from django.db.models.signals import post_save
def book_created(sender, instance, created, **kwargs):
if created and instance.title == 'book1':
#logic here
post_save.connect(save_profile, sender=Book)
you need to stick that post_save.connect() function somewhere where it will be evaluated when the app is run, you can use app_dir/app.py for instance.

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 1.8: Function not called on Signal

I'm picking up on a code which should send a signal every time a user logs in. Thats not happening though. The function get_create_stripe() isnt getting called when the user logs in.
Anyone can tell whats wrong?
I'm working in Django 1.8 and the whole code is here.
Gist about the code: This code is part of an e-commerce site which users stripe as its payment gateway. Intent is, every time user logs in, we create a new stripe id or return an existing one.
Is it because this function is not in models.py? This is written to a file 'signals.py' and I'm not quite sure how Django should understand to call get_create_stripe() from a signal call in this file. Is it so?
import stripe
from django.conf import settings
from django.contrib.auth.signals import user_logged_in
from .models import UserStripe
stripe.api_key = settings.STRIPE_SECRET_KEY
def get_create_stripe(sender, user, *args, **kwargs):
new_user_stripe, created = UserStripe.objects.get_or_create(user=user)
print "hello"
if created:
customer = stripe.Customer.create(
email = str(user.email)
)
print customer
new_user_stripe.stripe_id = customer.id
new_user_stripe.save()
user_logged_in(get_create_stripe)
You need to connect your signal method to the signal.
Something like
from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in
#receiver(user_logged_in, sender=UserStripe)
def get_create_stripe(sender, user, *args, **kwargs):
EDIT: Also, what is this:
user_logged_in(get_create_stripe)
That is not how signals work. Either you do what I wrote above, or do this:
user_logged_in.connect(get_create_stripe)

Categories

Resources