0

So I am trying to upload and save a csv file to a variable via a POST to a url. I have looked through the django documentation on file uploads found here. I just don't understand the use of a form? What's the purpose in this situation?

They use an example with a form:

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

Upload 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>
4

1 に答える 1

3

models.py

from django.db import models

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

フォーム.py

from django import forms
from app_name.models import Upload

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

ビュー.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>
于 2013-03-28T07:19:24.983 に答える