从视图中使用Django保存表单

问题描述 投票:0回答:1

我需要从我的观点中保存一个带有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'

django django-forms django-views
1个回答
0
投票

如果要将数据保存到Django视图中的表单,则需要在表单上发送字典,然后使用is_valid()方法验证此数据:

form = NewSubject({
    'owner': request.user.id,
    #Another fields
    'teacher': teacher,
    'group': request.user.group
})
if form.is_valid():
    form.save()
© www.soinside.com 2019 - 2024. All rights reserved.