如何在sqlite数据库django中上传csv文件

时间:2013-10-28 05:21:40

标签: python django django-models django-templates

我正在尝试通过django上传csv,但它无法正常工作..

代码

Views.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})

Url.py

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

models.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)

Forms.py

from django import forms
from models import Article

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

html文件

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

1 个答案:

答案 0 :(得分:0)

您的模板必须是:

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

请参阅文档中的binding uploaded files to a form部分。