获取日期小部件以为美国用户显示美国日期 [英] Getting Date Widget to Display American Dates for American Users

查看:60
本文介绍了获取日期小部件以为美国用户显示美国日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can use this code to detect if the user is in America

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.

If the user is American I want to pass information to the template bootstrap_datetimepicker.html.

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

I am really unsure how to add information about the users country to the below code (which I got from another website).

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函数.

I want to run a different JQuery function for American users.

{% 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软件包geoip2来确定用户的位置(单击这两个链接以获取有关安装geoip2的说明,

You can use Python package geoip2 to determine the location of the user (click on these two links for instructions on installing geoip2, get-visitor-location & maxminds).

from django.contrib.gis.geoip import GeoIP2

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

Also IP address can be extracted by the request.

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

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

I was runnning my site on Localhost and had an issue with the above. So as a temporarily solution I did -

ip="72.229.28.185"

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

This was a random American IP address I found online.

g = GeoIP2()
g.country(ip)

执行 print(g)将为您提供类似的信息

Doing print(g) will give you something like this

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

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

In your widget constructor, determine the location. Then store the country code as a context variable, like so:

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的代码时,我遇到了一个错误.您可以在此处阅读更多有关该错误的信息.

When I was following Lewis' code I had an error. You can read more about the error here.

TypeError: 'NoneType' object is not subscriptable 

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

I made the below changes to Lewis' code.

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> 替换为表单字段的名称.

Then where you define the widget in the form, ensure you pass request into the widget to allow you to utilise it in the widget class thus determining location. Replace <field_name> with the name of the form field.

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)

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

Also in your view you must pass request into the given form:

form = YourForm(request=request)

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

Finally in the widget just use condition like so:

<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的方法.

I need to find a way of telling the back end if the date format is mm/dd/yyyy or 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'])

这篇关于获取日期小部件以为美国用户显示美国日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆