I'm new in Django. I read a lot on documentation and on this site about my question. But I really can not understand what I should do to make this. Can someone show me with all steps please?
model.py:
class Post(models.Model):
title=models.CharField(max_lengt=50)
img=models.ImageField(upload_to = 'images')
template:
{% for post in posts %}
<h1> {{post.title}} </h1>
<img src="{{post.img}}">
{% endfor %}
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
If I access the admin page, how can I upload the image? In template I can't see image!
Sorry for my bad English. Help me please
In template, use:
{% for post in posts %}
<h1> {{post.title}} </h1>
<img src="{{ post.img.url }}">
{% endfor %}
You have to add {{ post.img.url }}.
Also, make sure that in urls.py, you have:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It will Work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With