Django signal based on the datetime field valueUpdate tasks in Celery with RabbitMQExtending the User model with custom fields in DjangoHow to combine 2 or more querysets in a Django view?Does Django scale?Django datetime issues (default=datetime.now())Need a minimal Django file upload exampleHow to check Django versiondifferentiate null=True, blank=True in djangoAre Django signals thread safe?django : How to use signals?How to check if Django Signal works?
Incremental Ranges!
How much water is needed to create a Katana capable of cutting flesh, bones and wood?
Short story written from alien perspective with this line: "It's too bright to look at, so they don't"
Word for a small burst of laughter that can't be held back
Why is c4 bad when playing the London against a King's Indian?
Wiring from Main to Subpanel
If Boris Johnson were prosecuted and convicted of lying about Brexit, can that be used to cancel Brexit?
Working in the USA for living expenses only; allowed on VWP?
Old black and white movie: glowing black rocks slowly turn you into stone upon touch
Do adult Russians normally hand-write Cyrillic as cursive or as block letters?
Responsibility for visa checking
How do you build a story from a world?
Is there any word or phrase for negative bearing?
Comma Code - Ch. 4 Automate the Boring Stuff
Does Peach's float negate shorthop knockback multipliers?
Secure offsite backup, even in the case of hacker root access
Movie where a boy is transported into the future by an alien spaceship
What's the logic behind the the organization of Hamburg's bus transport into "rings"?
Credit card offering 0.5 miles for every cent rounded up. Too good to be true?
How certain is a caster of when their spell will end?
Explain Ant-Man's "not it" scene from Avengers: Endgame
Could the Missouri River be running while Lake Michigan was frozen several meters deep?
What is a simple, physical situation where complex numbers emerge naturally?
Opposite of "Squeaky wheel gets the grease"
Django signal based on the datetime field value
Update tasks in Celery with RabbitMQExtending the User model with custom fields in DjangoHow to combine 2 or more querysets in a Django view?Does Django scale?Django datetime issues (default=datetime.now())Need a minimal Django file upload exampleHow to check Django versiondifferentiate null=True, blank=True in djangoAre Django signals thread safe?django : How to use signals?How to check if Django Signal works?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I'm struggling with the following.
I'm trying to create a custom signal that will trigger when the current time will be equal to the value of my model's notify_on DateTimeField
.
Something like this:
class Notification(models.Model):
...
notify_on = models.DateTimeField()
def send_email(*args, **kwargs):
# send email
signals.when_its_time.connect(send_email, sender=User)
After I've read through all docs and I found no information on how to implement such a signal.
Any ideas?
UPDATE:
Less naive approach with ability to discard irrelevant tasks: https://stackoverflow.com/a/55337663/9631956
django celery django-signals
add a comment |
I'm struggling with the following.
I'm trying to create a custom signal that will trigger when the current time will be equal to the value of my model's notify_on DateTimeField
.
Something like this:
class Notification(models.Model):
...
notify_on = models.DateTimeField()
def send_email(*args, **kwargs):
# send email
signals.when_its_time.connect(send_email, sender=User)
After I've read through all docs and I found no information on how to implement such a signal.
Any ideas?
UPDATE:
Less naive approach with ability to discard irrelevant tasks: https://stackoverflow.com/a/55337663/9631956
django celery django-signals
2
I believe you may need Celery delayed tasks as signals starts running after some events but not by time.
– Sergey Pugach
Mar 24 at 13:32
@SergeyPugach I already use celery to send confirmation emails, now I'll need to figure out how to configure to it to check all myNotification
instances. Thank you
– bloodwithmilk
Mar 24 at 13:53
1
When you call task with.apply_async()
you can passeta
orcountdown
arg in order your task yo be run in certain time: docs.celeryproject.org/en/latest/userguide/calling.html
– Sergey Pugach
Mar 24 at 14:13
add a comment |
I'm struggling with the following.
I'm trying to create a custom signal that will trigger when the current time will be equal to the value of my model's notify_on DateTimeField
.
Something like this:
class Notification(models.Model):
...
notify_on = models.DateTimeField()
def send_email(*args, **kwargs):
# send email
signals.when_its_time.connect(send_email, sender=User)
After I've read through all docs and I found no information on how to implement such a signal.
Any ideas?
UPDATE:
Less naive approach with ability to discard irrelevant tasks: https://stackoverflow.com/a/55337663/9631956
django celery django-signals
I'm struggling with the following.
I'm trying to create a custom signal that will trigger when the current time will be equal to the value of my model's notify_on DateTimeField
.
Something like this:
class Notification(models.Model):
...
notify_on = models.DateTimeField()
def send_email(*args, **kwargs):
# send email
signals.when_its_time.connect(send_email, sender=User)
After I've read through all docs and I found no information on how to implement such a signal.
Any ideas?
UPDATE:
Less naive approach with ability to discard irrelevant tasks: https://stackoverflow.com/a/55337663/9631956
django celery django-signals
django celery django-signals
edited Mar 26 at 23:16
bloodwithmilk
asked Mar 24 at 13:08
bloodwithmilkbloodwithmilk
5381616
5381616
2
I believe you may need Celery delayed tasks as signals starts running after some events but not by time.
– Sergey Pugach
Mar 24 at 13:32
@SergeyPugach I already use celery to send confirmation emails, now I'll need to figure out how to configure to it to check all myNotification
instances. Thank you
– bloodwithmilk
Mar 24 at 13:53
1
When you call task with.apply_async()
you can passeta
orcountdown
arg in order your task yo be run in certain time: docs.celeryproject.org/en/latest/userguide/calling.html
– Sergey Pugach
Mar 24 at 14:13
add a comment |
2
I believe you may need Celery delayed tasks as signals starts running after some events but not by time.
– Sergey Pugach
Mar 24 at 13:32
@SergeyPugach I already use celery to send confirmation emails, now I'll need to figure out how to configure to it to check all myNotification
instances. Thank you
– bloodwithmilk
Mar 24 at 13:53
1
When you call task with.apply_async()
you can passeta
orcountdown
arg in order your task yo be run in certain time: docs.celeryproject.org/en/latest/userguide/calling.html
– Sergey Pugach
Mar 24 at 14:13
2
2
I believe you may need Celery delayed tasks as signals starts running after some events but not by time.
– Sergey Pugach
Mar 24 at 13:32
I believe you may need Celery delayed tasks as signals starts running after some events but not by time.
– Sergey Pugach
Mar 24 at 13:32
@SergeyPugach I already use celery to send confirmation emails, now I'll need to figure out how to configure to it to check all my
Notification
instances. Thank you– bloodwithmilk
Mar 24 at 13:53
@SergeyPugach I already use celery to send confirmation emails, now I'll need to figure out how to configure to it to check all my
Notification
instances. Thank you– bloodwithmilk
Mar 24 at 13:53
1
1
When you call task with
.apply_async()
you can pass eta
or countdown
arg in order your task yo be run in certain time: docs.celeryproject.org/en/latest/userguide/calling.html– Sergey Pugach
Mar 24 at 14:13
When you call task with
.apply_async()
you can pass eta
or countdown
arg in order your task yo be run in certain time: docs.celeryproject.org/en/latest/userguide/calling.html– Sergey Pugach
Mar 24 at 14:13
add a comment |
2 Answers
2
active
oldest
votes
In django's documentation there is two interesting signals that may help you on this task: pre_save and post_save.
It depends on your needs, but let's say you want to check if your model's notify_on
is equal to the current date after saving your model (actually after calling the save()
or create()
method). If it's your case you can do:
from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
class Notification(models.Model):
...
# Every notification is related to a user
# It depends on your model, but i guess you're doing something similar
user = models.ForeignKey(User, related_name='notify', on_delete=models.DO_NOTHING)
notify_on = models.DateTimeField()
...
def send_email(self, *args, **kwargs):
"""A model method to send email notification"""
...
@receiver(post_save, sender=User)
def create_notification(sender, instance, created, **kwargs):
# check if the user instance is created
if created:
obj = Notification.objects.create(user=instance, date=datetime.now().date())
if obj.notify_on == datetime.now().date():
obj.send_email()
And you should know, that django signals won't work by they own only if there is an action that triggers them. What this mean is that Django signals won't loop over your model's instances and perform an operation, but django signals will trigger when your application is performing an action on the model connected to a signal.
Bonus: To perform a loop over your instances and process an action regulary you may need an async
worker with a Queue
database (mostly, Celery
with Redis or RabbitMQ
).
add a comment |
Ok, thanks to comments by @SergeyPugach I've done the following:
Added a post_save
signal that calls a function that adds a task to the celery. apply_async
let's you pass eta
- estimated time of arrival which can accept DateTimeField
directly, that's very convenient.
# models.py
from django.db.models import signals
from django.db import models
from .tasks import send_notification
class Notification(models.Model):
...
notify_on = models.DateTimeField()
def notification_post_save(instance, *args, **kwargs):
send_notification.apply_async((instance,), eta=instance.notify_on)
signals.post_save.connect(notification_post_save, sender=Notification)
And the actual task in the tasks.py
import logging
from user_api.celery import app
from django.core.mail import send_mail
from django.template.loader import render_to_string
@app.task
def send_notification(self, instance):
try:
mail_subject = 'Your notification.'
message = render_to_string('notify.html',
'title': instance.title,
'content': instance.content
)
send_mail(mail_subject, message, recipient_list=[instance.user.email], from_email=None)
except instance.DoesNotExist:
logging.warning("Notification does not exist anymore")
I will not get into details of setting up celery, there's plenty of information out there.
Now I will try to figure out how to update the task after it's notification instance was updated, but that's a completely different story.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55324117%2fdjango-signal-based-on-the-datetime-field-value%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
In django's documentation there is two interesting signals that may help you on this task: pre_save and post_save.
It depends on your needs, but let's say you want to check if your model's notify_on
is equal to the current date after saving your model (actually after calling the save()
or create()
method). If it's your case you can do:
from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
class Notification(models.Model):
...
# Every notification is related to a user
# It depends on your model, but i guess you're doing something similar
user = models.ForeignKey(User, related_name='notify', on_delete=models.DO_NOTHING)
notify_on = models.DateTimeField()
...
def send_email(self, *args, **kwargs):
"""A model method to send email notification"""
...
@receiver(post_save, sender=User)
def create_notification(sender, instance, created, **kwargs):
# check if the user instance is created
if created:
obj = Notification.objects.create(user=instance, date=datetime.now().date())
if obj.notify_on == datetime.now().date():
obj.send_email()
And you should know, that django signals won't work by they own only if there is an action that triggers them. What this mean is that Django signals won't loop over your model's instances and perform an operation, but django signals will trigger when your application is performing an action on the model connected to a signal.
Bonus: To perform a loop over your instances and process an action regulary you may need an async
worker with a Queue
database (mostly, Celery
with Redis or RabbitMQ
).
add a comment |
In django's documentation there is two interesting signals that may help you on this task: pre_save and post_save.
It depends on your needs, but let's say you want to check if your model's notify_on
is equal to the current date after saving your model (actually after calling the save()
or create()
method). If it's your case you can do:
from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
class Notification(models.Model):
...
# Every notification is related to a user
# It depends on your model, but i guess you're doing something similar
user = models.ForeignKey(User, related_name='notify', on_delete=models.DO_NOTHING)
notify_on = models.DateTimeField()
...
def send_email(self, *args, **kwargs):
"""A model method to send email notification"""
...
@receiver(post_save, sender=User)
def create_notification(sender, instance, created, **kwargs):
# check if the user instance is created
if created:
obj = Notification.objects.create(user=instance, date=datetime.now().date())
if obj.notify_on == datetime.now().date():
obj.send_email()
And you should know, that django signals won't work by they own only if there is an action that triggers them. What this mean is that Django signals won't loop over your model's instances and perform an operation, but django signals will trigger when your application is performing an action on the model connected to a signal.
Bonus: To perform a loop over your instances and process an action regulary you may need an async
worker with a Queue
database (mostly, Celery
with Redis or RabbitMQ
).
add a comment |
In django's documentation there is two interesting signals that may help you on this task: pre_save and post_save.
It depends on your needs, but let's say you want to check if your model's notify_on
is equal to the current date after saving your model (actually after calling the save()
or create()
method). If it's your case you can do:
from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
class Notification(models.Model):
...
# Every notification is related to a user
# It depends on your model, but i guess you're doing something similar
user = models.ForeignKey(User, related_name='notify', on_delete=models.DO_NOTHING)
notify_on = models.DateTimeField()
...
def send_email(self, *args, **kwargs):
"""A model method to send email notification"""
...
@receiver(post_save, sender=User)
def create_notification(sender, instance, created, **kwargs):
# check if the user instance is created
if created:
obj = Notification.objects.create(user=instance, date=datetime.now().date())
if obj.notify_on == datetime.now().date():
obj.send_email()
And you should know, that django signals won't work by they own only if there is an action that triggers them. What this mean is that Django signals won't loop over your model's instances and perform an operation, but django signals will trigger when your application is performing an action on the model connected to a signal.
Bonus: To perform a loop over your instances and process an action regulary you may need an async
worker with a Queue
database (mostly, Celery
with Redis or RabbitMQ
).
In django's documentation there is two interesting signals that may help you on this task: pre_save and post_save.
It depends on your needs, but let's say you want to check if your model's notify_on
is equal to the current date after saving your model (actually after calling the save()
or create()
method). If it's your case you can do:
from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
class Notification(models.Model):
...
# Every notification is related to a user
# It depends on your model, but i guess you're doing something similar
user = models.ForeignKey(User, related_name='notify', on_delete=models.DO_NOTHING)
notify_on = models.DateTimeField()
...
def send_email(self, *args, **kwargs):
"""A model method to send email notification"""
...
@receiver(post_save, sender=User)
def create_notification(sender, instance, created, **kwargs):
# check if the user instance is created
if created:
obj = Notification.objects.create(user=instance, date=datetime.now().date())
if obj.notify_on == datetime.now().date():
obj.send_email()
And you should know, that django signals won't work by they own only if there is an action that triggers them. What this mean is that Django signals won't loop over your model's instances and perform an operation, but django signals will trigger when your application is performing an action on the model connected to a signal.
Bonus: To perform a loop over your instances and process an action regulary you may need an async
worker with a Queue
database (mostly, Celery
with Redis or RabbitMQ
).
edited Mar 24 at 14:04
answered Mar 24 at 13:38
Chiheb NexusChiheb Nexus
5,41931829
5,41931829
add a comment |
add a comment |
Ok, thanks to comments by @SergeyPugach I've done the following:
Added a post_save
signal that calls a function that adds a task to the celery. apply_async
let's you pass eta
- estimated time of arrival which can accept DateTimeField
directly, that's very convenient.
# models.py
from django.db.models import signals
from django.db import models
from .tasks import send_notification
class Notification(models.Model):
...
notify_on = models.DateTimeField()
def notification_post_save(instance, *args, **kwargs):
send_notification.apply_async((instance,), eta=instance.notify_on)
signals.post_save.connect(notification_post_save, sender=Notification)
And the actual task in the tasks.py
import logging
from user_api.celery import app
from django.core.mail import send_mail
from django.template.loader import render_to_string
@app.task
def send_notification(self, instance):
try:
mail_subject = 'Your notification.'
message = render_to_string('notify.html',
'title': instance.title,
'content': instance.content
)
send_mail(mail_subject, message, recipient_list=[instance.user.email], from_email=None)
except instance.DoesNotExist:
logging.warning("Notification does not exist anymore")
I will not get into details of setting up celery, there's plenty of information out there.
Now I will try to figure out how to update the task after it's notification instance was updated, but that's a completely different story.
add a comment |
Ok, thanks to comments by @SergeyPugach I've done the following:
Added a post_save
signal that calls a function that adds a task to the celery. apply_async
let's you pass eta
- estimated time of arrival which can accept DateTimeField
directly, that's very convenient.
# models.py
from django.db.models import signals
from django.db import models
from .tasks import send_notification
class Notification(models.Model):
...
notify_on = models.DateTimeField()
def notification_post_save(instance, *args, **kwargs):
send_notification.apply_async((instance,), eta=instance.notify_on)
signals.post_save.connect(notification_post_save, sender=Notification)
And the actual task in the tasks.py
import logging
from user_api.celery import app
from django.core.mail import send_mail
from django.template.loader import render_to_string
@app.task
def send_notification(self, instance):
try:
mail_subject = 'Your notification.'
message = render_to_string('notify.html',
'title': instance.title,
'content': instance.content
)
send_mail(mail_subject, message, recipient_list=[instance.user.email], from_email=None)
except instance.DoesNotExist:
logging.warning("Notification does not exist anymore")
I will not get into details of setting up celery, there's plenty of information out there.
Now I will try to figure out how to update the task after it's notification instance was updated, but that's a completely different story.
add a comment |
Ok, thanks to comments by @SergeyPugach I've done the following:
Added a post_save
signal that calls a function that adds a task to the celery. apply_async
let's you pass eta
- estimated time of arrival which can accept DateTimeField
directly, that's very convenient.
# models.py
from django.db.models import signals
from django.db import models
from .tasks import send_notification
class Notification(models.Model):
...
notify_on = models.DateTimeField()
def notification_post_save(instance, *args, **kwargs):
send_notification.apply_async((instance,), eta=instance.notify_on)
signals.post_save.connect(notification_post_save, sender=Notification)
And the actual task in the tasks.py
import logging
from user_api.celery import app
from django.core.mail import send_mail
from django.template.loader import render_to_string
@app.task
def send_notification(self, instance):
try:
mail_subject = 'Your notification.'
message = render_to_string('notify.html',
'title': instance.title,
'content': instance.content
)
send_mail(mail_subject, message, recipient_list=[instance.user.email], from_email=None)
except instance.DoesNotExist:
logging.warning("Notification does not exist anymore")
I will not get into details of setting up celery, there's plenty of information out there.
Now I will try to figure out how to update the task after it's notification instance was updated, but that's a completely different story.
Ok, thanks to comments by @SergeyPugach I've done the following:
Added a post_save
signal that calls a function that adds a task to the celery. apply_async
let's you pass eta
- estimated time of arrival which can accept DateTimeField
directly, that's very convenient.
# models.py
from django.db.models import signals
from django.db import models
from .tasks import send_notification
class Notification(models.Model):
...
notify_on = models.DateTimeField()
def notification_post_save(instance, *args, **kwargs):
send_notification.apply_async((instance,), eta=instance.notify_on)
signals.post_save.connect(notification_post_save, sender=Notification)
And the actual task in the tasks.py
import logging
from user_api.celery import app
from django.core.mail import send_mail
from django.template.loader import render_to_string
@app.task
def send_notification(self, instance):
try:
mail_subject = 'Your notification.'
message = render_to_string('notify.html',
'title': instance.title,
'content': instance.content
)
send_mail(mail_subject, message, recipient_list=[instance.user.email], from_email=None)
except instance.DoesNotExist:
logging.warning("Notification does not exist anymore")
I will not get into details of setting up celery, there's plenty of information out there.
Now I will try to figure out how to update the task after it's notification instance was updated, but that's a completely different story.
answered Mar 24 at 20:00
bloodwithmilkbloodwithmilk
5381616
5381616
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55324117%2fdjango-signal-based-on-the-datetime-field-value%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
I believe you may need Celery delayed tasks as signals starts running after some events but not by time.
– Sergey Pugach
Mar 24 at 13:32
@SergeyPugach I already use celery to send confirmation emails, now I'll need to figure out how to configure to it to check all my
Notification
instances. Thank you– bloodwithmilk
Mar 24 at 13:53
1
When you call task with
.apply_async()
you can passeta
orcountdown
arg in order your task yo be run in certain time: docs.celeryproject.org/en/latest/userguide/calling.html– Sergey Pugach
Mar 24 at 14:13