0

I am using forms in my Django project, and I want to specify some of the attributes of the widget that I use in my form but am having trouble figuring out how to pass in the attrs dictionary to the widget.

The view.py:

form_schedule_start = WINDOW_Schedule_Form(section_label=" Start",required=True,initial=scheduleStart,attributes={'class':"form-control",'placeholder':".col-md-4"})

The form:

class WINDOW_Schedule_Form(forms.Form):
  def __init__(self,*args,**kwargs):
    section_label = kwargs.pop('section_label')
    initial_value = kwargs.pop('initial')
    required_value = kwargs.pop('required')
    attributes = kwargs.pop('attributes')

    super(WINDOW_Schedule_Form,self).__init__(*args,**kwargs)
    self.fields['WINDOW_Schedule'].label=mark_safe(section_label)
    self.fields['WINDOW_Schedule'].initial=initial_value
    self.fields['WINDOW_Schedule'].required=required_value
    self.fields['WINDOW_Schedule'].attrs=attributes


  WINDOW_Schedule = forms.CharField(widget=forms.TextInput())

Normally you would just do

WINDOW_Schedule = forms.CharField(widget=forms.TextInput(attrs={'class':"form-control text-center",'placeholder':".col-md-8"}))

but I want to be able to specify the 'class' and 'placeholder' attributes in my views.py.

I keep getting an error that attributes is not defined though. Can anyone tell me what I'm doing wrong?

kdubs
  • 936
  • 3
  • 22
  • 45
  • Where do you get the error? At the point where `kwargs.pop('attributes')` is called? – Alain Jul 22 '15 at 19:37
  • @Alain yes, I get it where `kwargs.pop('attributes')` is called. – kdubs Jul 22 '15 at 20:40
  • This is interesting. According to the definition of the pop() function for dictionaries (see https://docs.python.org/2/library/stdtypes.html), a key error should be raised when you execute `required_value = kwargs.pop('required')` since there is no key 'required' and you don't assign a default. – Alain Jul 23 '15 at 01:18
  • @Alain I think that is a copy/paste error on my part. I have `required` defined in my code - see updated question. – kdubs Jul 23 '15 at 18:19

1 Answers1

0
This Code May Help You Out       
class ContactForm(ModelForm):
    class Meta:
      model = Contact
      created = MyDatePicker()

class Uniform(forms):
  def __init__(self, *args, **kwargs):
      attrs = kwargs.pop("attrs",{})
      attrs["class"] = "span3"
      kwargs["attrs"] = attrs
      super(Uniform, self).__init__(*args, **kwargs)

class MyDatePicker(Uniform,forms.DateInput)
  def __init__(self, *args, **kwargs):
      attrs = kwargs.pop("attrs",{})
      attrs["class"] = "datepick" 
      attrs["id"] =kwargs.get('datetag', '')
      kwargs["attrs"] = attrs
      super(MyDatePicker, self).__init__(*args, **kwargs)
Arun
  • 3,440
  • 1
  • 11
  • 19
  • Source :https://stackoverflow.com/questions/8474409/django-forms-and-bootstrap-css-classes-and-divs – Arun Mar 18 '18 at 23:44