How can you create a form button to select a Django file?

I am trying to create my Django file upload button , but since it is processed through a form and is clearly not written in HTML in the template, I cannot erase it directly from other input buttons of the type from HTML and CSS.

I tried adding my CSS class to my forms.py , but it placed the default Django file upload button located on top of my stylized CSS 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 in my Meta class as follows:

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

but it was like my first attempt.

Is there any other way to accomplish this, or are there some logical errors you might find in my code?

+7
source share
3 answers

For posterity, here is the solution 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> 
+3
source

If you want the file upload button style to define another button or link and the style that is. Then set the click event to trigger the file download button.

HTML:

 <div> <a id="browse" class="my_class">Browse</a> <input type="file" name="data" style="display: none" /> </div> 

JavaScript:

 $('#browse').click(function(){ $(this).parent().find('input').click(); }); 

To make this work in Django form, you can do it with widget .

+1
source

I know this is an old thread, but the answers above do not solve the problem, and I almost wanted to post a similar question. I found the answer, check it here: How can I create django forms using bootstrap CSS?

0
source

Source: https://habr.com/ru/post/1211023/


All Articles