'django download a file filtered from a list of files
I'm working on a website where I have multiple excel files uploaded by users and stored in the DB, then a user chooses a file's name and date from a dropdown list and this specific file should be downloaded to him. right now I can get the File object that he requested but can't download it correctly.
This is my Models.py
class File(models.Model):
file_name = models.TextField(max_length=1000, default='myFile')
created_at = models.DateTimeField(
default=datetime.datetime.now().replace(microsecond=0))
file = models.FileField()
file_class = models.CharField(
max_length=20, default='')
def __str__(self):
return self.file_name
This is the part where I store the file in Views.py:
modelFile = File()
now = datetime.datetime.now().replace(microsecond=0)
file_class = request.POST['select_course']
Fname = request.POST['file_name']
myFile = convertToBinaryData(uploaded_fileName)
xlfile = ContentFile(myFile)
modelFile.file.save(Fname, xlfile)
modelFile.file_class = file_class
modelFile.created_at = now
modelFile.file_name = Fname
modelFile.save()
And here is where I retrieve and download the file in Views.py :
def viewTrial(request):
if request.method == "POST":
chosen_filename = request.POST['select_trial']
chosen_date = request.POST['select_trial2']
date = pd.to_datetime(
chosen_date, infer_datetime_format=True).strftime('%Y-%m-%d %H:%M')
FileToView = File.objects.filter(created_at__contains=date).filter(
file_name__contains=chosen_filename)
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename=%s' % chosen_filename+".xls"
return response
else:
return render(request, "model/trials.html", {})
this code downloads an excel file with only the file name written in it, I've seen multiple questions here regarding this issue and the downloading, and none worked out for me.
if I changed the FileToView to be like this:
FileToView = File.objects.filter(created_at__contains=date).filter(
file_name__contains=chosen_filename).values('file')
then the excel file has a Queryset written in it like this:
{'file': 'myTest'}
where 'myTest' is the file name.
the different thing that I have is that I need to download the file that I've filtered from a list of files, I've been trying for a week now since I'm new to django, and I'll be thrilled to find a solution!
any help is appreciated!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
