How to apply Bootstrap 4 styles for 'Choose File' input to a Django form?

10,727

After crawling the interwebs, I found the link below but first here's the skinny:

Implementing bootstrap4 style on a choose file button while using a modelForm

***forms.py***
class ProfileForm(forms.ModelForm):
class Meta:
    model = Profile
    fields = ('avatar',)
    widgets = {'avatar':forms.FileInput(
        attrs={'style':'display: none;','class':'form-control', 'required': False, } 
         )}


****update_form.html****
**call each feil individualy**
<label class="btn btn-outline-secondary btn-lg">
    *button text goes here*
  {{profile_form.avatar}}
</label>

The main point is to use a span with a bootstrap class in HTML. Then nest your form.field inside while passing in 'style' attributes (CSS)'display: none;'

https://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3

Share:
10,727
cbuch1800
Author by

cbuch1800

Computer Science A Level student Building a webapp to run elections in school. Using Django and Python

Updated on June 09, 2022

Comments

  • cbuch1800
    cbuch1800 about 2 years

    I am displaying a form that involves uploading an image in my Django template.

    This is the template:

    {% extends 'header.html' %}
    
    {% block content %}
    <br>
    <div class="w-50 card mx-auto">
        <div class="card-body text-center">
            <h2 class="card-title">New Post</h2>
            <form method="post">
                {% csrf_token %}
                <p><strong>
                    Title<br>
                    {{ form.Title }}
                </strong></p>
                <p><strong>
                    Description<br>
                    {{ form.Description }}
                </strong></p>
                <p><strong>
                    Image 
                    {{ form.Image }}
                </strong></p>
                <p><strong>
                    Election<br>
                    {{ election_form.PostElection }}
                </strong></p>
                <button type="submit" class='button btn btn-outline-dark'>Post</button>
            </form>
        </div>
    </div>
    
    {% endblock %}
    

    As you can see, the submit button on the form has some Bootstrap attached. This makes it look different to the Choose File button on the image upload form. How do I apply the Bootstrap applied to the submit button to the button in the form?

  • cbuch1800
    cbuch1800 over 6 years
    Are you sure that replacing the code that renders the Django form with the above will still link the input to the Django form?
  • WebDevBooster
    WebDevBooster over 6 years
    Yes, 100%. Click the "run code snippet" button to see it working.
  • WebDevBooster
    WebDevBooster over 6 years
    I mean, that code snippet needs to be part of your Django form i.e. inside it.