0

I would like to get the absolute url from my saved object. My model has a method named get_absolute_url and I would like to call this method with my django post_save signal.

I receive a post_save signal when a new entry is added inside a specific table named Thread. This post_save signal executes my Celery task.

My Thread model is :

class Thread(models.Model):
    """ A thread with a title """

    topic = models.ForeignKey('Topic')
    title = models.CharField(max_length=200)
    sticky = models.BooleanField(default=False)
    slug = models.SlugField()
    time_created = models.DateTimeField(default=timezone.now)
    time_last_activity = models.DateTimeField(default=timezone.now)

    def __init__(self, *args, **kwargs):
        """ Initialize 'time_last_activity' to 'time_created' """
        super(Thread, self).__init__(*args, **kwargs)

        self.time_last_activity = self.time_created

    def __str__(self):
        """ Return the thread's title """
        return self.title

    def get_absolute_url(self):
        """ Return the url of the instance's detail view """
        url_kwargs = {
            'topic_pk': self.topic.pk,
            'topic_slug': self.topic.slug,
            'thread_pk': self.pk,
            'thread_slug': self.slug,
        }
        return reverse('simple-forums:thread-detail', kwargs=url_kwargs)

In my model, I have a celery.py file :

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db.models.signals import post_save
from django.dispatch import receiver
from simple_forums.models import Thread

from ..tasks import thread_notification


@receiver(post_save, sender=Thread)
def get_new_thread(sender, instance, **kwargs):
    """ Post_save method which start Celery task to notify forum subscribers that a new thread has been created """
    url = Thread.get_absolute_url()
    print(url)
    thread_title = instance.title
    thread_id = instance.id
    topic_id = instance.topic_id
    topic_slug = instance.topic.slug
    topic_title = instance.topic.title
    thread_notification.delay(thread_id=thread_id, thread_title=thread_title, topic_id=topic_id, topic_slug=topic_slug,
                              topic_title=topic_title)

And in my tasks.py file :

# -*- coding: utf-8 -*-

from celery import shared_task
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext_lazy as _

User = get_user_model()


@shared_task(bind=True, time_limit=3600, soft_time_limit=3600)
def thread_notification(self):
    print('Celery task executed')
    return ['success_message', _('Celery task ended')]

I would like to get the absolute_url in order to send an email with the new Thread path.

My question is : How I can pick up get_absolute_url or use request.build_absolute_uri if I don't have a specific view (not necessary) ?

1 Answer 1

2

Here:

@receiver(post_save, sender=Thread)
def get_new_thread(sender, instance, **kwargs):
    url = Thread.get_absolute_url()

the saved Thread instance is (suprise, surprise) your instance argument, so you want:

    url = instance.get_absolute_url()

calling an instance method on a class makes no sense (nb: except for a couple specific corner cases, and then you have to pass the instance as first argument, but let's not get further with this, when you'll need it you'll know how it works).

Now since you're in the same app, using a signal here makes no sense either and is actually an antipattern. The point of signals is to allow an app to react to events emitted by other apps. Here, your code should quite simply be in Thread.save().

4
  • Thank you for your detailed answer ! I will try to make changes according to your advice :)
    – ChocoBomb
    Feb 26, 2019 at 8:11
  • I just have a question : How I can import file in my project from a pip-installed module ? Because Thread object comes from simple_forums django module.
    – ChocoBomb
    Feb 26, 2019 at 8:21
  • And I used signals because if I make an update of simple_forums module, my code will be deleted if I change Thread.save() method.
    – ChocoBomb
    Feb 26, 2019 at 8:32
  • @ChocoBomb if the model is from a third part app then of course signals are the right tool - your post didn't made it clear, sorry. Feb 27, 2019 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.