Reputation: 413
I'm developing an application in which I need to put images on the screen. I configured the "settings" file as explained in the django tutorial. But for some reason the images are not found.
settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
MEDIA_ROOT = os.path.join(BASE_ROOT,'media')
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('licitacao.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
exemple.html
<img class="card-img-top figure-img img-fluid rounded" src="{% static "media/800x600.png" %}" alt="Card image cap">
If I change the url static by media, the image appears, however, static files like css and js stop working. How do I run the media and static together?
Upvotes: 0
Views: 1973
Reputation: 174
How do you handle saving your images?
Do you use FileField
or ImageField
in your model?
Say you have a a model like this:
class Image(models.Model):
condo = models.ForeignKey(Condo, on_delete=models.CASCADE, related_name='images')
**image = models.FileField(upload_to="images/")**
uploaded_at = models.DateTimeField(auto_now_add=True)
Then in your template you shouldn't be using static
or media
, but:
<img src="{{ object.image.url }}">
This will generate the correct url to your image.
Also, don't forget to add MEDIA_URL to routes.
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Upvotes: 2
Reputation: 599470
As well as Piyush's answer, you must not have STATIC_ROOT as one of STATICFILES_DIRS. They're separate settings for a reason; keep them separate.
Upvotes: 0
Reputation: 2015
Do not merge static
and media
in same path, keep them different. Something like this.
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
Then try it. It will work.
Upvotes: 0