I've tested this method and it functions correctly. Hopefully, you find success with it as well.
To start, you'll need to create a relevant form in your forms.py file following this structure:
from django import forms
class FileForm(forms.Form):
file = forms.FileField(required=True)
When implemented in your HTML file, it should look like this:
<div>
<form id="file_form" action="/application/new_file/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label class="btn btn-info btn-xs" for="subgroup_file" style="background-color: #042d63;border-color: #dddddd;border-width: 2px;color: white;padding: 5px 21px;" id="send_file" data-toggle="tooltip" data-placement="auto top" title="Choose The File">
<input id="the_file" name="file" type="file" style="display:none;">
<span class="glyphicon glyphicon-paperclip"></span>
</label>
<input type="submit" id="file_form_submit" class="my-small-btn" value="Submit" data-toggle="tooltip" data-placement="auto top" title="Submit File">
</form>
</div>
Then, triggering the id=file_form
will result in:
$('#file_form').submit(function(event){
event.preventDefault();
var formData = new FormData(this); //get data of form elements for submission
formData.append('sg_id', '{{ sg_id }}'); //add additional data to form's data
$.ajax({
url: "/application/new_file/",
type: "POST",
enctype: 'multipart/form-data',
data: formData,
processData: false,
contentType: false,
cache: false,
success: function (data) {
if(! data.created){
location.reload();
} else if(! data.valid_extension){
swal({
title: 'You can only submit PDF files',
text: '',
icon: 'error',
timer: 5000,
});
}
}
});
});
In addition, there is a helpful sweet alert that notifies users they can only upload PDF files. The URL then directs you from urls.py
to the saveFile
function in views.py
, which typically looks like this:
def saveFile(request):
if(request.user != AnonymousUser()):
try:
if request.method == 'POST':
file_form = FileForm(request.POST, request.FILES)
sg_id = request.POST.get("sg_id")
subgroup = SubGroup.objects.get(pk=sg_id)
if(file_form.is_valid()):
file = file_form.cleaned_data["file"]
name = str(file)
f, extension = os.path.splitext(name)
if(extension in valid_extensions):
obj = Files.objects.create(
file = file,
subgroup = subgroup,
creator = request.user,
created_at = datetime.datetime.now(),
name = name
)
.......
.......
.......
The SubGroup
and Files
are defined objects in models.py
, establishing connections to the database.