On 2/02/2012 12:13pm, Nikolas Stevenson-Molnar wrote:
TO_USE= (
('Y', 'Yes'),
('N', 'No'),
)
class X(models.Model):
txt= models.CharField(db_index=True,null=True,
blank=True,max_length=30)
use_txt=
models.CharField(blank=False,max_length=1,default='D',choices=TO_USE)
and in admin.py something as
class XForm(forms.ModelForm):
def clean(self):
cleaned_data=super(XForm, self).clean()
txt= cleaned_data['txt'].strip()
use_txt=cleaned_data['use_txt'].strip()
if txt.__len__()==0 and use_txt==TO_USE.__getitem__(0)[0]:
Personally, I would do this in models.py so it would run in any form's
clean method. In which case ...
class X(models.Model):
...
def clean(self):
self.txt = self.txt.strip()
Assuming you mean you only care about the contents of txt if there is
something there AND then if so, you want the user to make a Yes/No
selection ...
if self.txt:
ok = False
for abbr, fullword in TO_USE:
# fullword is ignored
if abbr in self.use_txt:
ok = True
break
if not ok:
raise django.core.exceptions.ValidationError('Yes or
No required')
The above 'in' keyword means you don't need to use_txt.strip()
raise forms.ValidationError('This is needed!')
return cleaned_data
The part .__getitem__(0)[0] is not very readable. I have looked for
enums in python, and if I have understood well, it seems they are not
implemented.
Have a look at list comprehension in the Python docs. It might help if
you make TO_USE into a list of tuples instead of a tuple of tuples. I'm
not as familiar with list comprehension as I should be and I suspect my
verbose approach above could be squished considerably.
Just as an aside, you ought to be able to extract all the functionality
ordinarily required without having to resort to __internal__() methods.
They are really for people who want to tweak the language in "special"
ways or give their own classes python-like class properties.
What is the best way to do it in python for my problem, given that I do
not want to write =='Y'.
I'm not saying the above is the "best" way but it might avoid =='Y'
Mike
--
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.