Django ModelForm not saving data that is added to request.POST or through form.save(commit=False)
<p>I have django form that submitted to the view that displays it and want to add some data to it before saving it but it seems not be working.</p>

<p><strong>models.py</strong>:</p>

<pre><code>from django.contrib.auth.models import User
from django.db import models

class Profile(models.Model):
    user = models.OneToOneField(User)
    display_name = models.CharField(max_length=145, blank=True, null=True)
    bio = models.CharField(max_length=1000, blank=True, null=True)

class Module(models.Model):
    name = models.CharField(max_length=45)
    semester = models.CharField(max_length=40)
    prof = models.ForeignKey('Profile', null=True, blank=True)
</code></pre>

<p><strong>forms.py</strong>:</p>

<pre><code>class ModuleForm(ModelForm):
    class Meta:
        model = Module
        fields = ['name',  'semester']
</code></pre>

<p><strong>views.py</strong>:</p>

<p>I have tried adding <code>prof</code> to <code>request.POST</code> before passing it to <code>moduleform</code> but it saves every other data submitted from the <em>HTML</em> except <code>prof</code></p>

<pre><code>prof = Profile.objects.get(user=request.user)
if request.method == 'POST':
    mtb = request.POST._mutable
    request.POST._mutable = True
    request.POST['prof'] = str(prof.id)
    request.POST._mutable = mtb
    moduleform = ModuleForm(request.POST)
    moduleform.save()
</code></pre>

<p>I have also tried saving with <code>commit=False</code> but <code>prof</code> is still not getting added.</p>

<pre><code>moduleform.save(commit=False)
moduleform.prof = prof
moduleform.save()
</code></pre>

<p>See this example from <a href="https://docs.djangoproject.com/es/1.10/topics/forms/modelforms/#the-save-method" rel="nofollow">django's official documentation</a>:</p>

<pre><code>form = PartialAuthorForm(request.POST)
author = form.save(commit=False)
author.title = 'Mr'
author.save()
</code></pre>

<p>In your case (untested):</p>

<pre><code>if request.method == 'POST':
    form = ModuleForm(request.POST)
    object = form.save(commit=False)
    object.prof = Profile.objects.get(user=request.user)
    object.save()
</code></pre>

<p><strong>EDIT:</strong>
To clarify your comment on my answer: </p>

<pre><code>moduleform.save(commit=False)
moduleform.prof = prof
moduleform.save()
</code></pre>

<p>Does not work because the form will never save <code>prof</code> on the instance because it is not part of the <code>fields</code>. This is why you HAVE TO set the <code>prof</code> on the model-level.</p>

python django django-forms