![](/img/trans.png)
[英]Django ModelForm not saving data to database, Form.save is not working?
[英]Django ModelForm not saving data that is added to request.POST or through form.save(commit=False)
我有 django 表單提交給顯示它的視圖,並想在保存之前向其中添加一些數據,但它似乎不起作用。
模型.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)
形式.py :
class ModuleForm(ModelForm):
class Meta:
model = Module
fields = ['name', 'semester']
視圖.py :
在將prof
傳遞給moduleform
之前,我嘗試將prof
添加到request.POST
但它保存了從HTML提交的所有其他數據,除了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()
我也試過用commit=False
保存,但仍然沒有添加prof
。
moduleform.save(commit=False)
moduleform.prof = prof
moduleform.save()
請參閱django 官方文檔中的此示例:
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()
編輯:澄清您對我的回答的評論:
moduleform.save(commit=False)
moduleform.prof = prof
moduleform.save()
不起作用,因為表單永遠不會在實例上保存prof
,因為它不是fields
一部分。 這就是為什么您必須在模型級別設置prof
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.