Create objects of a model of a parent and children from one form

My model has a parent object, each of which can have zero or more child objects connected by a foreign key.

My ModelForm autogeneration is great for a parent, but I would like the user to be able to create one or more child objects at the same time as the parent. Note that I do not mean the choice of pre-existing children - I mean the creation of children from scratch ...

Currently, I use a lot of django magic to get the form that appears with a very small template from me: I understand that you probably have to change to do this!

Here is the idea of โ€‹โ€‹what I have at the moment:

# urls.py
(r'^create/$',
    CreateAppView.as_view(
        model=App,
        template_name='edit.html')),

 

# edit.html
<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
<input type="submit" value="Submit" />
</form>

 

# model
class App(models.Model):
    name = models.CharField(max_length=100)

class Activation(models.Model):
    app = models.ForeignKey(App)

 

# 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)
+5
3

, .

+3

?

, , .

- :

# edit.html
<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ appform.as_p }}
    {{ appform2.as_p }}
<input type="submit" value="Submit" />
</form>

:

appform= AppForm(request.POST, prefix="1")
appform2= AppForm(request.POST, prefix="2")

:

appform= AppForm(request.POST, prefix="app")
spamform = SpamForm(request.POST, prefix="spam")

urls.py, /... thingy;)

+2

-, SO-:

0

All Articles