开发者

Django: Prevent form fields being cleared when invalid data entered

I have the following form, which allows a user to submit a file and email address.

from django import forms
from django.utils.translation import gettext_lazy as _
from django.core.validators import validate_email

class UploadFileForm(forms.Form):
    email = forms.EmailField()
    file = forms.FileField()

class EmailField(forms.CharField):
    default_error_messages = {
        'invalid': _(u'Enter a valid e-mail address.'),
    }
    default_validators = [validate_email]

Here's the view:

def upload_file(request):

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_v开发者_高级运维alid():
            email = form.cleaned_data['email']
            handle_uploaded_file(email, request.FILES['file'])
            return HttpResponseRedirect('/thanks')
    else:
        form = UploadFileForm()
    return render_to_response('upload_file.html', {'form': form},   
        context_instance=RequestContext(request))

If the user submits the form with an invalid email, the form is displayed back to the user, but the fields are cleared. What's the correct way to prevent this clearing of form fields?


Silly mistake. Updated my template to include the form values. All working now.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜