Thursday, September 29, 2011

Re: Help with forms (really struggling)

On Thu, Sep 29, 2011 at 2:58 PM, David <cthlogs@gmail.com> wrote:
> Hi Kurtis
>
> Thanks for your reply.
>
> That wasn't a silly question. A person is not a user.
>
> I modified my view like this:
>
> @login_required
> def update_log(request, pk):
>        try:
>                person = Person.objects.get(pk=pk)
>        except KeyError:
>                raise Http404
>        if request.method == 'POST':
>                form = LogForm(request.POST, instance=person,
> prefix='log')

Woah!

If this is a log form, then you really shouldn't be passing a Person
as the instance - that is really not going to work.

The code should look a little like this:

if request.method == 'POST':
form = LogForm(request.POST)
if form.is_valid():
log = form.save(commit=False)
# Add in the required missing parameters
log.person = person
# alternatively just use the id - this sets up log.user
log.user_id = user_id
log.save()

Another technique is to override save, and perform this logic there,
perhaps using values passed into the form's overridden constructor:

def save(commit=True, *args, **kwargs):
instance = super(LogForm, self).save(commit=False, *args, **kwargs)
instance.user = self.user
instance.person = self.person
if commit:
instance.save()
return instance

I like this behaviour as it takes that messy logic out of the view,
and has the happy side effect of making most views look very alike.

Cheers

Tom

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment