OneToOne模型的文件如何访问文件字段,在views.py中读取并传递给模板?

发布于 2025-01-18 23:08:11 字数 1729 浏览 7 评论 0原文

我正在开发一个简单的数据可视化应用程序,用户可以在其中注册、登录、上传文件并可视化其内容。

我使用默认的 User 模型,以及与 User 模型具有 OneToOne 关系的 Detail 模型。 Detail 有 3 个字段,分别是:

OneToOne(User)
FileField()
TextField()

现在,我想访问 views.pyFileField 中保存的文件并读取其内容,然后使用Python的NumPyMatplotlib`进行可视化,然后最终在前端显​​示可视化结果。

我需要指导我应该如何开始和完成这项任务?基本上,我需要深入指导如何访问和读取 views.py 中的文件?

我的 models.py 是:

class Detail(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    file = models.FileField(verbose_name="CSV File", upload_to='csv_files/')
    file_desc = models.TextField("CSV File Description")

    def __str__(self):
        return ("{} ({} {})".format(self.user.email, self.user.first_name, self.user.last_name))

views.py 中,我以这种方式处理它:

class VisualizeAPI(View):
    template_name = 'accounts/visualize.html'

    def get(self, request):
        msg = {'message': "Please login to view this page."}
        
        if request.user.is_authenticated:
            detail, _ = Detail.objects.get_or_create(user=request.user)
            context = {'detail': detail}

            return render(request, self.template_name, context)

        return render(request, self.template_name, msg)

在 < code>template,我是这样处理的:

<body>
    <h1>Visualized Details</h1>
 
    {% if request.user.is_authenticated %}
    {{ detail }}
    {% else %}
    <h2>{{ message }}</h2>
    {% endif %}
</body>

但它不会在前端打印文件的内容。 我将很高兴提供适当的方法和指导。

I am developing a simple Data Visualization App, where a user can register, login upload a file and visualize its content.

I am using default User model, and a Detail Model having OneToOne relation with User Model. The Detail has 3 fields, which are:

OneToOne(User)
FileField()
TextField()

Now, I want to access the file that is saved in FileField, inviews.pyand read it's content, then visualize it using Python'sNumPyandMatplotlib`, then finally show visualization results on the frontend.

I need a guidance that how should I start and approach this task? Basically, I need deep guidance in how to access and read the file in views.py?

My models.py is:

class Detail(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    file = models.FileField(verbose_name="CSV File", upload_to='csv_files/')
    file_desc = models.TextField("CSV File Description")

    def __str__(self):
        return ("{} ({} {})".format(self.user.email, self.user.first_name, self.user.last_name))

and in views.py, I am approaching it this way:

class VisualizeAPI(View):
    template_name = 'accounts/visualize.html'

    def get(self, request):
        msg = {'message': "Please login to view this page."}
        
        if request.user.is_authenticated:
            detail, _ = Detail.objects.get_or_create(user=request.user)
            context = {'detail': detail}

            return render(request, self.template_name, context)

        return render(request, self.template_name, msg)

and in template, I am approaching it this way:

<body>
    <h1>Visualized Details</h1>
 
    {% if request.user.is_authenticated %}
    {{ detail }}
    {% else %}
    <h2>{{ message }}</h2>
    {% endif %}
</body>

But it is not printing the content of the file on the frontend.
I will be glad for proper approach and guidance provided.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我爱人 2025-01-25 23:08:11

您需要在视图中解析 CSV 文件,然后将其传递到模板。

import csv
from io import StringIO


class VisualizeAPI(View):
    template_name = "accounts/visualize.html"

    def get(self, request):
        msg = {"message": "Please login to view this page."}

        if request.user.is_authenticated:
            detail, _ = Detail.objects.get_or_create(user=request.user)
            if detail.file:
                # Read file from detail object
                file = detail.file.read().decode("utf-8")
                # Parse file as csv
                csv_data = csv.reader(StringIO(file), delimiter=",")
            else:
                csv_data = None
            context = {
                "detail": detail,
                "csv_data": csv_data,
            }

            return render(request, self.template_name, context)

        return render(request, self.template_name, msg)

然后您可以在模板中打印 csv 文件的每一行。

<body>
  <h1>Visualized Details</h1>

  {% if request.user.is_authenticated %}
  {{ detail }}
  {% for row in csv_data %}
    {{ row }}
  {% endfor %}
  {% else %}
  <h2>{{ message }}</h2>
  {% endif %}
</body>

You need to parse the CSV file in your view and then pass it to your template.

import csv
from io import StringIO


class VisualizeAPI(View):
    template_name = "accounts/visualize.html"

    def get(self, request):
        msg = {"message": "Please login to view this page."}

        if request.user.is_authenticated:
            detail, _ = Detail.objects.get_or_create(user=request.user)
            if detail.file:
                # Read file from detail object
                file = detail.file.read().decode("utf-8")
                # Parse file as csv
                csv_data = csv.reader(StringIO(file), delimiter=",")
            else:
                csv_data = None
            context = {
                "detail": detail,
                "csv_data": csv_data,
            }

            return render(request, self.template_name, context)

        return render(request, self.template_name, msg)

Then you can print each row of your csv file in your template.

<body>
  <h1>Visualized Details</h1>

  {% if request.user.is_authenticated %}
  {{ detail }}
  {% for row in csv_data %}
    {{ row }}
  {% endfor %}
  {% else %}
  <h2>{{ message }}</h2>
  {% endif %}
</body>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文