I have just launched my project into production. I have a functionality where the user can upload their own profile picture. People can upload their pictures, it is even stored in the correct directory. However, when I try to achieve it I get a 404 not found error . I am using Pythonanywhere and all pictures are stored at path:
home/[username]/[project_name]/media/profile_picture
Here are the relevant code snippets:
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
class Person(models.model):
...
profile_picture = models.ImageField(upload_to="profile_picture", blank=True, null=True)
...
profile_page.html
...
<div class="photo-container">
{% if profile.profile_picture %}
<img src="{{ profile.profile_picture.url }}">
{% else %}
<img src="{% static 'external_page/assets/img/placeholder.png' %}">
{% endif %}
</div>
...
When I isolate the tag:
{{ profile.profile_picture.url }}
I get:
/media/profile_picture/[name_of_image_file].jpg
Update:
I suspect that the error lies in the serving of the files and not in me referencing its path. I suspect that since I also get an 404 not found when
I explicitly try to access the url of the media fiels ( https://www.website.com/media/profile_picture/[name_of_image_file.jpg] ),
whilst I am able to access the respective static files. ( https://www.website.com/media/assets/[some_asset] )
Although, that is the result of the python manage.py collectstatic
You need to add the URL and directory path to your media files. On the Webapp section on pythonanywhere.
I can see in your case. Your MEDIA_ROOT is:
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
So, in the Directory you have to put /home/username/media
instead of /home/username/media_cdn
.
This is how I got around the problem, I hope it helps.
Just switch from
{{ profile.profile_picture.url }}
to
{{ profile.profile_picture.path }}
尝试执行以下操作,将{{MEDIA_URL}}添加到src中:
<img src="{{ MEDIA_URL }}{{ profile.profile_picture.url }}">
You are storing the files in the filesystem of the pythonanywhere instance. I haven't used pythonanywhere but probably the files there aren't persistent. You need to store the media files in a persistent storage like S3. I strongly recomend you to use django-storages to handle this for you. The setup takes a bit of time but it will solve your problems.
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.