2016-09-27 3 views
1

私はdjangoフォームを表示するビューに提出し、それを保存する前にいくつかのデータを追加したい動作していないようです。Django ModelFormは、request.POSTまたはform.save(commit = False)に追加されたデータを保存しません

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

私はそれを渡す前request.POSTprofを追加しようとしていますへは、それは私もまだ追加取得されていませんが、commit=Falseprofで保存しようとしている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() 

以外HTMLから提出され、他のすべてのデータが保存されます。

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

答えて

1

django's official documentationからこの例を参照してください:あなたのケースで

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

(未テスト):

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

EDIT: 私の答えにあなたのコメントを明確にする:

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

フォームがの一部ではないため、フォームにprofを保存しないため、機能しません。このため、モデルレベルでprofを設定する必要があります。

+0

質問の最後の部分で説明したようにこれを実行しました。 – Yax

+1

@ Yax:いいえ、オブジェクトではなくフォームを保存します。 – sphere

+0

なぜ私はそれを見ませんでしたか?悪い私。大変ありがとう。 – Yax

関連する問題