Reputation: 41
hi im currently try to import a csv file into a django project with out using the django admin. the code ive written seems to work when in python run but im unsure about how to build the html template as i cant seem to find any examples. Is anyone able to either post an example or point me in the right direction
my code is
Forms
class DataInput(forms.Form):
file = forms.FileField()
def save(self):
records = csv.reader(self.cleaned_data["file"])
for line in records:
parts = Part()
parts.supplier_id = line[0]
parts.name = line[1]
parts.description = line[2]
parts.save()
view
def csv_import(request):
if request.method == "POST":
form = DataInput(request.POST, request.FILES)
if form.is_valid():
form.save()
success = True
context = {"form": form, "success": success}
return render_to_response("imported.html", context,
context_instance=RequestContext(request))
else:
form = DataInput()
context = {"form": form}
return render_to_response("imported.html", context,
context_instance=RequestContext(request))
thanks in advance
Upvotes: 1
Views: 898
Reputation: 28958
Your upload template will look something like this if you just want to use the default form rendering:
<!DOCTYPE html>
<html>
...
<form enctype="multipart/form-data" method="post" action=".">
{{ form }}
</form>
...
</html>
The distinguishing part is the enctype="multipart/form-data"
that lets it handle the file upload field.
Upvotes: 1