This link has been bookmarked by 36 people . It was first bookmarked on 14 Nov 2008, by Daniel Andrlik.
-
26 Jan 12
-
17 Aug 11
-
04 Aug 11
-
09 Apr 11
-
29 Jan 11
-
18 Jan 11
-
07 Nov 10
-
09 Sep 10
-
28 Jul 10
-
01 Sep 09
-
we only want to have this field when the form is being filled out by an anonymous visitor, and not when it’s coming from an authenticated user of the site
-
self.fields['captcha'] = CaptchaField()
-
if you wanted to change the
max_lengthof aCharField, for example, you could simply pull it out ofself.fieldsand make the changes you wanted. -
Of course, there are limits to what’s practical to do in an overridden
__init__(); sooner or later the amount of code required (and the gymnastics you’ll hve to do for things like custom validation methods) simply gets to be too much and you find yourself needing something a little more powerful. Typically, the solution for those cases is a factory function (or factory method, if you prefer) which knows how to build form classes. -
how to build a form for it, minus the
Userfield. -
profile_mod = get_profile_model() class _ProfileForm(forms.ModelForm): class Meta: model = profile_mod exclude = ('user',) # User will be filled in by the view. return _ProfileForm
-
form_class = utils.get_profile_form() if request.method == 'POST': form = form_class(data=request.POST, files=request.FILES) if form.is_valid(): # Standard form-handling behavior goes here...
-
- The name you want to give to your class.
- A list of one or more classes it will inherit from, in order.
- A dictionary whose keys and values will end up as the basic attributes of the class.
The
type()function takes three arguments: -
def make_contact_form(user): # The basic form class _ContactForm(forms.Form): name = forms.CharField(max_length=50) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea) if user.is_authenticated(): return _ContactForm class _CaptchaContactForm(_ContactForm): captcha = CaptchaField() return _CaptchaContactForm
-
But this is pretty ugly; let’s see how it works using
type(): -
def make_contact_form(user): fields = { 'name': forms.CharField(max_length=50), 'email': forms.EmailField(), 'message': forms.CharField(widget=forms.Textarea) } if not user.is_authenticated: fields['captcha'] = CaptchaField() return type('ContactForm', [forms.BaseForm], { 'base_fields': fields })
-
use
django.forms.BaseForminstead ofdjango.forms.Form
-
-
27 Aug 09
-
26 Aug 09
-
09 Jun 09
-
25 Apr 09
-
03 Mar 09
-
25 Nov 08
-
14 Nov 08
Daniel AndrlikA useful little tutorial from James Bennett on how to produce dynamic forms with Django. Some of these techniques I have been using on my own, but he provides examples that show a much more efficient way of doing it than I have in my own code.
-
13 Nov 08
-
12 Nov 08
-
10 Nov 08
Would you like to comment?
Join Diigo for a free account, or sign in if you are already a member.