Michael August
Michael August

Reputation: 29

Image is not coming up properly

I'm working on a little e-commerce site. when I post a product from my site, the image(picture) doesn't show but when I post from the admin panel, the image shows so I don't why. I need help on this please. This is the code. The code below is from the model.py

class OrderedItem(models.Model):
    name = models.CharField(max_length=50)
    price = models.FloatField()
    image = models.ImageField(upload_to='pics')

    def __str__(self):
        return self.name

The code below is from the views.py

def additem(request):
    if request.method == 'POST':
        stock_name = request.POST['stock_name']
        stock_price = request.POST['stock_price']
        stock_image = request.POST['stock_image']

        new_item = Stock(stock_name=stock_name, stock_price=stock_price, stock_image=stock_image)
        new_item.save()
        return redirect('/')
    else:
        return render(request, 'post.html')

the code below is from the html page

<form action="{% url 'additem' %}" method="post">
    {% csrf_token %}

    <div class="form-group">
        <input type="text" name="stock_name" id="" placeholder="stock_name">
    </div>
    <div class="form-group">
        <input type="text" name="stock_price" id="" placeholder="stock_price">
    </div>
    <div class="form-group">
        <input type="file" name="stock_image">
    </div>
    <div class="form-group">
        <input type="submit" value="Additem" class="btn btn-primary btn-lg">
    </div>
</form>

Upvotes: 0

Views: 37

Answers (1)

ngawang13
ngawang13

Reputation: 673

You need to add enctype='multipart/form-data' in the form otherwise no file will be accepted.

<form method="POST" action="" enctype='multipart/form-data'>

To get the images inputted in your html file

stock_image = request.FILES['stock_image']

Upvotes: 1

Related Questions