我一直在黑客這個項目好幾個小時了,只是無法弄清楚如何創建一個簡單的文件上傳應用程序。我看過所有的教程,但沒有一個適用於我的情況,我只是無法得到正確的代碼。我知道我現在擁有的代碼不會運行,但我希望somone能夠將我帶入正確的方向。我知道它不是很好,但我很沮喪,我希望有人能夠特別幫助我的views.py非常感謝。先謝謝你!使用ModelForms上傳django中的文件
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
class WorkSheet(models.Model):
worksheet_name = models.CharField(max_length= 150, default = True)
creator = models.ForeignKey(User, default = True)
worksheet_file = models.FileField(upload_to = 'worksheets', default = True)
number_of_stars = models.PositiveIntegerField(default = True)
category = models.CharField(max_length = 100, default = 0)
class UploadWorkSheetForm(ModelForm):
class Meta:
model = WorkSheet
Views.py
from django.shortcuts import render, render_to_response, HttpResponseRedirect
from django.conf import settings
from django import http
from models import WorkSheet
from forms import UploadWorkSheetForm
def upload(request):
template = 'upload.html'
if request.method == 'POST':
if 'file' in request.FILES:
file = request.FILES['file']
filename = file['filename']
fd = open('%s/%s' % (settings.MEDIA_ROOT, filename), 'wb')
fd.write(file['content'])
fd.close()
return http.HttpResponseRedirect('upload_success.html')
else:
form = UploadWorkSheetForm()
return render_to_response(template, {'form': form})
return render(request, 'upload.html', {'form': form})
Upload.html
<!DOCTYPE html>
<html>
<head>
<title>WSD Upload</title>
</head>
<body>
<h1>Upload WorkSheet</h1>
{% block body %}
<form action="." method="post" enctype="multipart/form-data"> {{ form }}
<type="submit" value = "Upload"/>
</form>
{% endblock %}
</body>
</html>
如果有別的喲你需要告訴我。謝謝你,謝謝你,謝謝你!
是否有錯誤,或者它,你希望它是什麼只是不能做? – Ngenator 2013-04-06 02:37:58