Auto-fill Django OneToOneField
<p>This maybe a simple question, but I do not have any idea how to do this.
I have two models in Django.</p>

<pre><code>class ModelA(models.Model):
    some_member = models.Charfield(...)

class ModelB(models.Model):
    model = OneToOneField(ModelA)
    other_member = models.Charfield(...)
</code></pre>

<p><code>ModelA</code> is filled in by a ModelForm and then redirect to the form for <code>ModelB</code>.
How can I Autofill the <code>OneToOneField</code> based on the previous form.
Thank you for helping.</p>

<hr>

<p>I am doing it like this now</p>

<pre><code>class ModelBView(CreateView):
.......
    def form_valid(self, form):
        model_b = form.save(commit=False)
        model_a_form = ModelAForm(self.request.POST)
        model_b.model = model_a_form.save(commit=False)
        model_b.save()
        return super(ModelBView, self).form_valid(form)
</code></pre>

<p>but get the error: "...could not be created because the data didn't validate."</p>

<p>So here the problem is, I simply can get the data from the previous form by request.POST.
How can I get this data.</p>

<p>It depends on what you want exactly.</p>

<p>If you want to auto-fill the field in the second form, then you can use the <code>initial</code> keyword argument when instantiating the form for ModelB (e.g. in your view); like this:</p>

<pre><code>def my_view(request):
    """
    Save data to ModelA and show the user the form for ModelB
    """
    if request.method == 'POST':
       # Save ModelA instance
       model_a_form = ModelFormA(request.POST)
       if model_a_form.is_valid():
           model_a_instance = model_a_form.save()

           # Once saved, show the user the form for ModelB, prefilled
           # with the result from the previous form
           model_b_form = ModelFormB(initial={'model': model_a_instance})

           # etc. Render the page as usual
       else:
           # ...
   elif request.method == 'GET':
       # ...
</code></pre>

<p>If, on the other hand, you don't want ModelA to appear in the second form as a field, but still link it to the resulting instance, you can do something like this when handling the response of the second form.</p>

<pre><code># ... instance of first model is saved in `model_a_instance`

# Initiate an empty instance of ModelB, with the value of `model` field set to model_a_instance
model_b_instance = ModelB(model=model_a_instance)

# Provide it as an instance to your model form
model_b_form = ModelFormB(request.POST, instance=model_b_instance)

if model_b_form.is_valid():
     # Everything else should work fine.
</code></pre>

<p>Hope this helps.</p>

python django forms