Search code examples
pythondjangodjango-viewsdjango-urlsdjango-email

Django how to get request.get_host?


Thankyou for reading my problem.I am not getting the request get host.I am sending an email to the drivers those who registered in my app.I am sending a Booking link with their id in URL. The problem is that i am not getting the host with it. For eg after hitting the link i want him to redirect to the page where he can see the car.

Output in mail After sending email :

Please hit the link and book a car /drivers/2/

but i want a proper link to send him in mail

for eg

http://127.0.0.1:8000/drivers/1/

Views.Py

from django.template import Context, Template as mailt

@csrf_exempt
def rentacar_carapp_approve(request):
    if request.POST:
        try:
            args['driver'] = driver = Driver.objects.get(id=request.POST.get('driver_id'))
            subject = "Please Register Your Car"
            from_email = settings.EMAIL_HOST_USER
            to_email = 'bakrshk@gmail.com'
            if to_email is not None:
                template = mailt("""Please hit the link and book a car {{ request.get_host }}{% url 'detail' driver_id=driver_id %}""")
                ctx = Context({'driver_id': driver.id})
                join_message = template.render(ctx)
                send_mail(subject=subject, from_email=from_email, recipient_list=[to_email], message=join_message,
                          fail_silently=False)
                print("email sent")
                print(request.get_host)
        except Driver.DoesNotExist:
            print("Driver doesn't exists")

Url.py

url(r'^drivers/(?P<driver_id>\d+)/$', rent_views.detail, name='detail'),

Solution

  • The best way is to build the URL in your view using build_absolute_uri method of HttpRequest, since this will also add the current protocol (https or http):

    url = request.build_absolute_uri(reverse('detail', kwargs={'driver_id': driver.id}))
    ctx = Context({'url': url})
    template = mailt("""Please hit the link and book a car {{ url }}""")
    join_message = template.render(ctx)
    

    This should lead to http://localhost:8000/drivers/2 displayed in your email message.