django,用唯一字段编辑表单,form.is_valid返回false

时间:2015-03-24 00:26:13

标签: django forms unique

class modelA(..):
    fieldA = ...     unique
    fieldB = ...     unique

    class Meta:
        unique_together = [['fieldA','fieldB']]


class formA(modelform):

    class Meta:
        model = modelA
        field = ['fieldA','fieldB']


def viewA(request):
    if request.method == 'POST':
        form = formA(request.POST)
        if form.is_valid():          here return false !!!!!
            ......

编辑表单中,当单击提交按钮更新数据库时,form.is_valid()返回false因为unique_together检查,如何解决问题?

1 个答案:

答案 0 :(得分:3)

您应该将instance参数传递给您要编辑的模型实例:

from django.shortcuts import get_object_or_404

def viewA(request, pk):
    obj = get_object_or_404(modelA, pk=pk)
    if request.method == 'POST':
        form = formA(request.POST, instance=obj)
        if form.is_valid():
            ...