I am new to Django, and I am doing a simple web application that saves and displays products. But my problem is when I tried to display the product information I could display everything except the product image. You can see my code below.
settings.py in the static section:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
The main urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pages.urls')),
path('products/',include('products.urls')),
] static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
The models.py of the Products application:
from django.db import models
from django.db.models.deletion import CASCADE
from django.db.models.fields import CharField, DateField, DateTimeField
from datetime import datetime
from django.db.models.fields.related import ForeignKey, ManyToManyField
# Create your models here.
class Product(models.Model):
categories = [
('Phone', 'Phone'),
('Computer', 'Computer'),
]
name = models.CharField(max_length = 50, default='Nothing', verbose_name='title')
content = models.TextField(default='Empty', null = True, blank = True, verbose_name='description')
price = models.DecimalField(max_digits = 5, decimal_places = 2, default=0.0)
image = models.ImageField(upload_to = 'photos/%y/%m/%d', default='media/photos/default/default_product.png',
verbose_name='picture')
active = models.BooleanField(default = True)
category = models.CharField(max_length=50, null=True, choices=categories)
def __str__(self):
return self.name
class Meta:
#verbose_name = 'name'
ordering = ['-name']
And finally in the products.html:
{% block content %}
{% comment "" %}{{pro}}{% endcomment %}
{% for product in pro %}
<h1>{{product.name}}</h1>
<h1>{{product.content}}</h1>
<h1>{{product.price}}</h1>
</img src="{{product.image}}" alt="">
<h1>-----------------------------------</h1>
{% endfor %}
{% endblock content %}
CodePudding user response:
try this.Note that to get image you have to access the .url
{% block content %}
{% comment "" %}{{pro}}{% endcomment %}
{% for product in pro %}
<h1>{{product.name}}</h1>
<h1>{{product.content}}</h1>
<h1>{{product.price}}</h1>
<img src="{{ product.image.url }}" alt=""/>
<h1>-----------------------------------</h1>
{% endfor %}
{% endblock content %}
CodePudding user response:
You have a typo in your img
tag
Change this line
</img src="{{product.image}}" alt="">
to
<img src="{{ product.image.url }}" alt=""/>