开发者

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() 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜