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?
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/dulMn79whF4J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
No comments:
Post a Comment