I have create a small project , where i am stuck at one point
Issue : not able to get images dynamically and display in template
i.image.url -> at this line in html images are not coming from folder media
when i runserver the media folder is not getting created and images are not copied from pics to media folder
seetings.py
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = []
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'web_components')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL='/media/pics/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'LEARN_FROM_TELUSKO',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'PROJECT.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'Template')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
},
},
]
urls.py
urlpatterns = [
path('', include('LEARN_FROM_TELUSKO.urls')),
path('admin/', admin.site.urls)
]
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
class courses(models.Model):
name = models.CharField(max_length=100)
price = models.IntegerField()
image = models.ImageField(upload_to='pics', height_field=None, width_field=None, max_length=None)
views.py
def index(request):
dest = courses.objects.all()
return render(request,'index.html',{'getdetails':dest})
template
{% for i in getdetails %}
<div class="col-xl-3 col-lg-3 col-md-6 col-sm-12">
<div class="product-box">
<i>
<img src="{{ i.image.url }}"/>
</i>
<h3>{{ i.name }} </h3>
<span>{{ i.price }}</span>
</div>
</div>
{% endfor %}
Project structure:
I uploaded files to 127.0.0.1/8000/admin
:
Here they are mentioned in the db