Do I need extra code for Image Field in Django
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(): # A开发者_StackOverflowll 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
Also make sure your form enctype
is set in the HTML to submit file data:
<form action="..." method="POST" enctype="multipart/form-data">
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()
andsave_m2m()
methods, aModelForm
works exactly the same way as any other forms form. For example, theis_valid()
method is used to check for validity, theis_multipart()
method is used to determine whether a form requires multipart file upload (and hence whetherrequest.FILES
must be passed to the form), etc.
精彩评论