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.POST
にprof
を追加しようとしていますへは、それは私もまだ追加取得されていませんが、commit=False
prof
で保存しようとしている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()
質問の最後の部分で説明したようにこれを実行しました。 – Yax
@ Yax:いいえ、オブジェクトではなくフォームを保存します。 – sphere
なぜ私はそれを見ませんでしたか?悪い私。大変ありがとう。 – Yax