开发者

Update database with uploaded file using Django

I am new to Django

I have a MySQL database - which I want to update using a csv file. I intend to use the LOAD DATA command of MySQL How do I go about it? - or is there a better way ?

How should I create 开发者_运维百科the upload form?


You can use the csv module in Python to read the file and loop over the rows:

import csv

csv_file = open('path/to/file', 'rb')
reader = csv.reader(csv_file)

for column1, column2, column3 in reader:
    #do something with the data here

Hope that helps!

This section is a followup showing a sample view:

#NOT TESTED
import csv

from django.shortcuts import render_to_response

form my_app.forms import MyForm
from my_app.models import MyModel

def my_view(request):
    if request.method == 'GET':
        form = MyForm()
    else:
        form = MyForm(request.FILES, request.POST)
        if form.is_valid():
            the_file = form.cleaned_data.get('the_file_field', None)
            if the_file:
                reader = csv.reader(the_file)
                for column1, column2, column3 in reader:
                    my_model = MyModel.objects.create(column1=column1, \
                    column2=column2, column3=column3)
    return render_to_response('my_template.html', {'form' : form})


To do this using Django, you might be better off writing a view and a supporting model that would have a form to upload your file, then parse the file row by row for information to be inserted into your database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜