You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中读取文本文件并在textarea中展示内容?

解决方案

步骤1:修改视图,读取文件内容并传递到模板

更新views.py,在上传文件成功后读取内容,同时支持默认读取已存在的yes.txt内容:

class CreateProfileView(View):
    def get(self, request):
        form = ProfileForm()
        file_content = ""
        # 尝试读取已上传的yes.txt内容
        try:
            with open('media/images/yes.txt', 'r', encoding='utf-8') as f:
                file_content = f.read()
        except FileNotFoundError:
            pass
        return render(request, "main/create_profile.html", {
            "form": form,
            "file_content": file_content
        })

    def post(self, request):
        submitted_form = ProfileForm(request.POST, request.FILES)

        if submitted_form.is_valid():
            uploadfile = UploadFile(image=request.FILES["upload_file"])
            uploadfile.save()
            # 读取刚上传的文件内容
            file_path = uploadfile.image.path
            with open(file_path, 'r', encoding='utf-8') as f:
                file_content = f.read()
            # 重置表单并传递内容到页面
            return render(request, "main/create_profile.html", {
                "form": ProfileForm(),
                "file_content": file_content
            })

        return render(request, "main/create_profile.html", {
            "form": submitted_form,
            "file_content": ""
        })

步骤2:修改模板,将内容填充到textarea

更新HTML文件中的textarea标签,用模板变量填充内容:

{% load static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Create a Profile</title>
    <link rel="stylesheet" href="{% static "main/styles/styles.css" %}">
  </head>
  <body>
    <form action="/" method="post" enctype="multipart/form-data">
      {% csrf_token %} {{ form }}
      <button type="submit">Upload!</button>
    </form>   

    <textarea name="" id="" cols="30" rows="10">{{ file_content }}</textarea>
  </body>
</html>

注意事项

  • 确保media/images目录存在,且Django已配置好媒体文件路径。
  • 读取文件时指定encoding='utf-8',避免特殊字符或中文乱码。
  • 若上传大文本文件,建议优化内容读取逻辑,避免内存占用过高。

内容的提问来源于stack exchange,提问作者mightycode Newton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:40:29