我需要从视图中使用Django保存表单。我从API中获取数据并需要直接保存在我的数据库中:
form = NewSubject()
#API request
form.owner = request.user
#Another fields
form.teacher = teacher
form.group = request.user.group
form.save()
但我明白了:
异常值:NOT NULL约束失败:subjects_subject.owner_id
所以我尝试了另一种方式:
form = NewSubject()
#API request
subject = form.save(commit=False)
subject.owner = request.user
#Another fields
subject.teacher = teacher
subject.group = request.user.group
form.save()
现在,表单已保存,但我总是得到错误:
例外值:' NewSubject'对象没有属性' cleaning_data'
答案 0 :(得分:0)
如果要将数据保存到Django视图中的表单中,您需要在表单上发送字典,然后使用is_valid()
方法验证此数据:
form = NewSubject({
'owner': request.user.id,
#Another fields
'teacher': teacher,
'group': request.user.group
})
if form.is_valid():
form.save()