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
6
  • 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. Commented Mar 6, 2010 at 22:04
  • Have you overwritten the forms save method? Can you show the form definition? Commented Mar 6, 2010 at 22:34
  • I just added the form def. No, I have not overwritten the save method... Commented Mar 6, 2010 at 22:45
  • Very strange, this code should work without a problem like this. Are you sure task_id is not None? Commented Mar 6, 2010 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. Commented Mar 6, 2010 at 23:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
Both the answer and your comment are useful. I went with what your comment said in the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.