简体   繁体   English

Django:防止输入无效数据时清除表单字段

[英]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? 什么是防止表单字段清除的正确方法?

Silly mistake. 愚蠢的错误。 Updated my template to include the form values. 更新了我的模板以包含表单值。 All working now. 一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django - 表单无效时输入数据的先前页面 - Django - Previously page with data entered when form is invalid 尝试创建新的 Django CreateView 表单时,我的 forms 正在填充上一个表单中输入的数据 - When trying to create a new Django CreateView form, my forms are being populated with the data that was entered in the last form 无效提交的 Django 表单数据临时在模板的其他地方使用 - Invalid submitted Django form data being temporarily used elsewhere in a template 创建模型表单实例时,将清除表单中未包含的db字段 - db fields not included in the form are cleared when creating a model form instance 表单字段未显示Django - Form fields not being displayed Django 输入无效值作为日期时的Django falis - Django falis when invalid values entered for dates 如果在 Django 中输入任何无效数据,则在输入字段下方引发表单错误 - Raise Form error below the input field in case any invalid data is entered in Django 如何允许提交表单,但防止使用 Django Admin 3.x 保存空白字段? - How to allow a form to submit, but prevent blank fields from being saved using Django Admin 3.x? Python Django表格,表格不适用于输入的数据 - Python Django forms, form is not work with entered data 用户以Django形式输入的无效RegEx导致500服务器错误 - Invalid RegEx Entered by User in Django Form Causes 500 Server Error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM