获取日期小部件以为美国用户显示美国日期

问题描述

我可以使用此代码来检测用户是否在美国

ip,is_routable = get_client_ip(request)
ip2 = requests.get('http://ip.42.pl/raw').text

if ip == "127.0.0.1":
    ip = ip2

Country = DbIpCity.get(ip,api_key='free').country

widgets.py

如果用户是美国人,我想将信息传递给模板bootstrap_datetimepicker.html.

我真的不确定如何在下面的代码(我从另一个网站获得)中添加有关用户所在国家的信息。

class BootstrapDateTimePickerInput(DateTimeInput):
    template_name = 'widgets/bootstrap_datetimepicker.html'

    def get_context(self,name,value,attrs):
        datetimepicker_id = 'datetimepicker_{name}'.format(name=name)
        if attrs is None:
            attrs = dict()
        attrs['data-target'] = '#{id}'.format(id=datetimepicker_id)
        # attrs['data-target'] = '#{id}'.format(id=datetimepicker_id)

        attrs['class'] = 'form-control datetimepicker-input'
        context = super().get_context(name,attrs)
        context['widget']['datetimepicker_id'] = datetimepicker_id
        return context

bootstrap_datetimepicker.html

我想为美国用户运行一个不同的JQuery函数

{% if America %}  
<script>
  $(function () {
    $("#{{ widget.datetimepicker_id }}").datetimepicker({
      // format: 'DD/MM/YYYY/YYYY HH:mm:ss',format: 'MM/DD/YYYY',changeYear: true,changeMonth: false,minDate: new Date("01/01/2015 00:00:00"),});
  });
</script>




{% else %}


<script>
  $(function () {
    $("#{{ widget.datetimepicker_id }}").datetimepicker({
      // format: 'DD/MM/YYYY/YYYY HH:mm:ss',format: 'DD/MM/YYYY',});
  });
</script>
{% endif %}
  

解决方法

您可以使用Python软件包geoip2确定用户的位置(单击这两个链接以获取有关安装geoip2的说明get-visitor-locationmaxminds)。

from django.contrib.gis.geoip import GeoIP2

该请求也可以提取IP地址。

ip = request.META.get("REMOTE_ADDR")

我在Localhost上运行我的网站时,遇到了上述问题。因此,我做了一个临时解决方案-

ip="72.229.28.185"

这是我在网上找到的随机美国IP地址。

g = GeoIP2()
g.country(ip)

print(g)会给你这样的东西

{'country_code': 'US','country_name': 'United States'}

在小部件构造函数中,确定位置。然后将国家/地区代码存储为上下文变量,如下所示:

from django.contrib.gis.geoip import GeoIP2

class BootstrapDateTimePickerInput(DateTimeInput):
    template_name = 'widgets/bootstrap_datetimepicker.html'

    def __init__(self,*args,**kwargs):
        self.request = kwargs.pop('request',None)
        super().__init__()

    def get_location(self):
        ip = self.request.META.get("REMOTE_ADDR")
        g = GeoIP2()
        g.country(ip)
        return g

    def get_context(self,name,value,attrs):
        datetimepicker_id = 'datetimepicker_{name}'.format(name=name)
        if attrs is None:
            attrs = dict()
        attrs['data-target'] = '#{id}'.format(id=datetimepicker_id)
        # attrs['data-target'] = '#{id}'.format(id=datetimepicker_id)

        attrs['class'] = 'form-control datetimepicker-input'
        context = super().get_context(name,attrs)
        context['widget']['datetimepicker_id'] = datetimepicker_id
        location = self.get_location()
        context['widget']['location'] = location['country_code']
        return context

当我遵循Lewis的代码时,我遇到了一个错误。您可以阅读有关错误here的更多信息。

TypeError: 'NoneType' object is not subscriptable 

我对Lewis的代码进行了以下更改。

def get_location(self):
    ip = self.request.META.get("REMOTE_ADDR") (or ip="72.229.28.185")
    g = GeoIP2()
    location = g.city(ip)
    location_country = location["country_code"]
    g = location_country
    return g
 
    location = self.get_location()
    context['widget']['location'] = location
    

然后在表单中定义窗口小部件的位置,确保将request传递到窗口小部件中,以允许您在窗口小部件类中使用它,从而确定位置。将<field_name>替换为表单字段的名称。

class YourForm(forms.Form):

    [...]

    def __init__(self,**kwargs):
        request = kwargs.pop('request',None)
        super().__init__(*args,**kwargs)
        self.fields[<field_name>].widget = BootstrapDateTimePickerInput(request=request)

在您看来,您还必须将请求传递给指定的表单:

form = YourForm(request=request)

最后在小部件中使用如下条件:

<script>
  $(function () {
    $("#{{ widget.datetimepicker_id }}").datetimepicker({
      // format: 'DD/MM/YYYY/YYYY HH:mm:ss',format: {% if widget.location == 'US' %}'MM/DD/YYYY'{% else %}'DD/MM/YYYY'{% endif %},changeYear: true,changeMonth: false,minDate: new Date("01/01/2015 00:00:00"),});
  });
</script>

其他问题

我需要找到一种告诉后端日期格式是mm / dd / yyyy还是dd / mm / yyyy的方法。

  def __init__(self,**kwargs):
    request = kwargs.pop('request',None)
    super().__init__(*args,**kwargs)
    self.fields['d_o_b'].widget = BootstrapDateTimePickerInput(request=request)
    (a) self.fields['d_o_b'].input_formats = ("%d/%m/%Y",)+(self.input_formats)
    (b) self.fields['d_o_b'].widget = BootstrapDateTimePickerInput(request=request,input_formats=['%d/%m/%Y'])