我正在使用django 2.0和python 3.6,我已经尝试了几乎所有方法来从request.FILES获取值,但是似乎没有任何效果,我认为我缺少了一些非常简单的东西,但是我找不到它
models.py
class Imagen(models.Model):
imagen = models.FileField(max_length=200, blank=True, upload_to='%Y/%m/%d/')
views.py
def prop_add(request):
if request.method == 'POST':
propiedad_instance = Propiedad(tipo = request.POST.get('tipo'), tamano=request.POST.get('tamano'), habitaciones = request.POST.get('habitaciones'), banos = request.POST.get('banos'), descripcion= request.POST.get('descripcion'), direccion= request.POST.GET('descripcion'), precio= request.POST.get('precio'), ubicacion= Ubicacion.objects.get(barrio= request.POST.get('barrio')))
propiedad_intance.save()
for filename in request.FILES.iteritems():
name = request.FILES[filename].name
print('name =' + name) ## <-- not printing anything
print('file = ' + file)## <-- not printing anything
print('filename = ' + filename)## <-- not printing anything
ubicaciones = Ubicacion.objects.all()
ctx = {'ubicaciones': ubicaciones}
return render(request, 'main/add_modal.html', ctx)
HTML模板
<form method='post' action='' enctype="multipart/form-data">
<input name='imagen' type="file" multiple/>
<button type='submit' class="btn waves-effect">Upload</button>
</form>
views.py是我现在拥有的那个,但是到目前为止,我已经尝试了以下所有变体:
**1**
if request.method == 'POST':
for f in request.FILES.getlist('imagen'):
filename = f.name
print(filename) ## <-- not printing anything
**2**
if request.method== 'POST':
form = FileUploadForm(request.POST, request.FILES) ## form imported from forms.py
if form.is_valid():
print('form is valid!') ## <-- not printing anything
else:
print('form not valid ') ## <-- not printing anything either!! IDK WHY
**3**
if request.method == 'POST':
print('request.method = "POST" checked ') # <-- Not priting anything! but the model below is being saved to the database! my brain is about to explode right now haha.
propiedad_instance = Propiedad(tipo = request.POST.get('tipo'), tamano=request.POST.get('tamano'), habitaciones = request.POST.get('habitaciones'), banos = request.POST.get('banos'), descripcion= request.POST.get('descripcion'), direccion= request.POST.GET('descripcion'), precio= request.POST.get('precio'), ubicacion= Ubicacion.objects.get(barrio= request.POST.get('barrio')))
propiedad_intance.save()
files = request.FILES.getlist('imagen')
if files:
for f in files:
print('something') #<-- not printing anything
print(f) #<-- not printing anything
print(f.name) <-- not printing anything
else:
print('nothing here') #<--- not printing anything
提交表单后的控制台日志 enter image description here
答案 0 :(得分:1)
根据文档上传多个文件的正确方法是。
files = request.FILES.getlist('file_field') #'file_field' --> 'imagen' for you
if form.is_valid():
for f in files:
... # Do something with each file.
您的html看起来还不错。按照上面的内容替换您的视图代码,并检查视图代码是否符合POST的要求?