Home > Blockchain >  Setting css class to field in form depending of it's type
Setting css class to field in form depending of it's type

Time:07-24

I want to manually render login and signup forms in Django. Here is my code:

{% load widget_tweaks %}


{% for field in form.visible_fields %}
    <div >
        <label >{{ field.label_tag }}</label>
        <div >
        {% if form.is_bound %}
            {% if field.errors %}
                {% render_field field %}
                {% for error in field.errors %}
                    {{ error }}
                {% endfor %}
            {% else %}
                {% render_field field %}
            {% endif %}
        {% else %}
            {% render_field field %}
        {% endif %}

        {% if field.help_text %}
            <p>{{ field.help_text }}</p>
        {% endif %}
        </div>
    </div>
{% endfor %}

{% if form.non_field_errors %}
  <div >
    {% for error in form.non_field_errors %}
      {{ error }}
    {% endfor %}
  </div>
{% endif %}

My question: is it possible to check in a loop what type the field has and, depending on the field, assign a specific CSS class?

For example:

  1. Field_1 has type text, so we apply css-class-1 to it
  2. Field_2 has a checkbox type, so we apply css-class-2 to it

CodePudding user response:

you can use the django form that is inherited from modelform to define specific css class to the form fields.

for instance, models.py file:

class Post(models.Model):
    title=models.CharField(max_length=254)
    text=models.TextField() 

forms.py file

from . import models 
class PostForm(forms.ModelForms):
    class Meta():
        model=models.Post
        fields='__all__'
        widgets={
               'title':forms.TextInput(attrs={'class':'textinputclass'}), #--->> you can use this textinputclass as the css class in your css file to style the title field of your forms.
                'text':forms.Textarea(attrs={'class':'content'})
                }

now in your static>css>yourcss.css you can access the class that we defined above as normal css class.

.content{
  font-size:15px;
}

That's all.

  • Related