Prometheus
Prometheus

Reputation: 33655

Django add attribute to every field by default

I need to be pointed in the right direction. I 'Crispy Forms' to render a form I use with AngularJS. I would like to add the attribute ng-model="NAME" to all form fields by default.

I was thinking this could be done using a mixin added to my form i.e. AngularJSFormMixin:

 class ProfileAuthenticationForm(AngularJSFormMixin, AuthenticationForm):


    def __init__(self, *args, **kwargs):
        super(ProfileAuthenticationForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_method = 'post'
        # turn off HTML5 validation
        self.helper.attrs = {'novalidate': ''}
        self.helper.form_show_labels = False

        self.helper.layout = Layout(
            Field('username',  placeholder="E-mail", autocomplete='off'),
            Field('password', placeholder="Password", autocomplete='off'),
            HTML('<input type="submit" name="Login" ng-click="submit()" css_class="btn btn-primary btn-block" />'),

        )

but I'm unsure what to do from here with AngularJSFormMixin. Is there a way to auto add ng-model="NAME" to every field by default?

Upvotes: 0

Views: 289

Answers (1)

Austin
Austin

Reputation: 4576

I've never worked with crispy forms before but this is what I have done in the __init__ on my model forms to add a ng-model attribute with a value to it. My 'get-error-elements' directive is used to show errors of the form to the user:

  def __init__(self, *args, **kwargs):                                      
      super(MyForm, self).__init__(*args, **kwargs)                     

      for field in self:                                                    

          field.field.widget.attrs.update({'ng-focus': ''})                 

          field.field.widget.attrs.update({                             
              'ng-model': 'formName.{0}'.format(field.name),            
              'get-error-elements': '',                                 
          })                                                            

Upvotes: 1

Related Questions