4

I have this in Model

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

In my view 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 for saving image or django will do it itself

miku
  • 181,842
  • 47
  • 306
  • 310
Mirage
  • 30,868
  • 62
  • 166
  • 261

2 Answers2

19

Also make sure your form enctype is set in the HTML to submit file data:

<form action="..." method="POST" enctype="multipart/form-data">
Torsten Engelbrecht
  • 13,318
  • 4
  • 46
  • 48
  • 4
    This, in addition to adding `request.FILES` to AccountForm, worked for me. Thanks! – elimisteve May 27 '12 at 07:11
  • For a record, it might be obvious, but if Django creates (generates) your form, `request.Files` isn't required, some details https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/ – potar Nov 18 '16 at 12:48
  • In addition to the above link - https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.get_form_kwargs – potar Nov 18 '16 at 13:11
18

You need to pass request.FILES to your account form as well.

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

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

Other than the save() and save_m2m() methods, a ModelForm works exactly the same way as any other forms form. For example, the is_valid() method is used to check for validity, the is_multipart() method is used to determine whether a form requires multipart file upload (and hence whether request.FILES must be passed to the form), etc.

miku
  • 181,842
  • 47
  • 306
  • 310