1

I spent some time adding some css to a input field with submit button. However, I was still only learning how to use django forms and found I had to use 'form.as_p' in my template. As a result, I lost the styling I wanted to have. What methods exist to add styling to django form elements?!

P.s. I didn't post up any of my code because it's stock standard. Just a regular template connected with form/model. Just curious about how to add the styling.

elmo330
  • 383
  • 2
  • 5
  • 12
  • Possible duplicate of [CSS styling in Django forms](http://stackoverflow.com/questions/5827590/css-styling-in-django-forms) - This could help you, it's for a table but works for p as well. – Henrik Andersson Oct 12 '15 at 02:23

2 Answers2

0

Your Django form elements are rendered with an id matching the given field name for example a form like this:

BasicForm(forms.Form):
    first_name = models.CharField(...)
    last_name = models.CharField(...)

will get rendered with ids for each input element like first_name_id and last_name_id, you can then apply css styles using those ids, if you wish to add a class to all form fields (if you are using something like bootstrap) you can modify form field widgets like this:

BasicForm(forms.Form):
    first_name = models.CharField(...,
                                  widget=forms.TextInput(attrs={'class' : 'myclass'})
    last_name = models.CharField(...,
                                 widget=forms.TextInput(attrs={'class' : 'myfieldclass'})
Jesus Gomez
  • 1,460
  • 13
  • 30
0

Add form-control css class to the widgets.

The form class is the access point of the input tags through widgets. By changing the widget attr from the constructor method in form.Form.

This method self.visible_fields() is to get all the visible field that can view in frontend.

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    
        for field in self.visible_fields():
            field.field.widget.attrs.update({'class': 'form-control'})