views:

97

answers:

4

I'm trying to update an object, but I'm getting: "primary key must be unique"... The model for Entry:

    class Entry(models.Model):
      title = models.CharField(max_length=250)
      author = models.ForeignKey(User, editable=False)
      status = models.IntegerField(choices=data_types.STATUS_CHOICES,
      default = data_types.STATUS_DRAFT)

And the view:

@login_required
def edit_entry(request, entry_id='0'):
  message = ""
  entry = get_object_or_404(Entry.objects, pk=entry_id)
  if request.method == 'GET':
    form = EntryForm(instance=entry)
  else :
    if request.method == 'POST':
      if request.POST['submit'] == 'Edit':
        print "entry id: %s" % entry.id
        form = EntryForm(request.POST, instance=entry)
        if form.is_valid():
            secondEntry = form.save(False)
            print "second entry id: %s" % secondEntry.id
            form.save()
            message = "entry updated"
        else:
            message = 'There were errors'
  return render_to_response(
        'myadmin/edit_entry.html',
         { 'entryForm':form,'message': message}, 
         context_instance=RequestContext(request))

So I print both IDs and they are the same: 1. That should make form.save() update the object, but instead, it tries to insert it... any idea?

A: 

Why do you have form.save() twice? Perhaps that is the problem.

defrex
A: 

Well maybe in the line form = EntryForm(request.POST, instance=entry) you dont specify an intance parameter, because this is for update an existing model....

A: 

form.save(force_update=True)

phillc
+1  A: 

Your first form.save(False) produces an Entry object filled with the data from the form, so you should save that Entry object instead of the form again.

secondEntry = form.save(commit=False)
secondEntry.save()
Adam