Issue
My motive is to show the product_image
in the orderlist
template. The ProductOrder
works well and it also stores the product_image
url in the img
in the database. But when tried to show the image in the template, it has shown an error. Where did the actual problem occur? Please give me a relevant solution.
models.py:
class Products(models.Model):
user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True)
product_image = models.ImageField(blank=True, null=True, upload_to = "1_products_img")
class ProductOrder(models.Model):
User = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='UserOrderRelatedName',on_delete=models.CASCADE)
img = models.ImageField(blank=True, null=True)
views.py:
this works well,
def Order(request, quick_view_id):
OrderProduct = get_object_or_404(Products, pk=quick_view_id)
if request.method == "POST" and request.user.is_authenticated:
ProductOrder.objects.create(
img = OrderProduct.product_image
)
return redirect('quick_view', quick_view_id)
def OrderList(request):
AllOrder = ProductOrder.objects.all()
context = {
"AllOrder":AllOrder,
}
return render(request, "order_list.html", context)
template:
{% for order in AllOrder %}
<img style="width: 100px;" src="{{order.img.url}}">
{% endfor %}
error:
ValueError at /OrderList/
The 'img' attribute has no file associated with it.
Request Method: GET
Request URL: http://127.0.0.1:8000/OrderList/
Django Version: 4.0.4
Exception Type: ValueError
Exception Value:
The 'img' attribute has no file associated with it.
Exception Location: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\django\db\models\fields\files.py, line 40, in _require_file
Python Executable: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\Scripts\python.exe
Python Version: 3.9.5
Python Path:
['D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39',
'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site\\env',
'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce '
'site\\env\\lib\\site-packages']
Server time: Sat, 30 Jul 2022 13:52:11 +0000
Solution
If the product_image
or img
does not have any image, you have to make an if condition that checks for the existence of the image, before rendering it.
For example, in your template:
{% for order in AllOrder %}
{% if order.img %}
<img style="width: 100px;" src="{{order.img.url}}">
{% else %}
<img style="width: 100px;" src="<some static image url>">
{% endif %}
{% endfor %}
Answered By - Rohit Rahman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.