Django在保存之前表单更改实例属性

时间:2014-11-12 09:49:57

标签: python django forms

正如我在标题中所说:

def profile(request, template='/member/profile.html'):

    .....

    member = get_object_or_404(Member, id=id)

    # >>> member.qrcode
    #  <ImageFieldFile: upload/qrcode/2014-11-12/99_1.41578387725e12.jpg>


    if request.method == 'POST':
        form = ProfileForm(request.POST, request.FILES, instance=member)

        # >>> member.qrcode
        #  <ImageFieldFile: 20140901192104.png>

        if form.is_valid():
            member = form.save(commit=False)
.....

表单实例memberform = ProfileForm(request.POST, request.FILES, instance=member)之后立即更改。
因为我只想在member.type == 1时保存成员,并根据比较memberform.cleaned_data中的某些数据的结果更改某些字段。

我认为在调用member之前更改form.save()的属性非常糟糕 我怎样才能改变它?

1 个答案:

答案 0 :(得分:0)

  

如果使用commit = False调用save(),则它将返回尚未保存到数据库的对象。

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

member = form.save(commit=False)
if member.type == 1:
    member.save()