Django如何获得request.get_host?

Django how to get request.get_host?

感谢您阅读我的 problem.I 我没有收到请求 host.I 我正在向那些在我的 app.I 中注册的司机发送电子邮件 我正在发送预订 link 他们的 id 在 URL 中。问题是我没有得到主机。 例如 点击 link 后,我希望他重定向到他可以看到汽车的页面。

邮件输出发送邮件后:

请按link订车/drivers/2/

但我想要一个合适的 link 来给他发邮件

例如

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

像这样构建 url 并尝试。

request.get_host +'/driver/'+driver_id

最好的方法是使用 HttpRequestbuild_absolute_uri 方法在您的视图中构建 URL,因为这也会添加当前协议(https 或 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)

这会导致 http://localhost:8000/drivers/2 显示在您的电子邮件中。