If anyone is interested, I’ve made progress using an inline form set
class ArticleCreateView(LoginRequiredMixin,CreateView):
template_name = 'articles/article_add.html'
model = Article
form_class = ArticleForm
success_url = reverse_lazy('index')
SectionFormSet = inlineformset_factory(Article, Section, extra=1, fields=('content',))
def get(self, request, *args, **kwargs):
print('get called on article create view')
self.object = None #what does this achieve?
return self.render_to_response(
self.get_context_data(form=self.get_form(),
section_form=self.SectionFormSet(),
))
def post(self, request, *args, **kwargs):
print('post called on article create view')
self.object = None
form = self.get_form()
section_form = self.SectionFormSet(self.request.POST)
if (form.is_valid() and section_form.is_valid()):
return self.form_valid(form, section_form)
else:
return self.form_invalid(form, section_form)
def form_valid(self, form, section_form):
form.instance.author = self.request.user
if section_form.is_valid():
self.object = form.save()
section_form.instance = self.object
section_form.save()
#return super().form_valid(form)
return self.render_to_response( self.get_context_data(form=form,
section_form=section_form,
))
def form_invalid(self, form, article_form):
return self.render_to_response(
self.get_context_data(form=form,
article_form=article_form))
It basically works for one inline form for section.
However, there are issues . If you look at the last couple of lines
return self.render_to_response( self.get_context_data(form=form,
section_form=section_form,
))
If I use the top line it redirects to success url. BUT… does this
saving article model
saving section model
saving article model
using the 2nd line redirects back to where you’ve just added the article – which is not what I want but only save the article model once…
sigh.
I’ve kind of cobbled this together from various other forums, and a little bit confused if I’m doing it right. There’s code in here I’m slightly suspicious about to say the least.