Django signal get request full path

拥有回忆 提交于 2019-12-12 17:16:59

问题


I wrote a signal in my django project, inside I want to send an email with the full path of my website. But to do so, I need to get the request object inside the signal, how could I do that? Thanks.

    @receiver(pre_save, sender=AccessRequest)
    def email_if_access_true(sender, instance, **kwargs):
        #How can I get the full path of my website here?
        pass

回答1:


Put following code in your pre_save signal receiver:

from django.contrib.sites.models import get_current_site
current_site = get_current_site(request=None)
domain = current_site.domain
protocol = "http"

You can generate absolute url to your website in email by passing required context variables to template. If access_request is instance in your case and there is one get_abosulte_url() method in your AccessRequest model, then following line in email template will give you absolute url.

{{ protocol }}://{{ domain }}{% access_request.get_absolute_url %}

Reference - PasswordResetForm in django.contrib.auth.form.




回答2:


If you don’t have access to the request object, you can use the get_current() method of the Site model’s manager.

from django.contrib.sites.models import Site

@receiver(pre_save, sender=AccessRequest)
def email_if_access_true(sender, instance, **kwargs):
    current_site = Site.objects.get_current()
    if current_site.domain == 'foo.com':
        #do other stuff here
    else:
        pass

you need to ensure that you defined SITE_ID=1 in your settings



来源:https://stackoverflow.com/questions/15520246/django-signal-get-request-full-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!