One mold for two models

UPDATE The problem is solved, all the code that you see works.

Hello!

I have a ForeignKey relationship between TextPage and Paragraph, and my goal is to make the front-end TextPage to create / edit the form as if it were in ModelAdmin with "inlines": several fields for TextPage, and then several Paragraph instances laid out in stack in line. The problem is that I have no idea how to check and save this:

@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, fields=('title', 'text', ), extra=5) textpage = TextPage() if request.POST: textpageform = TextPageForm(request.POST, instance=textpage, prefix='page') formset = PageFormSet(request.POST, instance=textpage, prefix='paragraphs') # Saving data if textpageform.is_valid(): textpageform.save() if formset.is_valid(): formset.save() return HttpResponseRedirect(reverse(consult_categories)) else: textpageform = TextPageForm(instance=textpage, prefix='page') formset = PageFormSet(instance=textpage, prefix='paragraphs') return render_to_response('textpages/manage.html', { 'formset' : formset, 'textpageform' : textpageform, }, context_instance=RequestContext(request)) 

I know this is a kind of code monkey style for publishing code that you don't even expect to work, but I wanted to show what I'm trying to execute. 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 greatly appreciated. Thanks!

UPDATE Instance references added but still not working - result in ValidationError for this line:

 formset = PageFormSet(request.POST, instance=textpage, prefix='paragraphs') 

Any ideas?

+4
source share
1 answer

Updated code with instance links really works! The problem was in the template: I forgot ManagmentForm. Here is the template code:

 {% extends "site_base.html" %} {% block body %} <form action="" method="post"> {{ textpageform.as_p }} {{ formset.management_form }} {% for form in formset.forms %} <p>{{ form.as_p }}</p> {% endfor %} <input type="submit" value="Go" /> {% endblock %} 

Hope this example helps newbies like me :)

+2
source

Source: https://habr.com/ru/post/1305806/


All Articles