Django ModelForm not saving data that is added to request.POST or through


April 2019


546 time


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.

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)

class ModuleForm(ModelForm):
    class Meta:
        model = Module
        fields = ['name',  'semester']

I have tried adding prof to request.POST before passing it to moduleform but it saves every other data submitted from the HTML except prof

prof = Profile.objects.get(user=request.user)
if request.method == 'POST':
    mtb = request.POST._mutable
    request.POST._mutable = True
    request.POST['prof'] = str(
    request.POST._mutable = mtb
    moduleform = ModuleForm(request.POST)

I have also tried saving with commit=False but prof is still not getting added. = prof

1 answers


See this example from django's official documentation:

form = PartialAuthorForm(request.POST)
author =
author.title = 'Mr'

In your case (untested):

if request.method == 'POST':
    form = ModuleForm(request.POST)
    object = = Profile.objects.get(user=request.user)

EDIT: To clarify your comment on my answer: = prof

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