2

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
Community
  • 1
  • 1
Ignacio
  • 7,947
  • 15
  • 63
  • 74
  • Just to add more info, the form gets populated correctly with the object's data when editing and it shows empty when adding a new one. All works correctly apart from this issue. – Ignacio Mar 06 '10 at 22:04
  • Have you overwritten the forms save method? Can you show the form definition? – Felix Kling Mar 06 '10 at 22:34
  • I just added the form def. No, I have not overwritten the save method... – Ignacio Mar 06 '10 at 22:45
  • Very strange, this code should work without a problem like this. Are you sure task_id is not None? – Wolph Mar 06 '10 at 23:32
  • well, I'm pretty sure, since the form gets populated with the data from that task... I'll give this a look when I'm less tired and I'll return with some answer, I hope. – Ignacio Mar 06 '10 at 23:39
  • Oops, I'm looking at it again and actually the task_id IS None when i submit the form. I think I'm missing the id in the form or somewhere in the view function when I submit the Update. Any clues? – Ignacio Mar 10 '10 at 02:26

1 Answers1

4

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:

  1. On the form I added: <form action="{% url App.myapp.views.new_task **task_id** %}"
  2. 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.

Ignacio
  • 7,947
  • 15
  • 63
  • 74
  • 2
    Erm - I *think* if you leave the action attribute out then it will just submit back to the same URL and the view will pick up the task_id – Ryan Jan 19 '11 at 01:22
  • 1
    Both the answer and your comment are useful. I went with what your comment said in the end. – chryss Mar 01 '12 at 21:41