checking an IP range

158 views
Skip to first unread message

Ken Lacey

unread,
Apr 9, 2010, 8:41:53 AM4/9/10
to Django users
Hi

I am trying to check an IP so some information will/will not be
displayed based on the first 8 digites of the remote IP address.

I have a vairable ip_address which contains the remote address and a
vairable accept_ip with a value "192.168." but when I carry out the
following it is not working correctly.

{% ifequal ip_address|slice:"8" accept_ip %}
do something
{% endifequal %}


I have also tried
{% ifequal ip_address|slice:"8" "192.168." %}
do something
{% endifequal %}

and
{% ifequal ip_address|slice:"8"|stringformat:"s" "192.168." %}
do something
{% endifequal %}

the same results appaear whether the ip_address is 192.168..... or any
other range.

Thanks

Ken

Tom Evans

unread,
Apr 9, 2010, 9:11:01 AM4/9/10
to django...@googlegroups.com

You shouldn't do logic like this in the template - as you can see, it
is quite hard!

The simplest option is to calculate whether that IP is in the correct
range in the view and set a variable in the context to indicate that.
If you are iterating through a list of things, you would probably want
to write a templatetag to do the comparison for you.

PS:
Treating IP addresses as strings, and performing string manipulation
to test belonging is poor form. I would recommend the netaddr library,
and write code like this:

>>> import netaddr
>>> range = netaddr.IPNetwork('192.168.0.0/16')
>>> addr = netaddr.IPAddress('192.168.12.4')
>>> addr in range
True


Cheers

Tom

Reply all
Reply to author
Forward
0 new messages