我想知道我的代码出了什么问题。当我尝试保存数据时,它会被覆盖。
if form.is_valid():
for item in unions_choice_list:
announcement = form.save(commit=False)
obj = Union.objects.get(pk=item)
announcement.union = obj
announcement.tittle = request.POST.get('tittle')
announcement.message_text = request.POST.get('message_text')
tilldate = request.POST.get('till_date')
p = unicodedata.normalize('NFKD', tilldate).encode('ascii','ignore')
till_date1 = datetime.datetime.strptime(p, '%d %b %Y').date()
announcement.till_date = till_date1
announcement.type = type
announcement.message_from = request.POST.get('message_from')
announcement.show_to = 'union'
if request.FILES.get('file1') is not None:
announcement.file1 = request.FILES['file1']
announcement.save()
else:
messages.error(request, "Correct the displayed errors")
答案 0 :(得分:1)
如果多次调用表单的save()
方法,将始终保存相同的模型实例。要在每次调用时创建新实例,您必须将实例的pk
设置为None
:
for item in unions_choice_list:
form.instance.pk = None
announcement = form.save(commit=False)
...
或者,这是相同的:
for item in unions_choice_list:
announcement = form.save(commit=False)
announcement.pk = None
...