views:

54

answers:

3

I am using django forms to add a new objects to the db. The code I currently have is:

if request.method == 'POST':
    form = MyForm(data=request.POST)

    if form.is_valid():
        obj = form.save()
 else:
    form = MyForm()

return render_to_response('reflections/add_reflection.html', {'form':form},context_instance=RequestContext(request))

The code above currently adds a new object each time the form is submitted. What I want to happen is that the object is edited the next time the save button is pressed rather than adding a new record.

How would I do this?

+1  A: 

Use

 instance_id = None
 if request.method == 'POST':
    try:
        instance = MyType.objects.get(id=request.POST.get('instance_id'))
    except MyType.DoesNotExist:
        instance = None
    form = MyForm(data=request.POST, instance=instance)

    if form.is_valid():
        obj = form.save()
        instance_id = obj.id
 else:
    form = MyForm(instance=None)

return render_to_response('reflections/add_reflection.html', {'form':form, 'instance_id': instance_id or ''},context_instance=RequestContext(request))

Once the object is saved, pass it's id in context to page and add it to a hidden input field inside the form as name='instance_id'.

Happy Coding.

simplyharsh
Thanks for the answer. I've put an answer above with your new code in. Does this look correct. I didn't add it to the comments as you can't add blocks of code in here
John
A: 

You either need to add a separate view for editing an existing object, or - better - to add the functionality to this view. To do the latter, you could pass in an instance of the object you want to edit with your modelform to else part of your clause:

else:
   if existing_obj:
       form = MyForm(instance=existing_obj) #this is editing your 'existing_obj'
   else:
       form = MyForm() # this is creating a brand new, empty form

You'll also need to update the POST-handling bit of code too. See the example here

stevejalim
A: 

Thanks harshh

Editing my code I would get:

if request.method == 'POST':
    form = MyForm(data=request.POST, instance=your_instance or None)

    if form.is_valid():
        obj = form.save()
 else:
    form = MyForm(instance=your_instance or None)

return render_to_response('reflections/add_reflection.html', {'form':form},context_instance=RequestContext(request))

Would this allow me to edit the new object i.e. obj in the code above? I don't redirect anywhere after the save so would I need to add MyForm(instance=obj) after the obj = form.save() call?

John