django forms - edit object after form submitted the first time
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?
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.
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
精彩评论