为什么我的views.py没有将提交的csv文件保存在Django项目中我的app目录下的data文件夹中?

yc0p9oo0  于 2023-05-19  发布在  Go
关注(0)|答案(1)|浏览(102)

你好,我正在做一个Django项目。
我试图保存一个文件后,用户提交它从网页。
创建视图和HTML
下面提供了views.py、html和urls.py。
我可以得到一些帮助,为什么我的代码不保存在我的应用程序目录中的数据文件夹中的文件?
views.py

class CsvPlot(View):
    def save_uploaded_file(self, request, file):
        if request.method == 'POST' and request.FILES[file]:
            uploaded_file = request.FILES['document']
            # attribute = request.Post.get("attribute")
            # print(attribute)
            # check if the file ends with csv
            if uploaded_file.name.endswith('.csv'):
                save_file = FileSystemStorage()
                name = save_file.save(uploaded_file.name, uploaded_file)
                print(name)
                # Let's save the file in the data folder
                current_dir = settings.BASE_DIR / 'ml_in_geotech'
                file_directory = os.path.join(current_dir, 'data')
                if not os.path.exists(file_directory):
                    os.makedirs(file_directory)
                self.file_path = os.path.join(file_directory, name)
                self.readfile(request, self.file_path)
                request.session['file_path'] = self.file_path
            else:
                return HttpResponse('Invalid file type. Only CSV files are allowed.')

我的HTML

<div class="upload_file">
    <h2>Train Your Data</h2>
    <form method="POST" enctype="multipart/form-data" action="/">
      {% csrf_token %}
      <input type="file" name="document" id="document" required="required">
      <button type="submit">Submit</button>
    </form>   
    
    {% block messages %}
        {% if messages %}
            <div class="container" style="color: firebrick; margin-top: 20px" >
            {% for message in messages %}
                {{ message }}
            {% endfor %}
            </div>
        {% endif %}
    {% endblock %}

  </div>

我的urls.py

[
  path('csv-plot/', views.CsvPlot.as_view(), name='csv_plot'),
]
1mrurvl1

1mrurvl11#

在django docs中查看基于函数的视图和基于类的视图的典型结构差异:https://docs.djangoproject.com/en/4.2/topics/class-based-views/intro/
基于功能的视图:

from django.http import HttpResponse

def my_view(request):
    if request.method == "POST":
        # <view logic>
        return HttpResponse("result")

基于类的视图:

from django.http import HttpResponse
from django.views import View

class MyView(View):
    def post(self, request):
        # <view logic>
        return HttpResponse("result")

在你的情况下应该是这样的:

class CsvPlot(View):
    def post(self, request, file):
        if request.FILES[file]:
            uploaded_file = request.FILES['document']
        ...

并确保为每个if/else子句返回有效的Http响应。

相关问题