Search code examples
djangopathrequestsignals

Django signal get request full path


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

Solution

  • 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.