gpt4 book ai didi

django - 保存前更改表单字段值

转载 作者:行者123 更新时间:2023-12-02 06:56:57 25 4
gpt4 key购买 nike

我有一个表格:

class ReferencesForm(forms.ModelForm):

error_css_class = 'error' #set some css when an error
contactName = forms.CharField(label='Contact Name:')
company = forms.CharField(label='Company:')
address = forms.CharField(label='Address:')
telephoneNumber = forms.CharField(label='Telephone Number:')

class Meta:
fields = '__all__'
model = References

def __init__(self, *arg, **kwarg):
super(ReferencesForm, self).__init__(*arg, **kwarg)
self.empty_permitted = True
def clean(self):
""" Custom validation for fields
"""
cleaned_data = super(ReferencesForm, self).clean()

return self.cleaned_data

并在我的 View 文件中构建它,如下所示:
ReferencesInlineFormSet = inlineformset_factory(
Applicant, References, form=ReferencesForm, extra=1, can_delete=False)
...
if request.method == 'POST':
references_formset = ReferencesInlineFormSet(
request.POST, instance=applicant)

if (references_formset.is_valid()):
references_formset.instance['address'] = "test";
references_formset.save();

我认为申请人模型在这里并不重要,但如有必要,我可以稍后添加。

我想将一些地址字段(addr1、addr2、town 等)合并到一个名为“address”的数据库字段中,并且正在考虑在 View 文件中这样做。

我在这里尝试了一个带有“test”的简单分配,但收到了错误:
'Applicant' object does not support item assignment
references_formset.instance['address'] = "test";

最佳答案

你可以使用这样的东西:

if form.is_valid():
obj = form.save(commit=False)
obj.address = "test"
obj.save()

关于django - 保存前更改表单字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29416478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com