Custom Model Field with Validation...how to hook it back to ModelForm

2009-12-18 Thread bkev
Hello...

A common occurrence I have with one particular project is that it
requires the user to enter dimensions (for width/depth/height) in Feet
and Inches. Calculations are needed to be performed on that dimension,
so I've been working on a custom field type that takes in a dimension
in Feet/Inches (eg. 1'-10") and saves it to the database as a decimal
number using a regex to parse the input. The field displays to the end-
user as feet-inches at all times (with the eventual goal of writing a
method to be able to optionally display in metric, and interact with
measure.py, and geodjango stuff). What I have so far is definitely not
DRY, but aside from that, I'm having trouble with validation at the
form level. The custom model field itself works properly (from what
I've seen), and I've written a form field clean method which should
work to validate the field. My question is how to hook that form field
back into my model form to work for all the width/depth/height fields.
I'm thinking maybe an override of the init on the modelform (a la
self.fields['depth']...) , but I'm not quite sure where to go from
here...would you help me?

DCML_PATTERN = re.compile(r'^(?P\d+)(?P\.?\d*)\'?$')
FTIN_PATTERN = re.compile(r'^(?P\d+)\'?\s*-?\s*(?P[0-9]|10|
11)?\"?$')

class FtInField(models.Field):
__metaclass__ = models.SubfieldBase

empty_strings_allowed = False

def db_type(self):
return 'double'

def get_internal_type(self):
return "FtInField"

def to_python(self,value):
if value is u'' or value is None:
return None
if isinstance(value, float):
m = FTDCML_PATTERN.match(str(value))
if m is None:
raise Exception('Must be an integer or decimal 
number')
feet = int(m.group('feet'))
dec_inch = float(m.group('dec_inch') or 0)
inch = dec_inch * 12
return "%d\'-%.0f\"" % (feet,inch)
return value

def get_db_prep_value(self,value):
if value is u'' or value is None:
return None
m = FTIN_PATTERN.match(value)
if m is None:
raise Exception('Must be in X\'-Y" Format')
feet = int(m.group('feet'))
inch = int(m.group('inch') or 0)
return (feet + (inch/float(12)))


class FtInField(forms.Field):

def clean(self,value):
super(FtInField, self).clean(value)
if value is u'' or value is None:
raise forms.ValidationError('Enter a dimension in 
X\'-Y" format')
m = FTIN_PATTERN.match(value)
if m is None:
raise forms.ValidationError('Must be in X\'-Y" Format')
feet = int(m.group('feet'))
inch = int(m.group('inch') or 0)
value = '%d\'-%.0f"' % (feet,inch)
return value

class ProductClass(models.Model):
productname = models.CharField('Product Name', max_length=60,
blank=True)
depth = FtInField('Depth (Feet/Inches)')
width = FtInField('Width (Feet/Inches)')
height = FtInField('Height (Feet/Inches)')

class ProductClassForm(forms.ModelForm):
depth = FtInField()
width = FtInField()
height = FtInField()

class Meta:
model = ProductClass

class ProductClassAdmin(admin.ModelAdmin):
form = ProductClassForm

--

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




Django contact_form import error

2009-04-28 Thread bkev

Hello,

This is perhaps a stupid newbie issue, but I'm having trouble using
James Bennett's lovely contact_form plugin. I'm getting a template
syntax error - "No module named contact_form". As suggested in the
install docs, I have put 'contact_form' in my installed apps setting,
added (r'^contact/', include('contact_form.urls')), to my urls.py
file, and added the four requisite templates - contact_form.txt,
contact_form.html, contact_form_sent.html, and
contact_form_subject.txt in a contact_form subdirectory within my
templates directory. The directory where contact_form is located is on
my pythonpath (and is verified when I do an import sys - print
sys.path), and if I go into an interactive shell within my app, I'm
able to import contact_form without issue. I'm at a loss to figure out
why I'm able to import it, but django is not...? Any ideas?

Sincere thanks in advance...
bkev
--~--~-~--~~~---~--~~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Stupid Newbie ManyToManyField Contains question

2009-02-10 Thread bkev

Hmm... That sort of works, but not quite. If I use the filter method,
it won't properly set the jumbledname on the first save. However, if I
go back in and save the instance again a second time, it will properly
set jumbledname. If I had it to guess, (after looking at the Django
documentation) it's because the filter method uses a SQL like
statement (rather than just evaluating the post data) which probably
means it has to look at the database first...in other words, the first
save changes the lastname field, and the second save looks at that
field and changes jumbledname accordingly. (This is a guess, but based
on the behavior, I think it's the right one). Any ideas as to how I
might modify it?

Thank you for everything,
bkev
--~--~-~--~~~---~--~~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Stupid Newbie ManyToManyField Contains question

2009-02-10 Thread bkev

Hmm...It is just a normal python string, but when I try 'Smith' in
self.lastname, I get a "ManyRelatedManager is not iterable" error. Any
ideas?

Thanks again,
-bkev
--~--~-~--~~~---~--~~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Stupid Newbie ManyToManyField Contains question

2009-02-10 Thread bkev

Hello all,

Is there a way to check whether a field contains a certain value in a
ManyToManyField in the admin on a custom save method? For example, I
have a model like:

class LastName(models.Model):
lastname = models.CharField(...)

class Person(models.Model):
   firstname = models.CharField(...)
   lastname = models.ManyToManyField(LastName,...)
   jumbledname = models.CharField(..., editable = False)

   def save(self):
if self.lastname CONTAINS? 'Smith':
self.jumbledname = u'%s%s' % ('self.firstname,
self.lastname')
else:
self.jumbledname = self.firstname
super(Person,self).save()

Thanks,
-bkev
--~--~-~--~~~---~--~~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Unexpected keyword argument 'raw_in_admin' in Django 1 release 9014?

2008-09-11 Thread bkev

Hi,

I'm trying to set up this simple model in Django and I'm getting an
"init got unexpected keyword argument 'raw_in_admin'" in Django 1.0
release 9014 when doing a syncdb. I'm trying to get a non-dropdown
ForeignKey (or OneToOneField) field...am I doing something wrong or
was something changed in Django 1.0?

class Depth(models.Model):
depth_feetinch = models.CharField(verbose_name="Depth",
max_length=10)

class Dimensions(models.Model):
depth = models.ForeignKey(Depth, raw_id_admin=True)

Thank you,
bkev
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



Re: Newbie Question - Regex Field to deal with Feet/Inches

2008-09-04 Thread bkev

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(\d{1,5}))(\')(\s?)(-?)(\s?)(?
P(\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.))

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



Re: Newbie Question - Regex Field to deal with Feet/Inches

2008-08-28 Thread bkev

Ronny,

This is fabulous...thank you so very much. If you don't mind me
asking, can you give me an example of how you implemented this method
in your Class? In my case, I've defined the field as a DecimalField
type, but that brings up an error. Did you define some sort of custom
save method around that? Thank you; I really appreciate it.

bkev



On Aug 27, 2:32 am, "Ronny Haryanto" <[EMAIL PROTECTED]> wrote:
> On Wed, Aug 27, 2008 at 3:13 AM, bkev <[EMAIL PROTECTED]> wrote:
> > I'm working on a site that has several imperial measurements (feet and
> > inches) and I'd like to implement a field in my model that uses a
> > regular expression like:
> >  ^(\d{1,5})\'((\s?)(-?)(\s?)([0-9]|(1[0-1]))\")?$
> > to parse off the feet and inches and save them in a sortable manner
> > (I'm guessing the best way would be to convert them and save them as a
> > decimal number, but the list and admin display needs to in x'-y"
> > format. Anyone have any ideas as to how I might accomplish that? (or
> > where I should look for more information)?
>
> I use the following method in one of my projects:
>
> def feetinch_to_cm(length):
>     """convert US style (feet-inch) length to metric (cm)"""
>     if length == u'' or length is None:
>         return None
>     m = re.match(r'(?P\d+)[\'`](
> *(?P\d+)(?P.)?("|\'\'))?', 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)
>     half = int(m.group('half') == u'\xbd')
>     return (30.48 * feet) + (2.54 * inch) + (1.27 * half)
>
> I save the length in centimeters in database, then I can reformat it
> as needed in the template or admin using a custom filter.
>
> 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
-~--~~~~--~~--~--~---



Re: Newbie Question - Regex Field to deal with Feet/Inches

2008-08-28 Thread bkev

Ronny,

This is fabulous...thank you so very much. If you don't mind me
asking, can you give me an example of how you implemented this method
in your Class? In my case, I've defined the field as a DecimalField
type, but that brings up an error. Did you define some sort of custom
save method around that? Thank you; I really appreciate it.

bkev



On Aug 27, 2:32 am, "Ronny Haryanto" <[EMAIL PROTECTED]> wrote:
> On Wed, Aug 27, 2008 at 3:13 AM, bkev <[EMAIL PROTECTED]> wrote:
> > I'm working on a site that has several imperial measurements (feet and
> > inches) and I'd like to implement a field in my model that uses a
> > regular expression like:
> >  ^(\d{1,5})\'((\s?)(-?)(\s?)([0-9]|(1[0-1]))\")?$
> > to parse off the feet and inches and save them in a sortable manner
> > (I'm guessing the best way would be to convert them and save them as a
> > decimal number, but the list and admin display needs to in x'-y"
> > format. Anyone have any ideas as to how I might accomplish that? (or
> > where I should look for more information)?
>
> I use the following method in one of my projects:
>
> def feetinch_to_cm(length):
>     """convert US style (feet-inch) length to metric (cm)"""
>     if length == u'' or length is None:
>         return None
>     m = re.match(r'(?P\d+)[\'`](
> *(?P\d+)(?P.)?("|\'\'))?', 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)
>     half = int(m.group('half') == u'\xbd')
>     return (30.48 * feet) + (2.54 * inch) + (1.27 * half)
>
> I save the length in centimeters in database, then I can reformat it
> as needed in the template or admin using a custom filter.
>
> 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
-~--~~~~--~~--~--~---



Re: Newbie Question - Regex Field to deal with Feet/Inches

2008-08-28 Thread bkev

Ronny,

This is fabulous...thank you so very much. If you don't mind me
asking, can you give me an example of how you implemented this method
in your Class? In my case, I've defined the field as a DecimalField
type, but that brings up an error. Did you define some sort of custom
save method around that? Thank you; I really appreciate it.

bkev



On Aug 27, 2:32 am, "Ronny Haryanto" <[EMAIL PROTECTED]> wrote:
> On Wed, Aug 27, 2008 at 3:13 AM, bkev <[EMAIL PROTECTED]> wrote:
> > I'm working on a site that has several imperial measurements (feet and
> > inches) and I'd like to implement a field in my model that uses a
> > regular expression like:
> >  ^(\d{1,5})\'((\s?)(-?)(\s?)([0-9]|(1[0-1]))\")?$
> > to parse off the feet and inches and save them in a sortable manner
> > (I'm guessing the best way would be to convert them and save them as a
> > decimal number, but the list and admin display needs to in x'-y"
> > format. Anyone have any ideas as to how I might accomplish that? (or
> > where I should look for more information)?
>
> I use the following method in one of my projects:
>
> def feetinch_to_cm(length):
>     """convert US style (feet-inch) length to metric (cm)"""
>     if length == u'' or length is None:
>         return None
>     m = re.match(r'(?P\d+)[\'`](
> *(?P\d+)(?P.)?("|\'\'))?', 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)
>     half = int(m.group('half') == u'\xbd')
>     return (30.48 * feet) + (2.54 * inch) + (1.27 * half)
>
> I save the length in centimeters in database, then I can reformat it
> as needed in the template or admin using a custom filter.
>
> 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
-~--~~~~--~~--~--~---



Newbie Question - Regex Field to deal with Feet/Inches

2008-08-26 Thread bkev

Hi there...

I'm working on a site that has several imperial measurements (feet and
inches) and I'd like to implement a field in my model that uses a
regular expression like:
 ^(\d{1,5})\'((\s?)(-?)(\s?)([0-9]|(1[0-1]))\")?$
to parse off the feet and inches and save them in a sortable manner
(I'm guessing the best way would be to convert them and save them as a
decimal number, but the list and admin display needs to in x'-y"
format. Anyone have any ideas as to how I might accomplish that? (or
where I should look for more information)?

Thank you,
bkev
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---