Passing a file from one view to another in Django using sessions

alacy

My current work project requires me to allow for a user to upload files in various formats (currently only dealing with CSV format) and then use the contained data to plot a graph using the Pandas library.

I have decided that the easiest way to render a graph to a template is to make a specific view for the graph and then just link an image to that view from the desired template (e.g. the form page that containing the file upload). I have that working for files with a local path that I hard-coded, but I can't seem to pass the uploaded file to the graph view. I've read that using sessions is the simplest way, but I haven't been successful in my attempts.

The following code is of my file upload form view which gives the following error:

Error #1

InMemoryUploadedFile: sampleCSV.csv (application/vnd.ms-excel) is not JSON serializable
# upload files
@login_required
def list(request):
    # handle file upload
    if request.method == 'POST':
        form = FileUploadForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = FileUpload(docFile = request.FILES['docFile'])
            newdoc.save();
            request.session['docFile'] = request.FILES['docFile']   
            return HttpResponseRedirect(reverse('list'))
    else:
        form = FileUploadForm()

    # render list page
    return render_to_response(
        'graphite/list.html',
        { 'form': form },
        context_instance=RequestContext(request)
    )

And my graph view shown below throws the following error:

Error #2

Expected file path name or file-like object, got class 'NoneType' type

# graph input file
def graph(request):
    new_file = request.session.get('docFile')
    fig = Figure()
    ax = fig.add_subplot(111)
    data_df = pd.read_csv(new_file)
    data_df = pd.DataFrame(data_df)
    data_df.plot(ax=ax)
    canvas = FigureCanvas(fig)
    response = HttpResponse( content_type = 'image/png')
    canvas.print_png(response)
    return response

Any ideas on what I am obviously doing wrong or what I can do differently would be greatly appreciated. Thanks.


EDIT

Per suggestion I tried to store the name of the file and then pass that via the session, but also to no avail. Current error is the same as error listed second above. My implementations are as follows:

Models.py

class FileUpload(models.Model):
    docFile = models.FileField(upload_to='Data_Files', blank=True)

    @property
    def filename(self):
        return os.path.basename(self.docFile.name)

File upload view

# upload files
@login_required
def list(request):
    # handle file upload
    if request.method == 'POST':
        form = FileUploadForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = FileUpload(docFile = request.FILES['docFile'])
            newdoc.save();
            request.session['docFile'] = newdoc.filename    
            return HttpResponseRedirect(reverse('list'))
    else:
        form = FileUploadForm()

    # render list page
    return render_to_response(
        'graphite/list.html',
        { 'form': form },
        context_instance=RequestContext(request)
    )

Graph View

# graph input file
def graph(request):
    new_file = request.session.get('docFile')
    fig = Figure()
    ax = fig.add_subplot(111)
    data_df = pd.DataFrame.from_csv(new_file)
    data_df.plot(ax=ax)
    canvas = FigureCanvas(fig)
    response = HttpResponse( content_type = 'image/png')
    canvas.print_png(response)
    return response

Traceback for above error:

Traceback:
File "C:\Python34\lib\site-packages\django-1.7.1-py3.4.egg\django\core\handlers\base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\vut46744\Desktop\graphite_project\graphite\views.py" in graph
  127.  data_df = pd.DataFrame.from_csv(new_file)
File "C:\Python34\lib\site-packages\pandas\core\frame.py" in from_csv
  1027.                           infer_datetime_format=infer_datetime_format)
File "C:\Python34\lib\site-packages\pandas\io\parsers.py" in parser_f
  465.         return _read(filepath_or_buffer, kwds)
File "C:\Python34\lib\site-packages\pandas\io\parsers.py" in _read
  241.     parser = TextFileReader(filepath_or_buffer, **kwds)
File "C:\Python34\lib\site-packages\pandas\io\parsers.py" in __init__
  557.         self._make_engine(self.engine)
File "C:\Python34\lib\site-packages\pandas\io\parsers.py" in _make_engine
  694.             self._engine = CParserWrapper(self.f, **self.options)
File "C:\Python34\lib\site-packages\pandas\io\parsers.py" in __init__
  1056.         self._reader = _parser.TextReader(src, **kwds)
sax

I don't think you can put a file object in session as is not serializable, store its filename and reopen the file in the graph view

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Passing Context From One Django View To Another

From Dev

Passing object from one view to another in django via HttpResponseRedirect

From Dev

Passing data from one view to another using UI-Router

From Dev

Passing data from one Backbone view to another

From Dev

passing product info from one view to another

From Dev

Passing php variable from one file to another?

From Dev

Passing variables from one swift file to another

From Dev

Passing an open file from one function to another

From Dev

Passing php variable from one file to another?

From Dev

Passing JSON objects from one table view to another table view

From Dev

Passing Variable From One View to Another View - Laravel 5.1

From Dev

Passing ID from one view to another and storing it in another table

From Dev

passing array from view using ajax to another view codeigniter

From Dev

Passing argument from view of one resource to create method of another with Laravel

From Dev

Passing a "User" object from one view controller to another

From Dev

Passing values from one view controller to another in Swift

From Dev

MVC Charts - Passing data from one view to another cshtml

From Dev

Passing values from one view controller to another in Swift

From Dev

MVC Charts - Passing data from one view to another cshtml

From Dev

Passing a "User" object from one view controller to another

From Dev

passing value from one jsp file to another jsp file

From Dev

Passing javascript variables from one function/file to another

From Dev

SAS - Passing date from one file to another program variable

From Dev

Passing value from one activity to another using intent

From Dev

Passing data from one app to another app using onActivityResult

From Dev

passing values from one page to another page using jquery

From Dev

Image passing from one activity to another using extras

From Dev

Passing data from View to another View

From Dev

Passing value from one view to another view by AJAX Post Request in Laravel

Related Related

  1. 1

    Passing Context From One Django View To Another

  2. 2

    Passing object from one view to another in django via HttpResponseRedirect

  3. 3

    Passing data from one view to another using UI-Router

  4. 4

    Passing data from one Backbone view to another

  5. 5

    passing product info from one view to another

  6. 6

    Passing php variable from one file to another?

  7. 7

    Passing variables from one swift file to another

  8. 8

    Passing an open file from one function to another

  9. 9

    Passing php variable from one file to another?

  10. 10

    Passing JSON objects from one table view to another table view

  11. 11

    Passing Variable From One View to Another View - Laravel 5.1

  12. 12

    Passing ID from one view to another and storing it in another table

  13. 13

    passing array from view using ajax to another view codeigniter

  14. 14

    Passing argument from view of one resource to create method of another with Laravel

  15. 15

    Passing a "User" object from one view controller to another

  16. 16

    Passing values from one view controller to another in Swift

  17. 17

    MVC Charts - Passing data from one view to another cshtml

  18. 18

    Passing values from one view controller to another in Swift

  19. 19

    MVC Charts - Passing data from one view to another cshtml

  20. 20

    Passing a "User" object from one view controller to another

  21. 21

    passing value from one jsp file to another jsp file

  22. 22

    Passing javascript variables from one function/file to another

  23. 23

    SAS - Passing date from one file to another program variable

  24. 24

    Passing value from one activity to another using intent

  25. 25

    Passing data from one app to another app using onActivityResult

  26. 26

    passing values from one page to another page using jquery

  27. 27

    Image passing from one activity to another using extras

  28. 28

    Passing data from View to another View

  29. 29

    Passing value from one view to another view by AJAX Post Request in Laravel

HotTag

Archive