Opened 8 years ago
Closed 8 years ago
#27052 closed Bug (invalid)
Malformed url of uploaded files; uploaded_to parameter is ignored
Reported by: | Laisvas | Owned by: | nobody |
---|---|---|---|
Component: | File uploads/storage | Version: | 1.10 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
1)If your model has a FileField - field with upload_to parameter, the parameter is ignored.
2)File.url method on files attached to objects returns MEDIA_URL + full absolute file path, not the url of the uploaded file.
How to reproduce:
- Fresh Django install, the project name: mysite, the app name: app
#models.py: from django.db import models class InputFile(models.Model): name = models.CharField(max_length=255) upload = models.FileField(upload_to='uploads/%Y/%m/%d/' ) #views.py: from django.shortcuts import render from django.http import HttpResponse from models import InputFile from django.core.files import File def index(request): tmp_file=open('/home/test/mysite/app/media_files/a.txt') django_file = File(tmp_file) file_name = django_file.name file_size = django_file.size saved = InputFile(name='a', upload=django_file) saved.save() ## Let's check does the file is saved: file_pk = saved.pk file_url = saved.upload.url upload_path = saved.upload.path output = 'File name: {0}, file size: {1}, file_pk: {2}, url: {3}, path: {4} '.format(file_name, file_size, file_pk, file_url, upload_path) return HttpResponse(output) # settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = "/home/test/mysite/app/media_files/" # urls.py from django.conf.urls import url from django.contrib import admin from app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^file/', views.index), ]
- Put a test file in your MEDIA_ROOT (i.e. '/home/test/app/media_files/a.txt'
- The output:
File name: /home/test/mysite/app/media_files/a.txt,
file size: 3,
file_pk: 1,
url: /media/home/test/mysite/ap/media_files/a_55k5fIW.txt,
path: /home/test/mysite/file/media_files/a_55k5fIW.txt
- The file was saved to /home/test/mysite/file/media_files/a_55k5fIW.txt
Expected result
Django v. 1.9.8 returns on the same code:
...
url: /media/uploads/2016/08/11/a.txt,
path: /home/test/mysite/app/media_files/uploads/2016/08/11/a.txt
...
The file was saved to /home/test/mysite/app/media_files/uploads/2016/08/11/a.txt
NB
The same problem is on Django version 1.11.dev20160811204658
You need to use
FieldFile
when interacting withFileField
if you wantupload_to
to be respected. Please take a look at the file topic guide for an example. If you need help, take a look at TicketClosingReasons/UseSupportChannels for ways to get help. Thanks!