Django one form for two models
Posted
by martinthenext
on Stack Overflow
See other posts from Stack Overflow
or by martinthenext
Published on 2010-04-01T21:37:16Z
Indexed on
2010/04/01
21:43 UTC
Read the original article
Hit count: 660
Hello!
I have a ForeignKey relationship between TextPage and Paragraph and my goal is to make front-end TextPage creating/editing form as if it was in ModelAdmin with 'inlines': several field for the TextPage and then a couple of Paragraph instances stacked inline. The problem is that i have no idea about how to validate and save that:
@login_required
def textpage_add(request):
profile = request.user.profile_set.all()[0]
if not (profile.is_admin() or profile.is_editor()):
raise Http404
PageFormSet = inlineformset_factory(TextPage, Paragraph, extra=5)
if request.POST:
try:
textpageform = TextPageForm(request.POST)
# formset = PageFormSet(request.POST)
except forms.ValidationError as error:
textpageform = TextPageForm()
formset = PageFormSet()
return render_to_response('textpages/manage.html', { 'formset' : formset,
'textpageform' : textpageform,
'error' : str(error),
}, context_instance=RequestContext(request))
# Saving data
if textpageform.is_valid() and formset.is_valid():
textpageform.save()
formset.save()
return HttpResponseRedirect(reverse(consults))
else:
textpageform = TextPageForm()
formset = PageFormSet()
return render_to_response('textpages/manage.html', { 'formset' : formset,
'textpageform' : textpageform,
}, context_instance=RequestContext(request))
I know I't a kind of code-monkey style to post code that you don't even expect to work but I wanted to show what I'm trying to accomplish. Here is the relevant part of models.py:
class TextPage(models.Model):
title = models.CharField(max_length=100)
page_sub_category = models.ForeignKey(PageSubCategory, blank=True, null=True)
def __unicode__(self):
return self.title
class Paragraph(models.Model):
article = models.ForeignKey(TextPage)
title = models.CharField(max_length=100, blank=True, null=True)
text = models.TextField(blank=True, null=True)
def __unicode__(self):
return self.title
Any help would be appreciated. Thanks!
© Stack Overflow or respective owner