Django表示:当文件POST到文件字段WITH enctype时,“此字段是必需的”

时间:2018-03-29 06:26:44

标签: django forms django-forms django-templates

我无法上传文件并获得“此字段是必填项”。到目前为止,它与报告的问题here相同。但是,我上午正在使用此问题中建议的enctype="multipart/form-data"

模特:

class ContentSheet(models.Model):
    content_sheet_name = models.CharField(max_length=500)
    content_sheet_file = models.FileField()

表格:

class ContentSheetForm(forms.ModelForm):
    content_sheet_name = forms.CharField(max_length=50)
    content_sheet_name.widget.attrs.update({'autofocus': 'autofocus', 'placeholder': 'Content Sheet Name'})
    content_sheet_file = forms.FileField()

    class Meta:
        model = ContentSheet
        exclude = tuple()

观点:

def add_user_sentence(request):
    statistics_context = get_statistics()
    if request.method == 'POST':
        form = ContentSheetForm(request.POST, request.FILES)
        if form.is_valid():
            # Save the new sentence to the database.
            form.save(commit=True)
             print "form.content_sheet_file", form.content_sheet_file
             ...
        else:
            print form.errors
    else:
        # If the request was not a POST, display the form to enter details.
        form = ContentSheetForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    context = {'user_sentence_form': form}
    return render(request, 'lf_classifier/insert_text.html', context)

HTML:

<form id="user_sentence_form" method="post" enctype="multipart/form-data" action="/lf_classifier/send_text/">
                {% csrf_token %}

                {% for field in user_sentence_form.visible_fields %}
                    {{ field.errors }}
                    {{ field.help_text }}
                    {{ field }}
                {% endfor %}

                <input type="submit" data-icon="action" data-iconpos="right" name="submit" data-inline="true" value="upload" />
            </form>

2 个答案:

答案 0 :(得分:2)

您尚未将文件数据传递给表单。

form = ContentSheetForm(request.POST, request.FILES)

答案 1 :(得分:0)

添加data-ajax="false"解决了我的问题。固定的HTML:

<form id="user_sentence_form" method="post" enctype="multipart/form-data" data-ajax="false"  action="/lf_classifier/send_text/">
            {% csrf_token %}

            {% for field in user_sentence_form.visible_fields %}
                {{ field.errors }}
                {{ field.help_text }}
                {{ field }}
            {% endfor %}

            <input type="submit" data-icon="action" data-iconpos="right" name="submit" data-inline="true" value="upload" />
        </form>