本文介绍了在保存前将数据添加到ModelForm对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个这样的表单:forms.py
$ _ code> class CreateASomethingForm(ModelForm):
class Meta:
model = Something
fields = ['field2','field3','field4' ]
我希望表单有这三个字段。然而,我的某些
类也有 field1
。我的问题是 - 如果我不使用 ModelForm
来收集数据,我如何将数据添加到 field1
中。我试着做这样的事情,但是它不起作用,我不确定正确的方法来解决这个问题:
views.py
def create_something_view(request):
if(request.method =='POST'):
#根据POST数据创建表单的对象
obj = CreateASomething(request.POST)
#**将数据添加到空白字段1 **(抛出错误)
obj [' field1'] = request.user
#...验证,保存,然后重定向
我收到的错误是:
TypeError:'CreateAClassForm'对象不支持项目分配
在Django中,在保存之前,将数据分配给 ModelForm
对象的正确方法是什么? ?
解决方案
form = CreateASomething(request.POST)
如果表单。 is_valid():
obj = form.save(commit = False)
obj.field1 = request.user
obj.save()
Say I have a form that looks like this:
forms.py
class CreateASomethingForm(ModelForm):
class Meta:
model = Something
fields = ['field2', 'field3', 'field4']
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
The error I receive is:
TypeError: 'CreateAClassForm' object does not support item assignment
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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!