Monday, September 13, 2010

Re: Form not taking my input...

On Sep 13, 9:32 pm, keynesiandreamer <keynesiandr...@gmail.com> wrote:
> Hi Daniel, thanks for looking at this!
>
> Here is my views.py code related to this:
>
> @login_required
> def wine_add_page(request):
>   if request.method == 'POST':
>     form = WineAddForm(request.POST)
>     if form.is_valid():
>       #create or get dummy wine
>       wine, dummy = Wine.objects.get_or_create(
>         wine_name=form.cleaned_data['wine_name']
>       )
>
>       #update wine_name
>       winerater.wine_name = form.cleaned_data['title']
>       #if the bookmark is being updated, clear old tag list
>       if not created:
>         winerater.tag_set.clear()
>       #create new tage list
>       tag_names = form.cleaned_data['tags'].split()
>       for tag_name in tag_names:
>         tag, dummy = Tag.objects.get_or_create(name=tag_name)
>         wnerater.tag_set.add(tag)
>         #save wine to DB
>       winerater.save()
>       return HttpResponseRedirect(
>         '/user/%s/' % request.user.username
>       )
>   else:
>     form = WineAddForm()
>   variables = RequestContext(request, {
>     'form': form
>   })
>   return render_to_response('wine_add.html', variables)
>
> HTH
>
> -Ben

The immediate issue here is that your `get_or_create()` call only
passes a value for `wine_name` - if the wine doesn't exist, Django
will try and create it, but doesn't have any of the other fields,
hence the integrity error. You need to use the `defaults` argument to
provide the rest of the data. See the documentation:
http://docs.djangoproject.com/en/1.2/ref/models/querysets/#get-or-create-kwargs

There are a few other issues with this code, which you'll discover
once you've fixed that - eg you start off calling the new Wine object
`wine`, then swap to `winerater`, which will lead to an error.
Similarly you've used `dummy` as the second result from
`get_or_create` but then later refer to `created`.
--
DR.

--
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