Question

I have different models in my app, the main model having multiple instances of some other models.

models.py:

class Person(models.Model):
    ...

class Pet(models.Model):
    owner = models.ForeignKey(Person)
    ...

forms.py:

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person


PetFormSet = inlineformset_factory(Person, Pet, extra = 1)

views.py:

def add_template(request):
    person_form = PersonForm(prefix = 'person_form')
    pet_form = PetFormSet(instance = Person(), prefix = 'pet_form')
    ... # check is_valid(), render when no POST data is present, etc.

The point is the addition works perfectly, storing each instance in the corresponding database table, etc. I use jquery.formset-1.2.js to manage the dynamical addition-deletion of forms in the "add.html".

But I later want to edit the stored info through a view, i.e., load the data from the object I pass in the request, and render the formsets with the data obtained from the database (if there are 3 pets related to the person being editted, display 3 form instances of "Pet" with their value displayed).

I would like to also add new Pets and remove existing ones, as well as changing existing field values.

I have tried with querysets in the FormSet creation, but it doesn't display anything.

Any idea how to ease this issue? Maybe using an app for an easier formset management?

Thank you

Was it helpful?

Solution

I'm not sure if I understand your problem correctly. If you want to display all Pets that belong to the Person:

def show_pets(request, person_id=None):
person = get_object_or_404(Person.objects.select_related(), id=person_id)
if request.method == 'POST':
   person_form = PersonForm(request.POST, instance=person)
   pet_formset = PetFormSet(request.POST, instance=person)
   # Rest of your code here
else:
   person_form = PersonForm(instance=person)
   pet_formset = PetFormSet(instance=person)
return render_to_response('your_template.html', {'person_form': person_form,
                                                        'pet_formset': pet_formset)})

Then you just need to render both forms in your template and add add and delete functionality

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top