I have a Post model. There is a field publish_date. If the post has a planned status, then i need to perform the publishing function on the publish_date. How can I do this?
models.py:
class Post(models.Model):
STATES = (
('draft', 'Draft'),
('published', 'Published'),
('planned', 'Planned')
)
state = models.CharField(choices=STATES, default=STATES[0][0])
channels = models.ManyToManyField('channel.Channel')
creator = models.ForeignKey('authentication.User', on_delete=models.SET_NULL, null=True)
publish_date = models.DateTimeField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@receiver(post_save, sender=Post)
def reschedule_publish_task(sender, instance, **kwargs):
# There should be a task setting for a specific time here, as I understand it
I tried to do this, but it didn't work, the task is not completed.
models.py
@receiver(post_save, sender=Post)
def reschedule_publish_task(sender, instance, **kwargs):
task_id = f"publish_post_{instance.id}"
if instance.state == 'planned' and instance.publish_date:
publish_post.apply_async((instance.id,), eta=instance.publish_date, task_id=task_id)
tasks.py
@shared_task
def publish_post(post_id: int) -> None:
from .models import Post
post = Post.objects.filter(id=post_id).first()
if post:
if post.state == 'planned' and post.publish_date <= now():
post.state = 'published'
post.save()