Login

Adding a field to a newform in __init__

Author:
bram
Posted:
May 15, 2007
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

When adding fields in the init of a newform, and you don't want the fields to be added after the class-attribute fields, this is a possibility... This is a bad example as the email_from could just as well have been defined as a class variable!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class ContactForm(forms.Form):
    to = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea())
    
    def __init__(self, user, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        
        # user isn't logged in, so ask him for an email
        from_field = forms.EmailField()
        
        if not user.is_anonymous():
            from_field.widget = forms.HiddenInput
            from_field.initial = user.email
        
        # insert the field at the start of the fields
        new_fields = self.fields.items()
        new_fields.insert(0, ('from', from_field))
        self.fields = SortedDictFromList(new_fields)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.