On Fri, Sep 5, 2008 at 1:53 AM, bkev <[EMAIL PROTECTED]> wrote:
>
> Ronny,
>
> Thank you so very much for your input; it has helped this newbie user
> a great deal. The one outstanding problem I'm having here (and it's
> the last field in my model...) is that I'd actually like to use a
> FloatField to save my data, but it's failing validation for that type
> of field ("enter a valid floating point number, etc"). Did you
> override the field validation using some clean() method variation, or
> am I missing something? See my modified class definition below:
>
> Thank you again,
> -bkev
>
>
>
> def feetinch_to_decimal(length):
>        """convert US style (feet-inch) length to decimal feet (ft)"""
>        if length == u'' or length is None:
>                return None
>        m = re.match(r'^(?P<feet>(\d{1,5}))(\')(\s?)(-?)(\s?)(?
> P<inch>(\d{1,2}))(")?$',length)
>        if m is None:
>                raise Exception("unable to parse length: %s" % length,)
>        feet = int(m.group('feet'))
>        inch = int(m.group('inch') or 0)
>        return (feet + (inch/12.0000))
>
> class FooBar(models.Model):
>        length = models.FloatField(verbose_name="Length",default="0")
>        try:
>                bar=FooBar.objects.get_or_create(id='1',length='1')
>                bar.foo=feetinch_to_decimal(input)
>                bar.save()
>        except Exception, e:
>                if isinstance(e,IntegrityError):
>                        print "Pass"
>                else:
>                        print "Fail with %s" % type(e)
>        class Admin:
>                pass


I wouldn't do that, it doesn't make sense to me.

Only this is needed in models.py:

class FooBar(models.Model):
    length_in_cm = models.FloatField(default=0)

Then somewhere else (e.g. views.py or others):

length_us = '5\'2"'
foo = FooBar()
foo.length_in_cm = feetinch_to_cm(length_us)
foo.save()

Alternatively, if you want FooBar to understand and support the
conversion you could create a length_in_feetinch property that will
automatically do the conversion to cm while keeping only the
length_in_cm in the database, have a look at
http://adam.gomaa.us/blog/the-python-property-builtin/ for an example.

Ronny

--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to