[Django]-Trouble scheduling and rescheduling posts with Celery

3πŸ‘

βœ…

I don’t know what your tasks.py file looks like, but I assume it’s something like the following:

from celery.decorators import task

@task
def publish_post(post_id):
    ''' Sets the status of a post to Published '''
    from blog.models import Post

    Post.objects.filter(pk=post_id).update(status=Post.STATUS_PUBLISHED)

You should edit the filter within the task to make sure that the current status is STATUS_SCHEDULED and that the time in date_published has passed. e.g.:

from celery.decorators import task

@task
def publish_post(post_id):
    ''' Sets the status of a post to Published '''
    from blog.models import Post
    from datetime import datetime

    Post.objects.filter(
        pk=post_id,
        date_published__lte=datetime.now(),
        status=Post.STATUS_SCHEDULED
    ).update(status=Post.STATUS_PUBLISHED)

This way, users can change the status back and forth, change the time, and the task will only ever change the status to publish if the task is running after the date_published column. No need to track ids or revoke tasks.

Leave a comment