使用ModelForms上传django中的文件

时间:2013-04-06 01:44:07

标签: html django django-models django-forms django-views

我已经在这个项目上乱砍了很多个小时了,只是无法弄清楚如何创建一个简单的文件上传应用程序。我查看了所有的教程,但没有一个适用于我的情况,我只是不能正确的代码。我知道我现在的代码不会运行但是我希望somone可以用我所拥有的东西把我推向正确的方向。我知道它不是很好,但我感到沮丧,我希望有人可以特别帮助我的观点。我非常感谢你。先感谢您!

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>

如果您还有其他需要,请告诉我。谢谢谢谢谢谢!

1 个答案:

答案 0 :(得分:5)

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 %}
....................