【问题标题】:Getting Date Widget to Display American Dates for American Users获取日期小部件以显示美国用户的美国日期
【发布时间】:2020-11-30 11:54:04
【问题描述】:

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

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, value, 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',
      changeYear: true,
      changeMonth: false,
      minDate: new Date("01/01/2015 00:00:00"),
   });
  });
</script>
{% endif %}
  

【问题讨论】:

    标签: python python-3.x django date widget


    【解决方案1】:

    您可以使用 Python 包 geoip2 来确定用户的位置(点击这两个链接获取安装 geoip2 的说明,get-visitor-location & maxminds)。

    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, value, 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 传递到小部件中,以允许您在小部件类中使用它,从而确定位置。将&lt;field_name&gt; 替换为表单字段的名称。

    class YourForm(forms.Form):
    
        [...]
    
        def __init__(self, *args, **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, *args, **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'])
    

    【讨论】:

    • 我收到错误 widget=BootstrapDateTimePickerInput(request=request) NameError: name 'request' is not defined
    • 我看到了这条评论 - 您在构建表单类时试图传递请求。此时没有请求。该请求仅存在于您的视图函数中。因此,您应该在构造表单实例时在视图函数中传递请求。要预填充表单,您可以使用表单构造函数的初始关键字。它需要一个字段名称和值的字典作为输入。
    • 没错,是的,请允许我编辑我的答案以适应表单中的请求。
    • 我为表单和查看代码 sn-ps 添加了一个部分。还替换了 GeoIP 的用法到 GeoIP2 这是一个错字。
    • 我收到错误消息 - ip = self.request.META.get("REMOTE_ADDR") AttributeError: 'NoneType' object has no attribute 'META'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多