Reputation: 355
I was wondering what went wrong in my code.When I try to save the data it gets overwritten.
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")
Upvotes: 0
Views: 62
Reputation: 45575
If you call form's save()
method several times the same model instance will be saved all the time. To create new instance at the each call you have to set the instance's pk
to None
:
for item in unions_choice_list:
form.instance.pk = None
announcement = form.save(commit=False)
...
Or, which is the same:
for item in unions_choice_list:
announcement = form.save(commit=False)
announcement.pk = None
...
Upvotes: 1