I've been looking at this django snippet: http://djangosnippets.org/snippets/1036/#c3564
my code is:
def handle_uploads(request, key):
saved=[]
upload_dir = settings.UPLOAD_PATH % request.user.username
upload_full_path =os.path.join(settings.MEDIA_ROOT, upload_dir)
if not os.path.exists(upload_full_path):
os.makedirs(upload_full_path)
for key in keys:
if key in request.FILES:
upload = request.FILES[key]
while os.path.exists(os.path.join(upload_full_path, upload.name)):
if (request.user.username not in upload.name) and (request.user.first_name not in upload.name):
upload.name = request.user.username + "_" + upload.name
dest = open(os.path.join(upload_full_path, upload.name), 'wb')
for chunk in upload.chunks():
dest.write(chunk)
dest.close()
saved.append((key, os.path.join(upload_dir, upload.name)) )
return saved
def upload_view(request):
开发者_C百科 user = request.user
if user.is_authenticated():
if request.method == 'POST':
form =upload_form(request.POST, request.FILES)
if form.is_valid():
saved_file = handle_uploads(request, ?)
in the example given, they seem to upload images. What should I put here if I want to upload ms word documents? Also in the example, they refer to a model called MyModel(), what would this model look like for msword documents. The way I want my site to work is that each user can view his/her documents that they uploaded. And then, if they need to, they can download these documents again. To attribute the documents to each user, should I add it in my expanded user_field class? And if I do, will the model referred to as "MyModel" in the example just be that expanded user field? Also, how do I set up file downloading? I didn't see anything in the docs about this.
Thank you.
Look at Django's documentation for uploading files, the model's FileField field type, and the Django forms FileField field type.
You will probably want to define a model to represent your uploaded file:
#in your models file
from django.contrib.auth.models import User
class UploadedFile(models.Model):
user = models.ForeignKey(User)
file = models.FileField(upload_to='myfiles/')
精彩评论