我是個新手,上傳文件,在它的代碼,以便即時通訊相當糟糕。我使用Django作爲框架。目前這是我的用戶輸入html代碼。如何重新命名輸入文本
<html>
<head>
<title>uploader</title>
<style>
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
text-align: center
}
table {
margin: auto;
}
a {
text-decoration: none
}
</style>
</head>
<body>
<h1>
{{what}}
<h3><p style="text-align: left;text-decoration: none;"><a href="{% url 'home' %}">Back</p></a></h3>
</h1>
<hr>
<table>
<tr>
<td>
<form action="upload/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset>
Category of the device:<br>
<input type="text" name="category" value="" required id="cat">
<br>
Model:<br>
<input type="text" name="model" value="" required id="mod">
<br>
<input type="submit" value="Upload File" class="submit" name="submit" />
<input type="file" name="file"/>
</fieldset>
</form>
</td>
</tr>
</table>
</body>
</html>
views.py
def home(request):
return render(request, 'index.html', {'what':'Upload Files'})
def upload(request):
try:
if request.method == 'POST' and request.FILES['file']:
try:
myfile = request.FILES['file']
category = request.POST['category']
model = request.POST['model']
validate_file_extension(myfile)
fs = FileSystemStorage(location='uploaded/')
filename = request.FILES['filename'].name
handle_uploaded_file(request.FILES['file'], str(request.FILES['file']))
modified_name = "{}_{}_{}".format(filename, category, modle)
filename = fs.save(modified_name, myfile)
return redirect("/success")
except:
return redirect("/unsuccessful")
except:
return redirect("/upload")
def handle_uploaded_file(file, filename):
if not os.path.exists('uploaded/'):
os.mkdir('uploaded/')
with open('uploaded/' + filename, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
我如何重命名上傳的用戶具有的文字,他們輸入自己的文件名後面用「_」的文件。
如:
filename = myfile
category = camera
model = XYZ123
該文件應該被重新命名爲 「myfile_camera_XYZ123」。
你必須做,在視圖中。你可以發佈嗎? –
當然!我編輯過它 –
與模型相關聯的形式? –