我正在尝试通过 django signal 发送一封包含我的网站地址的电子邮件。我发现这个问题:https://stackoverflow.com/a/15521046/2385132并按照接受的答案中的建议进行操作,但是在使用该代码时,我收到此错误:
AttributeError:“NoneType”对象没有属性“get_host”
它来 self 的代码中的 get_current_site
:
@receiver(post_save, sender=MyModel)
def post_obj_save(sender, instance: MyModel, **kwargs):
def _get_html(obj: MyModel):
return render_to_string('confirmation_email.html', _get_context(obj))
def _get_context(obj: MyModel):
current_site = get_current_site(request=None)
domain = current_site.domain
action = reverse('obj_activation', request=None, format=None, kwargs={})
url = '{protocol}://{domain}/{action}'.format(protocol=PROTOCOL, domain=domain, action=action)
return {
'header': _('Thank you for registering with ASDF.'),
'prompt': _('In order to be able to log in into ASDF administrator panel, you have to activate your account using'),
'link_name': _('this link'),
'activation_url': url
}
send_mail(
_('ASDF account activation'),
_get_html(instance),
EMAIL_FROM,
[obj.owner.email],
fail_silently=False,
)
所以问题是:如何在信号中获取 View 的完整 url?
顺便说一句。我正在使用django-rest-framework
。
最佳答案
在最近的 Django 版本中(可能是您的情况),如果您的设置中未定义 SITE_ID
,则域总是从请求中获取 。请参阅this 1.8 Django 版本中引入的更改:
Changed in Django 1.8:
This function will now lookup the current site based on request.get_host() if the SITE_ID setting is not defined.
因此,在您的情况下 request=None
您必须拥有 sites
framework已启用,您当前站点/域的条目和指向 Site
表中正确实例的 SITE_ID
设置,尝试此操作,您将看到:)
关于python - Django:如何在信号处理程序中获取域名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40193821/