保存前更改表单字段值

时间:2015-04-02 15:14:55

标签: django django-models django-forms django-views

我有一张表格:

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  

并在我的视图文件中构建它:

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"的数据库字段中。并且正在考虑在视图文件中执行此操作。

我尝试了一个简单的作业" test"在这里,我收到了错误:

'Applicant' object does not support item assignment
references_formset.instance['address'] = "test"; 

3 个答案:

答案 0 :(得分:3)

您可以使用以下内容:

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

答案 1 :(得分:0)

您可以通过模型的实例访问表单的字段。例如。而不是这一行:

references_formset.instance['address'] = "test";

试试这一行:

applicant.address = "test"

答案 2 :(得分:0)

易:

instance = form.instance
instance.user = request.user
instance.save()

但请注意,这不会检查is_valid()。如果要这样做,可以使用新值实例化表单:

# NOT TESTED, NOT SURE IF THIS WORKS...
form = MyForm(instance=instance)
if form.is_valid():
    form.save()