0

我正在尝试通过 django 上传 csv,但它不起作用..

代码

视图.py

from django.shortcuts  import render_to_response
from forms import UploadForm
from django.http import HttpResponseRedirect

def create(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadForm()
    return render_to_response('upload.html', {'form': form})

网址.py

urlpatterns = patterns('',
    (r'^$', create),
    #url(r'^articles/create/$', create, name='done'),
    url(r'^articles/create/$', 'article.views.create'),
)

模型.py

from django.db import models
from time import time

def get_upload_file_name(instance, filename):
    return "uploaded_files/%s_%s" % (str(time()).replace('.','_'), filename)

class Article(models.Model):
    file = models.FileField(upload_to=get_upload_file_name)

表格.py

from django import forms
from models import Article

class UploadForm(forms.ModelForm):
    class Meta:
        model = Article

.html 文件

{% csrf_token %} {{form.as_p}}
4

1 回答 1

0

您的模板需要是:

<form method="post" enctype="multipart/form-data">
   {% csrf_token %}
   {{ form.as_p }}
   <input type="submit" />
</form>

请参阅文档中将上传的文件绑定到表单部分。

于 2013-10-28T05:51:40.813 回答