0

我正在尝试在我的网站上添加一个简单的文件上传页面。每当我提交表单时,它会在文件选择器上方显示“此字段是必需的”,就好像它没有通过它一样。这是我的表单、模型和视图。

表格.py

from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

class UploadFileForm(forms.Form):

    MURRMACMOD = "MMM"
    CUBE67 = "C67"
    CUBE20 = "C20"
    VDINCONN = "VDC"
    IMPACT20 = "I20"
    IMPACT67 = "I67"
    CAT_CHOICES = (
        (MURRMACMOD, 'Murrelektronik Mac Module'),
        (CUBE67, 'Cube67/Cube67'),
        (CUBE20, 'Cube20'),
        (VDINCONN, 'Valve DIN Connectors'),
        (IMPACT20, 'Impact 20'),
        (IMPACT67, 'Impact 67')
    )

    article = forms.CharField(max_length=100)
    title = forms.CharField(max_length=100)
    file = forms.FileField()
    cat = forms.ChoiceField(choices=CAT_CHOICES)

模型.py

from django.db import models

class File(models.Model):

    article = models.CharField(max_length=100)
    title = models.CharField(max_length=100)
    file = models.FileField()
    cat = models.CharField()

视图.py

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext

from files.forms import UploadFileForm

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()

    ctxt_dict = {
        'form': form,
    }
    context = RequestContext(request, ctxt_dict)
    return render_to_response('upload.html', context_instance=context)

我希望得到一些帮助,谢谢。

编辑:这是模板。

{% if user.is_staff %}
<form action="." method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
{% else %}
{% endif %}
</form>
4

1 回答 1

1

在 Django 模板中,如果您尝试呈现具有文件字段的表单。你必须通过替换

表单方法="post" 动作="">

表单方法="POST" enctype="multipart/form-data">

同时循环表单集和列表中的表单+ FileField 需要错误:django

于 2013-03-27T00:15:16.923 回答