Issue
I am creating a website in django. I need to store the image as binary in mysql database as well as check its size before saving. Tried many ways nothing seems to help.
views.py
def client_create_view(request):
base_form = ClientForm(None, initial=initial_data)
context={ "form": base_form }
if request.method == 'POST':
form = ClientForm(request.POST,request.FILES)
if form.is_valid():
form.save()
return render(request,'cc.html',context)
forms.py
class ClientForm(ModelForm):
photo = forms.ImageField(required=False)
def clean(self):
super(ClientForm, self).clean()
photo_image = self.cleaned_data['photo'].file.read()
if photo_image.file_size > 0.250:
raise ValidationError(['Image Size should be lower than 250kb'])
html
<form method="post" enctype='multipart/form-data'>
#some data
</form>
Solution
You need to handle things manually, you can't use form.save()
def client_create_view(request):
base_form = ClientForm(None, initial=initial_data)
context = { "form": base_form }
if request.method == 'POST':
form = ClientForm(request.POST,request.FILES)
if form.is_valid():
form.instance.image = request.FILES["image_file"].read()
form.instance.save()
return render(request,'cc.html',context)
Answered By - Mohamed ElKalioby
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.