我有一个Device
,许多Scans
与之关联并通过表单创建。
class Device(models.Model):
uuid = models.UUIDField(primary_key=True, verbose_name="UUID")
# fields omitted for brevity
class Scan(models.Model):
device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL)
通过表单提交扫描时,设备的UUID将包含在POST数据中。如果UUID存在,则扫描将与现有设备关联,否则将创建一个新设备,并将扫描与该设备关联。
我正在使用通用形式:
class DeviceForm(ModelForm):
class Meta:
model = Device
class ScanForm(ModelForm):
class Meta:
model = Scan
有问题的视图是这样的:
@login_required
def scan_test(request):
if request.method == 'GET':
device_form = DeviceForm()
scan_form = ScanForm()
# otherwise create a form instance and populate it with request data:
elif request.method == 'POST':
device_form = DeviceForm(request.POST)
scan_form = ScanForm(request.POST, request.FILES)
# is_valid is determining that UUID is not unique
if device_form.is_valid() and scan_form.is_valid():
form_data = device_form.cleaned_data
try:
device = Device.objects.get(uuid=form_data['uuid'])
except Device.DoesNotExist:
device = Device(
uuid=form_data['uuid'],
)
device.save()
scan = Scan(device=device, data=scan_form.cleaned_data['data'])
scan.save()
return HttpResponseRedirect(device.get_absolute_url())
return render(request, 'app/scan_form.html',
{'device_form': device_form,
'scan_form': scan_form})
创建新设备和关联的扫描工作正常。但是,当尝试使用现有设备UUID提交时,django会以“具有该UUID的设备已存在”的形式报告错误。并且不会保存新的扫描。
我认为这是因为UUID必须是唯一的,而对于现有的Device / UUID,device_form.is_valid()
是False,这样内部保存代码就不会执行。
有什么干净的方法可以确保表单仍然有效(包括确保UUID正确)但允许执行扫描创建代码?