Django表单不断抱怨必填字段

时间:2019-03-29 17:47:50

标签: django forms model field required

该表单已提交,但立即显示此字段是必填字段...尽管已填写。我在做什么错

我认为:

def fileupload(request):
    if request.user.is_authenticated and request.user.is_staff:
        if request.method == 'POST':
            form = UploadFileForm(request.POST, request.FILES)
            if form.is_valid():
                handle_uploaded_file(request.FILES.getlist('file_field'))
                return HttpResponseRedirect('/fileupload/')
        else:
            form = UploadFileForm()
        return render(request, 'fileupload.j2.html', {'form': form})
    return HttpResponseForbidden('<h1>403 Forbidden</h1>')

采用以下格式:

class UploadFileForm(forms.Form):
    kit_number = forms.CharField(label="Kit number", max_length=100, required=True, help_text='Required.')
    file_field = forms.FileField(label='Upload kit result')

和模板:

{% extends "menu.j2.html" %}
{% block content %}
{% if request.user.is_authenticated and request.user.is_staff %}
<h3>File upload</h3><br><br>
    <form action="/fileupload/" method="post">
    {% csrf_token %}
<div class="form-group">
    <table>
{{ form.as_table() }}
    </table>
</div>
    <input id="button" class="btn" type="submit" value="Sent">

    </form>

{% else %}
You are not authorized to see this page
{% endif %}
{% endblock %}

1 个答案:

答案 0 :(得分:1)

您忘记设置表单的enctype。

<form action="/fileupload/" method="post" enctype="multipart/form-data">