Note that there are some explanatory texts on larger screens.

plurals
  1. POCreate parent and children model objects from one form submission
    text
    copied!<p>My model has a parent object, each of which can have zero or more child objects associated by foreign key.</p> <p>My auto-generating ModelForm works great for the parent object, but I'd like the user to be able to create one or more of the child objects at the same time as creating the parent. Note, I don't mean pick from pre-existing child objects - I do mean create child objects from scratch...</p> <p>I'm currently using lots of django magic to get the form to appear with very little boilerplate from me: I realise that will probably have to change to get this done!</p> <p>Here's an idea of what I have at the moment:</p> <pre><code># urls.py (r'^create/$', CreateAppView.as_view( model=App, template_name='edit.html')), </code></pre> <p>&nbsp;</p> <pre><code># edit.html &lt;form action="" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} {{ form.as_p }} &lt;input type="submit" value="Submit" /&gt; &lt;/form&gt; </code></pre> <p>&nbsp;</p> <pre><code># model class App(models.Model): name = models.CharField(max_length=100) class Activation(models.Model): app = models.ForeignKey(App) </code></pre> <p>&nbsp;</p> <pre><code># view class AppForm(ModelForm): class Meta: model = App class CreateAppView(CreateView): def post(self, request, *args, **kw): form = AppForm(request.POST) if form.is_valid(): app = form.save() return HttpResponseRedirect(reverse('app_detail', args=(app.id,))) else: return super(CreateAppView, self).post(request, *args, **kw) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload