FunLovinCoder
FunLovinCoder

Reputation: 7897

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_valid():
            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?

Upvotes: 1

Views: 1494

Answers (1)

FunLovinCoder
FunLovinCoder

Reputation: 7897

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

Upvotes: 2

Related Questions