django,使用唯一字段编辑表单,form.is_valid return false
django,edit form with unique field, form.is_valid return false
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() return 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():
...
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() return 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():
...