Issue
I want to upload images in the django admin interface. During development everything works fine but when I put the files on my server it doesn't work. I have two different paths on my Server. One where I put all my source files and one where I put all the static files.
Path for source files: /htdocs/files/project/
Path for static files: /htdocs/html/project/
If I upload an image, then it is saved in /htdocs/files/project/media/
. But I want to save it in /htdocs/html/project/
. How can I change the path?
Here are my settings:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
'/var/www/ssd1257/htdocs/html/'
)
And here is my model:
class News(models.Model):
title = models.CharField(max_length=200, null=False)
date = models.DateField(null=False, default=datetime.now)
text = models.TextField(null=False, blank=True)
image = models.ImageField(upload_to="./news/")
Solution
The uploaded files are saved normally in the following path MEDIA_URL + the path specified in “upload_to” attribute in the model class
So in your case, MEDIA_ROOT = os.path.join(BASE_DIR, 'media') = “/htdocs/files/project/media” Django will create the path if it doesn’t exits
But I didn’t get the dot in-frontront of ‘upload_to’ to path(“./news/“)
So if you want to change the path where uploaded files are stored, simply change the MEDIA_ROOT Note, please provide the absolute full path
I guess it will be MEDIA_ROOT = '/var/www/ssd1257/htdocs/html/project'
Also, its better to rename the uploaded files before saving to avoid file_name conflicts
def get_news_image_path(instance, filename):
path_first_component = ‘news/‘
ext = filename.split('.')[-1]
timestamp = millis = int(round(time.time() * 1000))
file_name = ‘news_’ + str(instance.id) + str('_logo_image_') + timestamp + str('.') + ext
full_path = path_first_component + file_name
return full_path
class News(models.Model):
title = models.CharField(max_length=200, null=False)
date = models.DateField(null=False, default=datetime.now)
text = models.TextField(null=False, blank=True)
image = models.ImageField(upload_to=get_news_image_path)
Now the uploaded files will be saved in '/var/www/ssd1257/htdocs/html/project/news’
You are Done
In addition, also set appropriate MEDIA_URL
Ex: MEDIA_URL = “media So when generated URL for the upload images will be MEDIA_URL + upload_to path
Also, configure the web server to serve these URLs from appropriate locations
Answered By - Iyvin Jose
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.