You have many fairly basic errors here. For example, in your suggested syntax:
for rangeip in enumerate(whatever):
IP_CHOICES = (do_something)
It should be obvious to you that you are simply overwriting IP_CHOICES each time through the loop. At the end of the loop, it will simply have the value of the last iteration, which isn't by itself in a suitable format for choices
.
You have this same pattern a number of times. Please think about what it is actually doing.
But there's an even worse error in your save function, where you have this line:
ip_list = models.CharField(choices=IP_CHOICE, max_length=128, blank=True)
I have absolutely no idea what you think that is doing. You can't define a field in the middle of a save method. You can set a field's value, but you can't suddenly define a new field (again, please think about it: how would that work with the database? And remember fields are class-level attributes: all instances of that model need to have the same field selection).
It's almost impossible to understand what you are actually trying to do. I think you are trying to provide a choice of IP addresses for one field in the model (ip_list
), once the user has set the range in another field (ip_range
). (It would have been useful if you'd stated that explicitly up front.)
The place to do this is in the form, not in the model. Setting choices
on a model field is really just a shortcut to setting them on forms automatically created from that model, but if you need to do something dynamic you need to define the form yourself and put the logic there. I guess it would be something like this:
class IPBlockForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(IPForm, self).__init__(*args, **kwargs)
if self.instance and self.instance.ip_range:
ip_list_choices = get_ip_list_from_wherever(self.instance_ip_range)
self.fields['ip_list'] = forms.ChoiceField(choices=ip_list_choices)
class Meta:
model = IP_block
But naturally you need to fix the other logic errors in your save
method, which I mention above, first.