4

我已经在这个项目上苦苦挣扎了好几个小时,只是不知道如何创建一个简单的文件上传应用程序。我查看了所有教程,但没有一个完全适用于我的情况,我只是无法正确获取代码。我知道此时我拥有的代码不会运行,但我希望有人能够用我拥有的东西将我推向正确的方向。我知道这不是很好,但我很沮丧,我希望有人能帮助我,尤其是我的意见。py 非常感谢。先感谢您!

模型.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

视图.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})

上传.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>

如果您还有什么需要请告诉我。谢谢你,谢谢你,谢谢你!

4

1 回答 1

6

视图.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 %}
....................
于 2013-04-06T02:38:55.807 回答