[Answer]-Django Form, with Class Meta model based in class model, and more fields

1👍

What you really want here is to assign and save custom values to fields. To do this, you have to provide initial values and save method of form.

If you have a object to load data from, then you must pass it the form, for example:

neighbor = Neighborhood.objects.get(pk=1)
form = NeighborhoodForm(instance=neighbor)

The above code initialize the form with the object and fields related to it. But it still misses out on state field. To initialize it, you must pass initial value for it:

neighbor = Neighborhood.objects.get(pk=1)
state = neighbor.city.state
form = NeighborhoodForm(instance=neighbor, initial={'state': state})

OR you could override form’s __init__ method to extract value:

def __init__(self, *args, **kwargs):
    super(NeighborhoodForm, self).__init__(*args, **kwargs)
    if 'instance' in kwargs:
        state = self.instance.city.state
        self.fields['state'].initial = state

And you can save data similarly by overriding save method:

def save(self, *args, **kwargs):
    new_neighbor = super(NeighborhoodForm, self).save(*args, **kwargs)
    city = City.objects.create(state=self.cleaned_data['state'])
    new_neighbor.city = city
    new_neighbor.save()
    return new_neighbor
👤Arpit

Leave a comment