2013-04-06 73 views
3

我一直在黑客這個項目好幾個小時了,只是無法弄清楚如何創建一個簡單的文件上傳應用程序。我看過所有的教程,但沒有一個適用於我的情況,我只是無法得到正確的代碼。我知道我現在擁有的代碼不會運行,但我希望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> 

如果有別的喲你需要告訴我。謝謝你,謝謝你,謝謝你!

+0

是否有錯誤,或者它,你希望它是什麼只是不能做? – Ngenator 2013-04-06 02:37:58

回答

4

views.py

def upload(request): 
    template = 'upload.html' 
    if request.method == 'POST': 
     form = UploadWorkSheetForm(request.POST, request.FILES) 
     if form.is_valid(): 
      form.save() 

      return HttpResponseRedirect('upload_success.html') <---change this to your valid url not template name 
    else: 
     form = UploadWorkSheetForm() 

    return render(request, 'upload.html', {'form': form}) 

模板

...................   
{% block body %} 
<form action="." method="post" enctype="multipart/form-data"> 
    {% csrf_token %}  
    {{ form.as_p }} 
    <input type="submit" value = "Upload"/> 
</form> 
{% endblock %} 
.................... 
+0

如果您有其他問題,請告訴我 – catherine 2013-04-06 02:39:41

+0

謝謝,這正是我需要的!儘管還有一個問題,我沒有看到一個按鈕,我可以「提交」這個,即使有definitley form.save()它只是沒有顯示在我的大巴或HTML /模板不放在那裏按鈕?再次感謝 – user2251164 2013-04-06 03:00:21

+0

這是按鈕'',你不認識代碼嗎? – catherine 2013-04-06 03:02:11