Reputation: 33
I have activated i18n in my Django project and used i18n_patterns in my urls.py
. All translations work fine and change whenever the language code in the URL changes. The problem comes to the picture in the media folder.
I have a few pictures in the media folder as the slider background and they get changed every few seconds. With this i18n_patterns, it reads media files from /en/media/
instead of /media/
. In this case, I created the /en/media/
folder just for English and created the same folder /zh/media/
folder for Chinese. But the problem is, it always returns 404 even the images are there. All images in the /zh/media/
folder do not show. And only 2 out of 4 images in the /en/media/
folder shows. This is very confusing to me. Hope you guys have any idea of what is happening here.
Below is the portion of code in related files:
settings.py
LANGUAGE_CODE = 'en'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale')
]
LANGUAGES = [
('en', _('English')),
('zh', _('Chinese')),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
urlpatterns = [
]
urlpatterns += i18n_patterns(
path('admin/', admin.site.urls),
path('', include('pages.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
template.html
<img src="media/{% image_file_name %}" />
On the console, it shows as follows even though the file is present.
[TIMESTAMP] "GET /zh/media/XXX.jpg HTTP/1.1" 404 2798
Upvotes: 0
Views: 285
Reputation: 12096
It is a bad practice to use <img src="media/{% image_file_name %}" />
.
Instead do this <img src="{{ image_field.url }}" />
. The url will get rendered properly using this. You may read more on this topic in the official docs.
Upvotes: 0