Do I need extra code for image field in Django

I have it in Model

image_name = models.ImageField(upload_to='accounts/') 

In my opinion, I have

 def account_form(request): if request.method == 'POST': # If the form has been submitted... form = AccountForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass form.save() return HttpResponseRedirect('/thanks/') # Redirect after POST else: form = AccountForm() # An unbound form return render_to_response('account_form.html', { 'form': form, }) 

Do I need to do extra coding to save the image, or django will do it himself.

+4
source share
2 answers

You need to submit request.FILES to your account form.

 form = AccountForm(request.POST, request.FILES) # A form bound to the POST data 

Link: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

Besides the save() and save_m2m() methods, ModelForm works just like any other form. For example, the is_valid() method is used for validation, the is_multipart() method is used to determine if the forms require multiple files to upload (and therefore whether request.FILES should be passed to the form), etc.

+18
source

Also make sure your enctype form enctype set to HTML for submitting files:

 <form action="..." method="POST" enctype="multipart/form-data"> 
+19
source

All Articles