here is the problem. in my project user is going to upload an excel file and right after that the app must take it and read it using pandas
. file is uploaded in media/projects/%Y/%m/%d/
:
views.py
:
if request.method == 'POST' and request.FILES['createdatabase']:
user = request.user
data = request.FILES['createdatabase']
new = NewProject(
user=user,
data=data,
)
new.save()
models.py
:
from django.db import models
from django.contrib.auth.models import User
class NewProject(models.Model):
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
data = models.FileField(blank=True, upload_to='projects/%Y/%m/%d/')
u = models.TextField(blank=True)
v = models.TextField(blank=True)
w = models.TextField(blank=True)
u
, v
, and w
are in the data file that the user uploads and the app must read it. when I want to read the file in pandas
using the read_excel()
method, it needs the file URL. using data.url
or data.path
does not work seems it just says the file name or the wrong path media/datafilename.xlsx
. the true file URL must be something like media/2022/07/01/datafilename.xlsx
. also, some files might have the same names that are uploaded by the users. so the Django just adds a random string to it. but data.url
and data.path
print the main name of the file. not the changed one.
any help will be appreciated.
CodePudding user response:
Try this one. https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.FileField.upload_to
from datetime import datetime
from uuid import uuid4
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/projects/<year>/<month>/<day>/<filename>
ext = filename.split(".")[-1]
filename = "%s.%s" % (uuid4(), ext)
today = datetime.now()
today_path = today.strftime("%Y/%m/%d")
return 'projects/{0}/{1}'.format(today_path, filename)
class NewProject(models.Model):
data = models.FileField(upload_to=user_directory_path)
For accessing the uploaded file,
project.data.path # etc: '/media/projects/2022/07/02/4cc38320-556c-490a-90d5-f8834bf75275.xlsx'
Refer https://docs.djangoproject.com/en/4.0/topics/files/#using-files-in-models