tags:

views:

155

answers:

1

OK. I just tied myself in a knot trying to make a form in Django which I can use to either enter data about a new record or update an existing one.

Can anyone sketch out the right things I should have in my forms, views and urls if have this model? :

class Person(models.Model) :
  name = models.CharField()
  age = models.IntegerField()

In another page I want a link to a form which lets me create a new instance of a person OR edit an existing one.

Things I'm getting confused by :

  • do I need two distinct lines on the urls.py, one to link to the blank form, NOT passing an id and one to link to the form when I do pass the id?

  • do I need two different views, one to receive the form before an instance has been saved, and one when the instance exists?

I'm sure I've seen this done with one link and one function in views.py, but I don't seem to be able to get it right anymore. What doesn't seem to work is trying to send both the url with the id

  /edit/id

and without

  /edit/

to the same view function with a default argument for id

 def edit(request,id=0) :
    blah

So what's the right way to do this?

Cheers. phil

+3  A: 

Set up your urls.py to capture the id variable if included in the url, then check for null in your views.py

Your urls.py could look something like this:

(r'^edit/(?P<person_id>\w+)/$', 'mysite.myapp.views.edit_person'),

Then, in your views.py:

def edit_person(person_id=None):
    if(person_id): #show populated form
    else: # show empty form
Chris Lawlor
thanks, that sounds like what I was looking for
interstar