上传的文件需进行内容验证或者直接解析的例子

特点就是:

form_valid验证中,完成数据的验证或者解析

urls.py

from django.urls import path
from .views import UploadView


urlpatterns = [
    path('', UploadView.as_view(), name='index'),
]

 

forms.py

from django import forms
from django.core.validators import FileExtensionValidator


class UploadForm(forms.Form):
    file = forms.FileField(
        validators=[FileExtensionValidator(['csv', ])])

 

views.py

import csv
import io

from django.http import HttpResponse
from django.views.generic import FormView

from .forms import UploadForm


# Create your views here.
class UploadView(FormView):
    form_class = UploadForm
    template_name = 'app/UploadForm.html'

    def form_valid(self, form):
        csvfile = io.TextIOWrapper(form.cleaned_data['file'])

        # 这里需要替换你自己的逻辑。
        reader = csv.reader(csvfile)
        count = sum(1 for row in reader)
        result = '数据总数为:{}条'.format(count)

        # 需要在页面显示结果
        return self.render_to_response(self.get_context_data(result=result))

        # 如果需要下载文件,则按以下
        # response = HttpResponse(result, content_type='text/plain')
        # response['Content-Disposition'] = 'attachment; filename = "result.txt"'
        # return response

 

UploadForm.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<div>
    <form action="{% url 'index' %}" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <div>
            <div>
                {{ form.file }}
                <p>{{ form.file.errors }}</p>
            </div>
        </div>
        <input type="submit" value="アップロード">
    </form>
    <pre>{{ result }}</pre>
</div>
</div>
</body>
</html>

 

posted @ 2023-07-09 17:14  花生与酒  阅读(14)  评论(0编辑  收藏  举报