Reputation: 99
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
Upvotes: 0
Views: 146
Reputation: 802
<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
Upvotes: 1