Форум сайта python.su
0
Не могу понять как прикрутить проверку двух условий к одному полю!
Пробовал так:
class MyCommentForm(CommentForm):
__metaclass__ = CommentMetaclass
name = forms.CharField(initial='Name', label = '', max_length=50, help_text='Today date in text input.')
comment = forms.CharField(initial='Text',label ='', widget=forms.Textarea)
def clean_comment(self):
comment = self.cleaned_data['comment']
num_words = len(comment.split())
if comment != 'Text':
if num_words > 2:True
else:
raise forms.ValidationError(u'Введите Ваш Текст')
return comment
И так:
def clean_comment(self):
comment = self.cleaned_data['comment']
num_words = len(comment.split())
if comment == 'Text' or num_words > 2:
raise forms.ValidationError(u'Введите Ваш Текст')
return comment
Отредактировано (Сен. 5, 2011 01:52:28)
Офлайн
0
MalinaizerТак должно работать:if comment != 'Text':
if num_words > 2:True # Что сия конструкция означает? По факту она ничего не делает.
****
if comment == 'Text' or num_words > 2: # А тут знак сравнения, кажись не в ту сторону
raise forms.ValidationError(u'Введите Ваш Текст')
def clean_comment(self):
comment = self.cleaned_data['comment']
num_words = len(comment.split())
if comment != 'Text' and num_words > 2:
pass
else:
raise forms.ValidationError(u'Введите Ваш Текст')
return comment
# или так:
def clean_comment(self):
comment = self.cleaned_data['comment']
num_words = len(comment.split())
if comment == 'Text' or num_words < 2:
raise forms.ValidationError(u'Введите Ваш Текст')
return comment
Отредактировано (Сен. 5, 2011 09:58:28)
Офлайн
0
if comment != 'Text':
if num_words > 2:True # "Это я уже от без исходности начал тупить!
****
if comment == 'Text' or num_words > 2: # А тут знак сравнения, кажись не в ту сторону
raise forms.ValidationError(u'Введите Ваш Текст')
Отредактировано (Сен. 5, 2011 15:50:52)
Офлайн
0
Malinaizer
Ваши условия тоже не подходят! Задача вроде из простых, может это баг?
>>> # Упростим
>>> def clean_comment(comment):
... num_words = len(comment.split())
... if comment != 'Text' and num_words > 2:
... pass
... else:
... raise Exception('Введите Ваш Текст')
... return comment
>>> clean_comment('Text')
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
clean_comment('Text')
File "<pyshell#9>", line 6, in clean_comment
raise Exception('Введите Ваш Текст')
Exception: Введите Ваш Текст
>>> # OK
>>> clean_comment('Text text text')
2: 'Text text text'
>>> # OK
>>> clean_comment('buzz')
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
clean_comment('buzz')
File "<pyshell#9>", line 6, in clean_comment
raise Exception('Введите Ваш Текст')
Exception: Введите Ваш Текст
>>> # OK
>>> class F(Form):
... name = forms.CharField(initial='Name', label = '', max_length=50, help_text='Today date in text input.')
... comment = forms.CharField(initial='Text',label ='', widget=forms.Textarea)
...
... def clean_comment(self):
... comment = self.cleaned_data['comment']
... num_words = len(comment.split())
... if comment == 'Text' or num_words < 2:
... raise forms.ValidationError(u'Введите Ваш Текст')
... return comment
>>> f = F({'name': 'Booo', 'comment': 'Burururur'})
>>> f.is_valid()
16: False
>>> for k in f.errors:
... print f.errors[k]
<ul class="errorlist"><li>Введите Ваш Текст</li></ul>
>>> f = F({'name': 'Booo', 'comment': 'Text'})
>>> f.is_valid()
17: False
>>> f = F({'name': 'Booo', 'comment': 'Burururur bumbum'})
>>> f.is_valid()
18: True
Отредактировано (Сен. 5, 2011 16:53:56)
Офлайн
0
В том что он в форма не проходит валидацию даже если условия верны постоянный ‘Введите Ваш Текст’! хотя по отдельности каждое условие работает нормально!
Офлайн
0
Может дело в CommentForm? Я пытаюсь дополнит условия проверки!
Офлайн
0
Собрал форму полностью (Ну почти полностью…)
class CommentMetaclass(DeclarativeFieldsMetaclass):
def __init__(cls, cls_name, cls_bases, dict):
del dict['base_fields']['email']
del dict['base_fields']['url']
super(CommentMetaclass, cls).__init__(cls_name, cls_bases, dict)
class MyCommentForm(CommentForm):
__metaclass__ = CommentMetaclass
name = forms.CharField(initial='Name', label = '', max_length=50)
comment = forms.CharField(initial='Text',label ='', widget=forms.Textarea)
def clean_comment(self):
comment = self.cleaned_data['comment']
num_words = len(comment.split())
if comment == 'Text' or num_words < 2:
raise forms.ValidationError(u'Введите Ваш Текст')
return comment
*****************
>>> f = MyCommentForm(v, {'name':'Guido', 'comment':'Test text Ok'}) # v - что-бы не ругалось на отсутствие target_object
>>> f.errors
8: {'content_type': [u'This field is required.'],
'object_pk': [u'This field is required.'],
'security_hash': [u'This field is required.'],
'timestamp': [u'This field is required.']}
# ошибки по полю comment нет.
Отредактировано (Сен. 5, 2011 17:52:30)
Офлайн
0
from my_comments.forms import*
>>> f = MyCommentForm(v, {'name':'Guido', ‘comment’:'Test text Ok'})
Traceback (most recent call last):
File “<console>”, line 1, in <module>
NameError: name ‘v’ is not defined
Хочу проверить в джанго шелле но получаю ошибку что не так делаю?
Офлайн
0
По ходу дело выяснилось что и по длине не работает!
def clean_comment(self):
comment = self.cleaned_data['comment']
num_words = len(comment.split())
if num_words < 2:
raise forms.ValidationError('проверка')
return comment
Офлайн
0
Я прошу у Вас тысяча извинений, проблена с моей головой, перепутал split с join!
Офлайн