Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you style Django's file picker form button?

I am attempting to style my Django file upload button, but since it's handled through the form and not explicitly written in the HTML within the template I cannot style it directly with HTML and CSS like I can for other buttons of type input.

I've attempted to add my CSS class within my forms.py, but it is placing the vanilla default Django file upload button on top of my CSS styled button.

My code is as follows:

class FileUploadForm(forms.Form):
    docFile = forms.FileField(
        label = "Select a CSV file",
    )

    class Meta:
        model = FileUpload
        fields = ('docFile')

    def __init__(self, *args, **kwargs):
        super(FileUploadForm, self).__init__(*args, **kwargs)
        self.fields['docFile'].widget.attrs.update({'class': 'my_class'})

I also tried defining a widget within my Meta class like so:

class Meta:
        model = FileUpload
        widgets = {
            'docFile': forms.FileInput(attrs={'class': 'my_class'}),
        }

but that had the same effect as my first attempt.

Is there a different way of accomplishing this or are there some logical errors that you can spot within my code?

like image 653
alacy Avatar asked Jan 13 '15 18:01

alacy


1 Answers

For posterity's sake here is the solution which I found using Bootstrap here.

.fileUpload {
	position: relative;
	overflow: hidden;
	margin: 10px;
}
.fileUpload input.upload {
	position: absolute;
	top: 0;
	right: 0;
	margin: 0;
	padding: 0;
	font-size: 20px;
	cursor: pointer;
	opacity: 0;
	filter: alpha(opacity=0);
}
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet"/>
<div class="fileUpload btn btn-primary">
    <span>Upload</span>
    <input type="file" class="upload" />
</div>
like image 113
alacy Avatar answered Sep 21 '22 13:09

alacy