save() creates new entry instead of updating the passed on as instance

24 views
Skip to first unread message

Zeengr

unread,
Mar 11, 2012, 2:48:01 AM3/11/12
to django...@googlegroups.com
this is my code and weirdly it creates new entry instead of updating the passed one in instance argument, don't know if that because of m2m relationship in Entry model or my code is broken!
what could be the cause?

### my edit view
@login_required
def edit_entry_view(request, entry_id):
        
    try:
        entry = Entry.objects.get(pk=entry_id, is_visible=True)
    except ObjectDoesNotExist:
        return render(request, 'entry/entry.html', {'no_enties': True})

    if request.method == 'POST':
        entry.owner = request.user
        entry.id = entry_id
        form = EntryForm(data=request.POST, instance=entry)
        if form.is_valid():
          form.save()
          return redirect('entry')
    else:
        form = EntryForm(instance=entry)
    return render(request, 'entry/edit_entry.html', {'form': form})

###my form
class EntryForm(ModelForm):
    
    class Meta:
        model = Entry
        exclude = ('owner')

 

Peter of the Norse

unread,
Mar 13, 2012, 2:34:24 AM3/13/12
to django...@googlegroups.com
There are some issues with the code.
First, entry.id = entry_id is redundant. It might even be the cause of the new Entry.
Second, the best way to update from a form and code at the same time is to do save(commit=False). Updating your code:
        form = EntryForm(data=request.POST, instance=entry)
        if form.is_valid():
          updated_entry = form.save(commit=False)
          updated_entry.owner = request.user
          updated_entry.save()
          return redirect('entry')


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/MQ8mh7qDPHYJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Peter of the Norse



Reply all
Reply to author
Forward
0 new messages