使用会话将文件从一个视图传递到 Django 中的另一个视图 [英] Passing a file from one view to another in Django using sessions

查看:70
本文介绍了使用会话将文件从一个视图传递到 Django 中的另一个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前的工作项目要求我允许用户上传各种格式的文件(目前只处理 CSV 格式),然后使用包含的数据使用 Pandas 库.

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:

错误 #1

InMemoryUploadedFile: sampleCSV.csv (application/vnd.ms-excel) 不是 JSON 可序列化的

# 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:

错误 #2

预期的文件路径名或类文件对象,获得类NoneType"类型

# 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.

根据建议,我尝试存储文件的名称,然后通过会话传递该名称,但也无济于事.当前错误与上面列出的第二个错误相同.我的实现如下:

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:

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

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

文件上传视图

# 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 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:
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)

推荐答案

我认为您不能将 file 对象放入会话中,因为它不可序列化,存储其文件名并重新打开文件graph 视图

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

这篇关于使用会话将文件从一个视图传递到 Django 中的另一个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆