tmoe
tmoe

Reputation: 303

Django: Convert string of numbers to ip address in dynamic listview

I have a django website containing a page with a listview. The list, created from a object-list in a for loop {% for betr in object_list %} contains a field with ip addresses like <td>{{ betr.netmask }}</td>. The data in the object list is provided as a string of numbers like "123456789111".

What is the best way to display this as 123.456.789.111.

Tried lambda or normal functions imported as utils, but always ran into errors.

Upvotes: 0

Views: 256

Answers (3)

Nico Griffioen
Nico Griffioen

Reputation: 5405

I don't think this is possible, because a number could translate to multiple valid IP-addresses. For instance a number like 192168211 could be written as 192.168.2.11 or 192.168.21.1.

My advice is, either store the IP-address as a string, or as the actual decimal number representation. (An IP-address is after all just a 4 byte value. In that case 192.168.2.11 would translate to 3232236043, and 192.168.21.1 to 3232240897)

Upvotes: 0

ahmed oraby
ahmed oraby

Reputation: 1

Python 3 has ipaddress module which features very simple conversion:

    a="123456789111"
    int(ipaddress.IPv4Address(a))

Upvotes: 0

Rakesh
Rakesh

Reputation: 82765

Try creating a custom template tag.

Ex:

from django import template
import ipaddress  #Python 3

register = template.Library()
def toIp(value):
    return ipaddress.ip_address(value)

In template

{{ betr.netmask |toIp }}

More Info

Upvotes: 1

Related Questions