我正在尝试在我的网站上添加一个简单的文件上传页面。每当我提交表单时,它会在文件选择器上方显示“此字段是必需的”,就好像它没有传递它一样。这是我的表单,模型和视图。
forms.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)
models.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()
views.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>
答案 0 :(得分:1)
在Django Template中,如果您尝试渲染具有文件字段的表单。您必须通过替换
form method =“post”action =“”&gt;
与
form method =“POST”enctype =“multipart / form-data”&gt;
loop over forms in formset and a list at same time + FileField required error :django