2016-10-22 62 views
1

我試圖從django信號發送一個電子郵件與我的網站地址。我發現這個問題:https://stackoverflow.com/a/15521046/2385132,並着手爲接受的答案被告知,但使用該代碼的時候,我得到這個錯誤:Django:如何獲取信號處理程序中的域名

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

這是從我的代碼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, 
    ) 

所以問題是:如何在信號中獲得我的視圖的完整url?

Btw。我正在使用django-rest-framework

回答

3

在最近的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_ID設置指向正確的實例在Site表,試試這個,你會看到:)

+0

其實我使用的是django v1.9.7 :)。我想我會回答你的答案,所以謝謝你。 –

+0

嘿..是的,我已經更新了我的答案 – trinchet

相關問題