我正在构建我的第一个Django应用程序,我需要一个上传页面,我可以在不同的上传表单中上传多个文件。我需要不同的表单,我想模型,因为根据表单,文件必须存储在我的媒体根目录中的相应文件夹中,并进行不同的进一步转换。我还希望不同的用户对这些上传有不同级别的访问权限。
到目前为止,我有类似的东西(我在views.py中的函数内部有很多额外的代码,可以将数据发送到数据框或其他程序,但我没有发布这些代码:
models.py
class Upload(models.Model):
document = models.FileField(storage=OverwriteStorage(),upload_to=get_file_path)
upload_date=models.DateTimeField(auto_now_add =True)
class Upload_variables(models.Model):
variables = models.FileField(storage=OverwriteStorage(),upload_to=get_file_path_var)
upload_date=models.DateTimeField(auto_now_add =True)
forms.py
from django import forms
from uploader.models import Upload, Upload_variables
class UploadForm(forms.ModelForm):
class Meta:
model = Upload
fields = ('document',)
class UploadFormVar(forms.ModelForm):
class Meta:
model = Upload_variables
fields = ('variables',)
views.py
def home(request):
if request.method=="POST":
img = UploadForm(request.POST, request.FILES)
if img.is_valid():
img.save()
else:
img=UploadForm()
files=Upload.objects.all()
return render(request,'home.html',{'form':img})
def variables(request):
if request.method == 'POST':
var = UploadFormVar(request.POST, request.FILES)
if var.is_valid():
var.save()
else:
var = UploadFormVar()
files_st = Upload_variables.objects.all()
return render(request, 'home.html', {'form_b': var})
HTML
<form action="#" method="post" enctype="multipart/form-data">
{% csrf_token %} {{form}}
<input type="submit" value="Upload" id="submit_form"/>
</form>
<form action="#" method="post" enctype="multipart/form-data">
{% csrf_token %} {{form_b}}
<input type="submit" value="Upload" id="staging"/>
</form>
所以我可以看到2个上传按钮,但只有一个'选择文件'.... 谢谢你的帮助!
答案 0 :(得分:0)
目前,您将表单放在两个单独的视图中。您需要将它们放在相同的视图中:
def home(request):
if request.method=="POST":
var = UploadFormVar(request.POST, request.FILES)
img = UploadForm(request.POST, request.FILES)
if img.is_valid():
img.save()
if var.is_valid():
var.save()
else:
img = UploadForm()
var = UploadFormVar()
files=Upload.objects.all()
return render(request,'home.html',{'form': img, 'form_b': var})