gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:21:15 24 4
gpt4 key购买 nike

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 !!!!!
......

edit表单中,点击提交按钮更新数据库时,form.is_valid()返回false,因为unique_together校验,如何解决?

最佳答案

您应该将要编辑的模型实例传递给 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():
...

关于django,使用唯一字段编辑表单,form.is_valid 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29222886/

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