2013-03-28 247 views
-1

所以我想通過一個POST上傳並保存一個csv文件到一個url。我查看了文件上傳的django文檔,找到了here。我只是不明白使用表單?這種情況的目的是什麼?使用Django表單上傳csv文件

他們用一個例子用一種形式:

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

# Imaginary function to handle an uploaded file. 
from somewhere import handle_uploaded_file 

class UploadFileForm(forms.Form): 
    title = forms.CharField(max_length=50) 
    file = forms.FileField() 

def upload_file(request): 
    if request.method == 'POST': 
     form = UploadFileForm(request.POST, request.FILES) 
     if form.is_valid(): 
      handle_uploaded_file(request.FILES['file']) 
      return HttpResponseRedirect('/success/url/') 
    else: 
     form = UploadFileForm() 
    return render_to_response('upload.html', {'form': form}) 

上傳HTML:

<form enctype="multipart/form-data" action="/upload/" name="test" method="post"> 
    <input id="file" type="file" name="test" /> 
    <input id="signUpSubmit" type="submit" value="Submit"> 
</form> 

回答

3

models.py

from django.db import models 

class Upload(models.Model): 
    name = models.CharField(max_length=100) 
    file = models.FileField(upload_to="images") 

forms.py

from django import forms 
from app_name.models import Upload 

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

views.py

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

upload.html

<form enctype="multipart/form-data" action="/upload/" name="test" method="post"> 
    {% csrf_token %} 
    {{form.as_p}} 
    <input id="signUpSubmit" type="submit" value="Submit"> 
</form>