我已经在这个问题上戳了几个小时,我对这个问题感到很困惑。这个视图应该做两个操作。第一个工作操作是使用提交的表单数据创建对象。第二个操作是根据唯一字段“bar_code”更新“状态”字段。最初保存后,然后更新我得到由唯一属性“%s with this %s already exists.”引起的错误,这是预期的。我真的很想保留视图来执行这两个操作。
def check_in_part_two(request):
errlst=[]
c={}
c.update(csrf(request))
if request.method == 'POST':
form = PartForm(request.POST)
if form.is_valid():
try:
# Test if the part row exists based on bar_code
instance = Part.objects.get(bar_code=request.POST['bar_code'])
except Part.DoesNotExist:
# Clean the sn and create new row
form.cleaned_data['serial_number']
form.save()
return http.HttpResponseRedirect('/current_count/')
else:
edit = PartForm(request.POST, instance=instance, fields=['status'])
if edit.is_valid():
edit.cleaned_data['bar_code']
edit.save()
return http.HttpResponseRedirect('/current_count/')
else:
form = PartForm(initial={'status':3L, 'serial_number':'placeholder'})
return render(request,'add_part.html',{
'title':'Add Item',
'form': form,
})