Re: Modelforms and class based views

52 views
Skip to first unread message

nkryptic

unread,
Jan 5, 2013, 6:20:14 PM1/5/13
to django...@googlegroups.com
Multiple forms with generic views are a problem - you can't really use the form processing ones as they expect a single form.  But, say you want a view that has a Pet form and and Owner form

class Owner(models.Model):
    name = models.CharField(max_length=100)
    email = models.CharField(max_length=100)

class Pet(models.Model):
    owner = models.ForeignKey(Owner)
    name = models.CharField(max_length=100)
    breed = models.CharField(max_length=100)

class OwnerForm(forms.ModelForm):
    class Meta:
        model = Owner

class PetForm(forms.ModelForm):
    class Meta:
        model = Pet
        exclude = ('owner',)

class PetAndOwnerRegisterView(TemplateView):
    template_name = 'register.html'
    
    def get(self, request):
        forms_dict = self.get_forms()
        return self.render_to_response(forms_dict)
    
    def post(self, request):
        forms_dict = self.get_forms(request.POST)
        if forms_dict['owner_form'].is_valid() and forms_dict['pet_form'].is_valid():
            forms_dict['owner_form'].save()
            forms_dict['pet_form'].save()
            return HttpResponseRedirect(reverse('success_view'))
        return self.render_to_response(forms_dict)
    
    def get_forms(self, data=None):
        owner = Owner()
        pet = Pet(owner=owner)
        owner_form = OwnerForm(data, instance=owner)
        pet_form = PetForm(data, instance=pet)
        forms_dict = {
            'owner_form': owner_form,
            'pet_form': pet_form,
        }
        return forms_dict

The tricky part is in the get_forms method, with populates the instances for each form.  The Pet model is instantiated with an unsaved Owner model - the same one that is used in the owner form.  That ties them together.

Then, in the post method, you simply need to save the owner_form first - so that a primary key will be populated - and then the pet form can be saved and the pet tied to that owner.

On Friday, January 4, 2013 11:51:41 AM UTC-5, Marco A Morales wrote:
Hi everyone,

I'm still wraping my head around class based views and I'm trying my first project with class based views. I'm having trouble deciding how to write a view that will display a two Modelforms, one having a foreign key over the other. 

I will need to do the .save(commit=False) part to save my first model and then be able to save the model with foreign key.

How would you guys do it? 

Pedro J. Aramburu

unread,
Jan 6, 2013, 9:46:40 AM1/6/13
to django...@googlegroups.com
Have you tried merging the forms with formsets?

Pedro J. Aramburu

unread,
Jan 6, 2013, 9:48:52 AM1/6/13
to django...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages