On Tue, Dec 2, 2008 at 5:09 PM, Margie <[EMAIL PROTECTED]> wrote:
>
> I'm a new user to django and am attempting to go through the Sams
> "Teach Yourself Django in 24 hours" book and am having an issue
> related to the chapter on saving form data. I'm hoping someone can
> give me a hand.
>
> I'm using Django 1.0
>
> Here's my model:
>
> class Person(models.Model):
> userID = models.ForeignKey(User, unique=True)
> name = models.CharField('name', max_length=200)
> birthday = models.DateField('Birthday', blank = True, null=True)
> email=models.EmailField('Email', max_length=100, unique=True)
>
> Here's what the book says to use for the form:
>
> def person_form(request, pID='0'):
> p = get_object_or_404(Person, pk=pID)
> if request.method == 'POST':
> if request.POST['submit'] == 'update':
> message = 'Update Request for %s.' % p.name
> PersonForm = forms.form_for_instance(p)
> f = PersonForm(request.POST.copy())
> if f.is_valid():
> try:
> f.save()
> message += ' Updated.'
> except:
> message = ' Database Error.'
> else:
> message += ' Invalid.'
>
>
> That seems to be the "old" way of doing forms (I found that
> forms_for_instance doesn't exist),
> so I've modified it to look like this:
>
> class PersonForm(ModelForm):
> class Meta:
> model=Person
>
> def person_form(request, pID='0'):
> p = get_object_or_404(Person, pk=pID)
> if request.method == 'POST':
> if request.POST['submit'] == 'update':
> message = 'Update Request for %s.' % p.name
> f = PersonForm(request.POST)
> if f.is_valid():
> try:
> f.save()
> message += ' Updates.'
> except:
> message = ' Database Error.'
> else:
> message += ' Invalid.'
>
> I hope my modications are correct here - they could be part of the
> issue.
>
> The problem I have is that when I go to the form for a person, such as
> http://127.0.0.1:8000/people/Form/3/, and then modify a field such
> as the birthday, when I then click on the update button, the is_valid
> ()
> method returns false and the errors that get printed to the form are:
> * Person with this UserID already exists
> * Person with this Email already exists
>
> It seems like update is trying to create a new person with the
> same UserID, when really I want to just be modifying the person
> with that UserID.
>
> Can anyone tell me what I'm doing wrong?
>
> Thanks,
>
> Margie
>
>
>
> >
>
Change the way you create your form from this:
f = PersonForm(request.POST)
to this:
f = PersonForm(request.POST, instance=p)
Then your form will be populated with the data from 'p', and update
that record instead of creating a new one.
Colin
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---