Johar Inam Unnar
Johar Inam Unnar

Reputation: 145

Styling django filter form in html

Here's how my django filter form currently looks:

enter image description here

And here's my html code:

      <form action="" method="get" class="form-inline">
           {{myfilter.form|bootstrap}}

         <button class="btn btn-primary" type="submit">
           Search</button>
      </form>

I am having trouble with the following:

  1. How do I bring the filters in center of the page?

  2. How do I change the "Name contains" to "Name"?

  3. How do I change the color of text to white in order to make them more visible?

I have tried to search it online but no luckk. Little help will be appreciated. THANKS!

EDIT:

Here's my filters.py:

class WeeklyFilter(django_filters.FilterSet):
    Name = CharFilter(field_name='Name', lookup_expr='icontains')


    class Meta:
        model = Weekly
        fields = '__all__'
        exclude = ['Close','Score']

And my models.py:

Name = models.CharField(max_length=200, null=True)
Close = models.FloatField(null=True)
Score = models.IntegerField(null=True)
Result = models.CharField(max_length=200, choices=choices1,  null=True)

def __str__ (self):
    return self.Name

EDIT 2:

enter image description here

Upvotes: 2

Views: 6008

Answers (2)

Ankit Tiwari
Ankit Tiwari

Reputation: 4710

How do I bring the filters in center of the page?

form-inline is flexbox container so if you add justify-content-center it will center your form elements.

<form action="" method="get" class="form-inline justify-content-center">

How do I change the "Name contains" to "Name"?

You can override label value of form field by specifying new value to it.

Name = CharFilter(label='Name', field_name='Name', lookup_expr='icontains')

How do I change the color of text to white in order to make them more visible?

To make text white use .text-white class provided by bootstrap and specify it in your Django form by overriding attributes

Name = CharFilter(
  widget=forms.TextInput(
    attrs={
      "class":"form-control text-white text-center",
      "max_length":"100"
    }
  )
)

So your final code for Name field will look like this

Name = CharFilter(
  label='Name',
  field_name='Name',
  lookup_expr='icontains',
  widget=forms.TextInput(
    attrs={
      "class":"form-control text-white text-center",
      "max_length":"100"
    }
  )
)

Upvotes: 7

Diego Ven&#226;ncio
Diego Ven&#226;ncio

Reputation: 6037

And if somebody are using django-filter library, can do it in html file:

...
{% load widget_tweaks %}
...
    <div class="col-10">
        {{ filter.form.somefield.label_tag }}
        {% render_field filter.form.somefield class="form-select form-select-sm" %}
    </div>

pip install django-widget-tweaks

Upvotes: 0

Related Questions