保存前向 ModelForm 对象添加数据 [英] Add data to ModelForm object before saving
本文介绍了保存前向 ModelForm 对象添加数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个看起来像这样的表单:
Say I have a form that looks like this:
forms.py
class CreateASomethingForm(ModelForm):
class Meta:
model = Something
fields = ['field2', 'field3', 'field4']
我希望表单具有这三个字段.但是我的 Something
类也有 field1
.我的问题是 - 如果我不使用 ModelForm
收集数据,我该如何将数据添加到 field1
.我尝试做这样的事情,但它不起作用,我不确定解决这个问题的正确方法:
I want the form to have these three fields. However my Something
class also has field1
. My question is - how do I add data to field1
, if I am not using the ModelForm
to collect the data. I tried doing something like this, but it isn't working and I am unsure on the proper way to solve this:
views.py
def create_something_view(request):
if (request.method == 'POST'):
# Create an object of the form based on POST data
obj = CreateASomething(request.POST)
# ** Add data into the blank field1 ** (Throwing an error)
obj['field1'] = request.user
# ... validate, save, then redirect
我收到的错误是:
TypeError: 'CreateAClassForm' object does not support item assignment
在 Django 中,在保存之前将数据分配给 ModelForm
对象的正确方法是什么?
In Django, what is the proper way to assign data to a ModelForm
object before saving?
推荐答案
form = CreateASomething(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.field1 = request.user
obj.save()
这篇关于保存前向 ModelForm 对象添加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文