0

I am new to Django and trying to save image to database i have written few lines code, which are not showing any error but are not able to save image to database.

View:-

def IndexView(request):
    print("index view..")
    if request.method == 'POST':
        print("post")
        form = ImageForm(request.POST, request.FILES)
        print("form {}".format(form))
        if form.is_valid():
            print("valid..")
            form.save()

    form = ImageForm()
    return render(request, "index.html")

my template:-

<div class="container">
    <form enctype="multipart/form-data" action="" method="post">
        {% csrf_token%}
        <hr><br><br>
        <input type="file" name="" id="" required/>
        <br><br>
        <input type="submit" class="btn btn danger" value="Upload">
    </form>
</div>

model:-

class MyImage(models.Model):
    image = models.ImageField(upload_to="myimage")
    name = models.CharField(max_length=200, blank=True, default="")

Hope to here from you soon Thanks in advance

5
  • 1
    The "name" attribute of the file input in your template must match the name of the image field on your ImageForm form. Currently it's empty Commented Sep 17, 2021 at 8:16
  • Do you have model of this if yes please share Commented Sep 17, 2021 at 8:24
  • yes i sharing the model. Commented Sep 17, 2021 at 8:28
  • @sarangkkl i have added the model above, please have a look.. Commented Sep 17, 2021 at 8:30
  • @lain Shelvington thanks you were write.. Commented Sep 17, 2021 at 8:32

1 Answer 1

1
<div class="container">
    <form enctype="multipart/form-data" action="" method="post">
        {% csrf_token%}
        <hr><br><br>
        <input type="file" name="image" id="" required/>
        <br><br>
        <input type="submit" class="btn btn danger" value="Upload">
    </form>
</div>

def IndexView(request):
    print("index view..")
    if request.method == 'POST':
       image=request.FILES.get('image') 
       name=///give a nmae to your image
       x = MyImage.objects.create(image=image,name = name)
       x.save()
       return render(request, "index.html")

by this way you can see your image in the admin panel if you get any error assking for module install pillow just search google

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.