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>
0

1 Answer 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")

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.