Question

I have an issue when my IP list from a text field goes into "ip_list_coices", instead of having each IP as a choice on one line.

The IPs need to be separate choices. I have a feeling this might be an easy fix, but can't seem to figure it out.

Below are examples:

This is what happens:

192.168.1.2 192.168.1.3 ... 192.168.1.5

This is what I wish for:

192.168.1.2

192.168.1.3

...

192.168.1.5

models.py

#IP Block Class
class IP_block(models.Model):

#ip block and range save function


def save(self, *args, **kwargs):

    slash = unicode(self.slash)

    self.broadcast_ip = broadcast
    self.subnet = subnet


    #rangeip for loop

    ip = IP(self.network + slash)


    for rangeip in ip[2:-1]:
        self.ip_range += "%s \n" %rangeip

    super(IP_block, self).save(*args, **kwargs)


network = models.IPAddressField(unique=True)
slash = models.ForeignKey(Subnet, verbose_name='CIDR')
subnet = models.CharField(max_length=64, blank=True)
gateway_ip = models.CharField(max_length=64, blank=True)
broadcast_ip = models.CharField(max_length=64, blank=True)
ip_range = models.TextField(blank=True, verbose_name='Available IP Range')
dslam = models.ManyToManyField(Dslam, verbose_name='Dslam', blank=True)
ip_list = models.CharField(max_length=128, blank=True)

class Meta:
    verbose_name_plural = 'IP Blocks'

def __unicode__(self):
    return self.network 

forms.py as recommended by Daniel

class IP_blockForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
    super(IP_blockForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.ip_range:

            #This is where I pass the list from the text field    

            ip_list_choices = [(self.instance.ip_range, self.instance.ip_range ),]

            self.fields['ip_list'] = forms.ChoiceField(choices=ip_list_choices)

    class Meta:
        model = IP_block
Was it helpful?

Solution

You can do something like this:

split_range = self.instance.ip_range.split(' ') #Or whatever your delimiter is
ip_list_choices = zip(split_range, split_range) #Gives you a tuple. 
self.fields['ip_list'] = forms.ChoiceField(choices=ip_list_choices)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top