Danae Vogiatzi Danae Vogiatzi - 1 month ago 8
Python Question

django get files from different directories [NOT CONFIRMED]

I have a django app (installed on a Debian server) where there is file upload.

Traditionaly, it ulpload in a folder in site_media.
For some reason,(please don't ask why,take it for granted) I have to save the files in a different disk.

The path to the other disk is /disk/site_media
The saving do the other disk is donw succesfully!
When I try to open the file by clicking on it , I get File not Found.

I am open to ideas!!!

Here's my code when uploading the file:

obj = form.save(commit=False)
obj.user_id = self.request.user.pk
obj.save()
initial_path = obj.file.path
print(initial_path)
new = settings.MEDIA_ROOT_NEW + obj.file.name
print(new)
#os.rename(initial_path,new)
shutil.move(initial_path, new)


I upload the files in my EmployeeDoc class:

class EmployeeDoc(models.Model):

file = models.FileField('DocFile', upload_to='edocs/')
employee = models.ForeignKey(Employee , related_name='documents')
user = models.ForeignKey(User , related_name='employeedocs')
created_at = models.DateTimeField(auto_now_add=True,default=timezone.now)
update_at = models.DateTimeField(auto_now=True,default=timezone.now)


I get the files in my template with a function written under my Employee class:

class Employee(models.Model):
name ...
last ...

def getDocuments(self):
return EmployeeDoc.objects.filter(employee_id=self.pk,del_f=0)


Here are my paths in settings.py:

MEDIA_ROOT = os.path.join(PROJECT_PATH, 'site_media/')
MEDIA_ROOT_NEW = '/disk/site_media/'
MEDIA_URL = '/site_media/'


In my urls.py despite all the othe urls I have:

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Answer

You're serving MEDIA_ROOT directory on MEDIA_URL url. That means files from MEDIA_ROOT_NEW won't be accessible on MEDIA_URL url.

If you want to serve all your media files from MEDIA_ROOT_NEW, change line:

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

to

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT_NEW)

If you want to serve both directories on one URL, consider using nginx or other web server for that.

Comments