rgm
rgm

Reputation: 1281

django read file for importing details

I have used django-adaptops for this purpose. i have implemented the mechanism shown in docs. I need to know how can achieve this using browser , for example - i have a template where user has the option to select the csv file, once i click the import button i get the call to my view , but here i cannot read the file to upload to my model. how i can perform this.

this is my template code.

 <form action="/manage/dashboard/importProspects" method="post" class="form-horizontal"
                      enctype="multipart/form-data"> {% csrf_token %}

                    <div class="row-fluid" style="margin-top: 5%">
                        <div class="span6">
                            <div class="control-group">
                                <p>{{ csvform.fname.label_tag }} {{ csvform.fname }} {{ csvform.fname.url }}</p>
                            </div>
                        </div>


                        <button type="submit" class="btn btn-small btn-success " style="margin-left:10px; ">
                            Import from CSV
                        </button>
                    </div>
       </form>

csvForm is form object passed when this template is loaded.

the form code is below:

class ImportCsvForm(forms.Form):
     fname = forms.FileField(label='CSV')

and /manage/dashboard/importProspects url will call my view importcsv which right now does not perform anything.

how can i handle this so that i can read the csv file, i cannot get the csvfile path. or am i missing some thing here ? please help.

Upvotes: 1

Views: 436

Answers (1)

dhana
dhana

Reputation: 6525

Follow this,

in template:

<form action="/manage/dashboard/importProspects" method="post" class="form-horizontal"
                      enctype="multipart/form-data"> {% csrf_token %}

                    <div class="row-fluid" style="margin-top: 5%">
                        <div class="span6">
                            <div class="control-group">
                                <p>
                                    <input type="file" name="csvfile" />
                                </p>
                            </div>
                        </div>


                        <input type="submit" class="btn btn-small btn-success " style="margin-left:10px; " />

                    </div>
   </form>

in urls.py:

urlpatterns = patterns("mine.views",
        url(r'^', 'csvupload'),)

in views.py file:

def csvupload(request):
    if request.method == "POST":
       f = request.FILES['csvfile']
       with open("/tmp/csvfile.csv", 'wb+') as destination:
                for chunk in f.chunks():
                    destination.write(chunk)

then use csvfile whatever you want.....Hope this helps to you.

Upvotes: 3

Related Questions