Reputation: 8035
Hey, I've searched around to do this (particularly this Q: Django edit form based on add form?) but I just can't get it to work.
The problem I'm having is that the form always creates a new object, instead of modifying the existing one.
This is my code:
def new_task(request, task_id=None):
if task_id is not None:
task = Task.objects.get(pk=task_id)
else:
task = Task()
if request.method == 'POST': # If the form has been submitted...
form = TaskForm(request.POST, instance=task)
if form.is_valid():
form.save();
return tasks(request, 'Task #%s created successfully.' % (task.id))
else:
form = TaskForm(instance=task)
return custom_render('user/new_task.html',
{'form': form},
request);
Any clues on what I'm missing? Thanks
Edit: added form definitions.
class TaskForm(ModelForm):
description = CharField(max_length = 1500,
widget= forms.Textarea(attrs={'class':'task-description'}),
required=True)
class Meta:
model = Task
Upvotes: 2
Views: 5312
Reputation: 8035
Ok, after a nice night of debugging i found out what the problem was. Quite stupid actually. The problem was that on submit, task_id was None.
I worked it out by doing:
<form action="{% url App.myapp.views.new_task **task_id** %}"
On my views I added:
return custom_render('user/new_task.html', {'form': form, 'submit': submit, 'task_id':task.id}, request)
That was it. A newbie mistake. If someone out there knows a nicer way I'm open to suggestions.
Upvotes: 4