简体   繁体   中英

Django ModelForm not saving data that is added to request.POST or through form.save(commit=False)

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.

models.py :

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)

forms.py :

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

views.py :

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(prof.id)
    request.POST._mutable = mtb
    moduleform = ModuleForm(request.POST)
    moduleform.save()

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

moduleform.save(commit=False)
moduleform.prof = prof
moduleform.save()

See this example from django's official documentation :

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

In your case (untested):

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

EDIT: To clarify your comment on my answer:

moduleform.save(commit=False)
moduleform.prof = prof
moduleform.save()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM