Adding a field to a newform in __init__

 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. change a widget attribute in ModelForm without define the field by jedie 4 years, 9 months ago
  2. Render dynamically assigned fields in a template by rubic 6 years, 2 months ago
  3. FieldsetForm by Ciantic 6 years, 1 month ago
  4. DRY with common model fields (another way) by jmrbcu 5 years, 10 months ago
  5. filtered ModelChoiceField queries by robharvey 5 years, 2 months ago

Comments

(Forgotten your password?)