首页 > 解决方案 > Getting link of latest article in Models

问题描述

I have a post signal in my Models so that when I create a new post thru the admin, it will send a mail. It works, but I want the message to include the link of the article I just created. How can I do this?

def send_mails(sender, **kwargs):
    if kwargs['created']:
        message = 'Hello!\nWe have a new post: mysite.net/{latest article id}\nEnjoy!\n\nKind regards,\nThe Analyst'
        subject = 'New Article Published!'
        to = Email.objects.values_list('email', flat=True).distinct()
        from_email = settings.EMAIL_HOST_USER
        send_mail(subject, message, from_email, to, fail_silently=True)


post_save.connect(send_mails, sender=Post)

标签: pythondjangomodel

解决方案


The instance that was saved is passed as instance parameter:

def send_mails(sender, instance, created, **kwargs):
    if created:
        message = f'Hello!\nWe have a new post: mysite.net/{instance.id}\nEnjoy!\n\nKind regards,\nThe Analyst'
        subject = 'New Article Published!'
        to = Email.objects.values_list('email', flat=True).distinct()
        from_email = settings.EMAIL_HOST_USER
        send_mail(subject, message, from_email, to, fail_silently=True)

推荐阅读