Szworny Dziąch Szworny Dziąch - 1 month ago 12
Python Question

Django: How to get domain name inside a signal handler

I'm trying to send an email with my website address from django signal. I found this question: http://stackoverflow.com/a/15521046/2385132 and proceeded as was advised in the accepted answer, but when using that code, I'm getting this error:

AttributeError: 'NoneType' object has no attribute 'get_host'


Which is coming from the
get_current_site
in my code:

@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,
)


So the question is: how do I get full url of my view in a signal?

Btw. I'm using
django-rest-framework
.

Answer

In recent Django versions (probably your case), the domain is always taken from the request if SITE_ID is not defined in your settings. See this change introduced in 1.8 Django version:

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.

So, in your case request=None you must have the sites framework enabled, an entry for your current site/domain and SITE_ID setting pointing to the right instance in the Site table, try this and you will see :)