【问题标题】:How to get Host IP address in the Django [closed]如何在 Django 中获取主机 IP 地址 [关闭]
【发布时间】:2014-02-25 05:15:15
【问题描述】:

我想将我的主机 IP 地址传递给 Django 中的模板。 我应该从请求中获取它然后将其传递给模板吗? 如果是,我如何从视图中的请求中获取此变量?

【问题讨论】:

    标签: python django django-views django-templates python-requests


    【解决方案1】:
    # view 
    def get_client_ip(request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return render(request,'app/base.html',{'ip':ip})
    

    base.html:

    IP Address: {{ip}}
    

    【讨论】:

    • @AliHallaji 我已经更新了我的答案。
    猜你喜欢
    • 2014-06-09
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 2012-10-30
    • 2017-03-09
    • 1970-01-01
    相关资源
    最近更新 更多