I have read other topics on stackoverflow and on the django website, but I am still confused.
These are my configurations:
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
STATIC_URL = '/static/'
When I run manage.py collectstatic
, my static files will be collected at myproject/assests/
I will store a default profile photo (for using with my models) here: myporject/static/images/default_profile_photo.png
, so when I run collect static, it will be coppied in myproject/assets/images/default_profile_photo.png
Everything fine so far.
On my models.py I have a field:
class UserProfile(models.Model):
photo = models.ImageField(upload_to = get_upload_file_name,
storage = OverwriteStorage(),
default = 'path/to/my/default/image.jpg'))
My main question is: what path should I set to this default atribute? should I benefit from the STATIC_URL somehow?
Other questions: How can I user here the STATIC_URL from settings.py? and what is the usage of STATIC_URL? where and how can I see the effect between using STATIC_URL='/static/' and STATIC_URL='/wtf/'
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'static', 'templates'),
对于每个“ os.path.dirname()”,我在下面还包含一个与父目录相对应的文件,因此在我的示例中,我有四个,它表明根文件夹为当前目录上方的4个文件夹。
Files that are uploaded always go in a subdirectory of MEDIA_ROOT
and are referenced from MEDIA_URL
.
For any FileField
(like ImageField
), you simply give the subdirectory that will be used to store the files that are uploaded to this model.
If you have MEDIA_ROOT
as '/foo/bar/uploads/'
, then in your models you have this:
class Foo(models.Model):
photo = models.ImageField(upload_to='photos')
Then all photos uploaded will be stored in /foo/bar/uploads/photos/
.
Unlike collectstatic
, there is no command to manage media files. You have to deal with them on your own.
Now on setting a default value; in addition to a path, you can add the name of a callable (a function), that is called whenever an instance of the object is saved. You can exploit this:
import os
from django.contrib.staticfiles import finders
from django.config import settings
def get_default_photo_path():
results = finders.find('/default/image.jpg')
if results:
return os.path.join(settings.STATICFILES_DIRS[0], results[0])
class Foo(models.Model):
photo = models.ImageField(upload_to='photos',
default=get_default_photo_path, null=True)
Now, whenever a new object is created, the default value is the static file path to /default/image.jpg
. If for some reason this file doesn't exist (for example, you forgot to add it), None
will be returned. In other to store that, you have to set null=True
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.