Reputation: 525
I am newbie working with django, I am trying to create a form that permits the user to upload a file. The code I used is pretty much the same as from the djangoproject tutorial but it didn't work. my code is as follows:
for views:
from django import forms
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
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('/')
else:
form = UploadFileForm()
return render_to_response('upload_file.html', {'form': form})
def handle_uploaded_file(f):
destination = open('home/dutzy/Desktop/mysite/name.txt', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
models:
from django.db import models
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
and the template:upload_file.html
<form enctype="multipart/form-data" method="post" action="/upload_file/">
<table>
<tr>
<td>
<b> {{ form.file.label_tag }}</b> {{ form.file}}
</td>
</tr>
<tr>
<td>
<input type="hidden" value="title" name="title" id="title" />
<input type="submit" value="Save" id="Save"/>
</td>
</tr>
</table>
</form>
i am testing my code on the django development server. the error is:global name 'UploadFileForm' is not defined, altough i suspect there are also other problems.
i have configured the urls.py as:
(r'^upload/$', 'mysite.upload.views.upload_file')
Could someone please take a look at my code and point me in the right direction?
Thank you
Upvotes: 1
Views: 3690
Reputation: 1121
Agree with Yuji's answer. I would also suggest to define UploadFileForm class in your view instead of the models. It belongs with the presentation logic, not the data/model.
Upvotes: 1
Reputation: 118528
The error is a simple python error. UploadFileForm is not defined
According to what you've pasted, you've only imported stuff from django.
You have to import your UploadFileForm
from wherever it lives into your view function code, so add "from myproject.myapp.models import UploadFileForm"
To reproduce your error:
def global_name_error():
UploadFileForm
global_name_error()
[out] NameError: global name 'UploadFileForm' is not defined
Upvotes: 1
Reputation: 215
Make sure that your form follows these rules http://docs.djangoproject.com/en/1.2/ref/forms/api/#binding-uploaded-files-to-a-form
Upvotes: 1