It says 'Image' attribute has no file associated what does that mean? How do I solve this issue? I tried to search in internet and couldn't understand anything because I've only started learning.
My view:
def bookdata(req):
if req.method == "POST":
b_name = req.POST.get('book name')
a_name = req.POST.get('author name')
p_year = req.POST.get('published year')
price = req.POST.get('price')
image = req.FILE['image']
obj = BookDetails(Name=b_name, A_Name=a_name, P_Year=p_year, Price=price, Image=image)
obj.save()
return redirect(add_books)
My model:
class BookDetails(models.Model):
Name = models.CharField(max_length=30, null=True, blank=True)
A_Name = models.CharField(max_length=30, null=True, blank=True)
P_Year = models.IntegerField(null=True, blank=True)
Price = models.IntegerField(null=True, blank=True)
Image = models.ImageField(upload_to="book images", null=True, blank=True)
Template:
<table >
`<thead>`
<tr>
<th>Name</th>
<th>A_Name</th>
<th>P_Year</th>
<th>Price</th>
<th>Image</th>
</tr>
</thead>
{% for i in data %}
<tr>
<td>{{ i.Name }}</td>
<td>{{ i.A_Name }}</td>
<td>{{ i.P_Year }}</td>
<td>{{ i.Price }}</td>
<td>
<img src="{{ i.Image.url}} ">
</td>
</tr>
{% endfor %}
CodePudding user response:
The error causes because no image is associated with the image field. Use the following code to store image properly:
def bookdata(req):
if req.method == "POST":
b_name = req.POST.get('book name')
a_name = req.POST.get('author name')
p_year = req.POST.get('published year')
price = req.POST.get('price')
image = req.FILES['image'] # Change Done Here
obj = BookDetails(Name=b_name, A_Name=a_name, P_Year=p_year, Price=price, Image=image)
obj.save()
return redirect(add_books)
In the template, you can also make some changes like :
<td>
{% if i.Image %}
<img src="{{ i.Image.url}} ">
{% else %}
<img src="#path_to_default_image">
{% endif %}
</td>