change min_length in form __init__?

44 views
Skip to first unread message

galgal

unread,
Jan 11, 2012, 6:15:47 AM1/11/12
to django...@googlegroups.com
Is there any way, to change the field's min_length argument inside form constructor? That doesn't work:

def __init__(self, *args, **kwargs):
    super(CreateTeamForm, self).__init__(*args, **kwargs)
    self.fields['primary_color'].min_length = 4

Wen 温业逵Yekui

unread,
Jan 13, 2012, 1:02:13 AM1/13/12
to django...@googlegroups.com
why you use the "*" in your function argument?

2012/1/11 galgal <weglare...@gmail.com>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/laN38iWqC-oJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

bruno desthuilliers

unread,
Jan 13, 2012, 5:41:44 AM1/13/12
to Django users
On Jan 13, 7:02 am, Wen 温业逵Yekui <wenye...@yuejia.net> wrote:
> why you use the "*" in your function argument?
>
Because it's the sensible thing to do here - cf
http://docs.python.org/release/2.6.7/tutorial/controlflow.html#more-on-defining-functions


bruno desthuilliers

unread,
Jan 13, 2012, 5:47:28 AM1/13/12
to Django users
On Jan 11, 12:15 pm, galgal <weglarek.rob...@gmail.com> wrote:
> Is there any way, to change the field's *min_length* argument inside form
> constructor? That doesn't work:
>
> def __init__(self, *args, **kwargs):
>     super(CreateTeamForm, self).__init__(*args, **kwargs)
>     self.fields['primary_color'].min_length = 4

Assuming primary_color is a CharField, this should theoretically
JustWork AFAICT. What is the result ? ("doesn't work" is not really
descriptive...)

Alasdair Nicol

unread,
Jan 13, 2012, 5:59:28 AM1/13/12
to django...@googlegroups.com
Hi Bruno,

I answered this question on Stack Overflow earlier this week [1].

When a field with min_length is initialised, a MinLengthValidator is added to the its validators. So if you set the min_length attribute after calling parent classes __init__ method, it is 'too late' for it to have any effect.

The solution is to change the field's validators in the __init__ method instead,

Cheers,
Alasdair

[1]: http://stackoverflow.com/questions/8818261/django-change-min-length-in-form-init/

-- 
Alasdair Nicol
Developer, MEMSET

mail: alas...@memset.com
 web: http://www.memset.com/

Memset Ltd., registration number 4504980. 25 Frederick Sanger Road, Guildford, Surrey, GU2 7YD, UK.
Reply all
Reply to author
Forward
0 new messages