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

2024-04-27 15:00:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以用这个代码来检测用户是否在美国

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\u 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 %}
  

Tags: 用户nameipidformatgetifcontext
1条回答
网友
1楼 · 发布于 2024-04-27 15:00:59

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

from django.contrib.gis.geoip import GeoIP2

也可以通过请求提取IP地址

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

我在本地主机上运行我的站点,但遇到了上述问题。所以作为一个暂时的解决方案,我做了-

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

当我遵循刘易斯的密码时,我犯了一个错误。您可以阅读有关错误here的更多信息

TypeError: 'NoneType' object is not subscriptable 

我对刘易斯的密码做了如下修改

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

相关问题 更多 >