On Sat, 2007-06-09 at 13:39 +0000, Car wrote:
> Hi,
> 
> I have 1:n Relation, model A which hase foreign key ("type") to B. I'm
> passing foreign key to a view via post using the ModelChoiceField.
> Problem is its converted into string, so when I try to create in a
> view  a 'A' record
> 
> like
> # data = POST dictionary
> 
> A(
>                 address         = data[ 'address' ],  # okay becouse
> address = charfield
>                 gateuser     = data[ 'gateuser' ], # still okay
>                 type           =  ...........
> 
> And now I have type error - type should be a B-type not string.
> 
> I can try smth like this: type B.objects.get(pk=int(data['type'])  -
> but is it a simplier and cleaner way to convert data passed via POST
> from string to objects.

You should never access POST data like this to work with it in your
code, because (a) it will all be strings, as you've noticed and (b) you
are bypassing all of the field validation code in the form, so your data
might not be at all valid (what if the client submitted 'elephant' where
you expected a number?).

Have a read of the newforms documentation on the website (or in
docs/newforms.txt in the source). Look at the is_valid() method. You
will normally want to do something like this:

        form = MyForm(request.POST)
        if not form.is_valid():
            # do something about the errors...
        else:
            # work with form.cleaned_data

If you want specific field cleaning that isn't provided by the default
field classes, have a read of 

        http://groups.google.com/group/django-users/msg/37fe68ea76416872

(which will soon be in the documentation).

Regards,
Malcolm



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

Reply via email to