2

Django上传文件

models.py


class FilesModel(models.Model):
    """ 文件名称"""
    # file = models.FileField(upload_to='demo_files/%Y/%m/%d/')
    file = models.FileField(upload_to='demo_files/%Y/%m/%d/%H:%M:%S')
    date = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=30, blank=True, null=True)


class ContentModel(models.Model):
    """文件内容"""
    filed_ids = models.CharField(max_length=20)
    name = models.CharField(max_length=20)
    sex = models.CharField(max_length=10)
    age = models.CharField(max_length=20)
    desc = models.CharField(max_length=200)
    file = models.ForeignKey(FilesModel)


views.py


def handle_uploaded_file(file):
    """ 读取excle 文件存入数据库"""
    return excel_reader_dict(file=file)


def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            file = request.FILES['file']
            time_str = now().strftime('/%Y/%m/%d/%H:%M:%S')
            # path = '/Users/fiz/Desktop/my/demo_files'
            path = '/home/my/demo_files'
            path = path + time_str + '/' + file.name
            print(path)
            new_file = form.save()
            # 名称是否重复
            new_file.name = file.name
            new_file.save()
            try:
                datas = handle_uploaded_file(path)
                print(datas)
                for data in datas:
                    ContentModel.objects.create(name=data.get('name'),
                                                filed_ids=data.get('id'),
                                                sex=data.get('sex'),
                                                age=data.get('age'),
                                                desc=data.get('desc'),
                                                file=new_file
                                                )
                alert_message = True
                print(alert_message)
                return render(request, 'demo/upload.html',
                              {'form': form, 'succcess': alert_message})
            except Exception or IndexError or ValueError as ex:
                print(ex.args)
                FilesModel.objects.filter(id=new_file.pk).delete()
                return HttpResponse("文件或者数据格式不对,请查看后上传")
               
    else:
        form = UploadFileForm()
    return render(request, 'demo/upload.html', {'form': form})
    

forms.py

# -*- coding:utf-8 -*-
""" Created by FizLin on 2017/07/31/-下午2:54
    mail: https://github.com/Fiz1994
"""
from django.forms import ModelForm
from demo.models import  FilesModel, CommentModel


class UploadFileForm(ModelForm):
    class Meta:
        model = FilesModel
        fields = ('file',)



class CommentForm(ModelForm):
    class Meta:
        model = CommentModel
        fields = '__all__'

urls.py

# -*- coding:utf-8 -*-
""" Created by FizLin on 2017/07/31/-下午2:58
    mail: https://github.com/Fiz1994
"""
from django.conf.urls import url, static
from demo.views import upload_file, success, home, view_excle_web, comment, delete_data,delete_excle
from django.conf import settings

urlpatterns = [
    url(r'/upload/$', upload_file, name='upload_file'),
    url(r'/success/url/$', success, name='success'),
    url(r'/home/$', home, name='home'),
    url(r'/comment/$', comment, name='comment'),
    url(r'/delete_data/$', delete_data, name='delete_data'),
    url(r'/view_excle_web/(?P<id>\d+)/$', view_excle_web, name='view_excle_web'),
    url(r'/delete_excle/$', delete_excle, name='delete_excle'),

]

templeate

base.html
<div class="container">

    <div class="row">
        <div class="col-md-2"></div>
        <div class="col-md-8">
            <h2 style="font-style: italic; font-family: 'Microsoft Sans Serif', Tahoma, Arial, Verdana, Sans-Serif">

                upload file test</h2>
        </div>
        <div class="col-md-2"></div>
    </div>
</div>
<div class="container">
    <div class="col-md-3"></div>
    <div class="col-md-6">
        {% block content %}{% endblock %}
    </div>
    <div class="col-md-3"></div>
</div>

home.html

{% extends 'demo/base.html' %}
{% block title %} home-upload file {% endblock %}
{% block content %}
    <form action="{% url 'home' %}" method="post">
        {% csrf_token %}
        <input type="text" placeholder="文件名称,时间" name="condition">
        <button type="submit" class=""> 查找</button>
    </form>
    <hr/>
    <p>你已经上传过的文件</p>

    <ul>
        <li></li>
        {% for file in files %}
            <li>
{#                <a href="{% url 'view_excle_web' id=file.id %}">{{ file.name }}-上传时间 {{ file.date|date:'Y-m-d G:i:s' }}</a>#}
                <p>
                    <a href="{% url 'view_excle_web' id=file.id %}">{{ file.name }}-上传时间 {{ file.date|date:'Y-m-d G:i:s' }}</a> &nbsp; &nbsp; &nbsp;
                    <a class="btn-danger" href="{% url 'delete_excle' excel_id=file.id %}">delete</a>
                </p>

            </li>
        {% endfor %}

    </ul>

{% endblock %}

upload.html

{% extends 'demo/base.html' %}
{% block title %} upload file {% endblock %}
{% block content %}

    {% if succcess %}
        <script>
            alert("上传成功,你可以返回首页查看");
        </script>
    {% endif %}

    {% if  error_info %}
        <script>
            alert({{ error_info }});
        </script>
    {% endif %}

    <p> 请按照这个格式制作excel 文件进行测试,因为列数相当于数据库中的列名称,多余的会被扔掉</p>
    <img src="https://fizblog.cn/media/uploads/2017/07/31/snip20170731_1.png" alt="">
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn-default">Upload</button>
    </form>
{% endblock %}

具体的源码可以查看

git@github.com:Fiz1994/inter.git

results

图片描述

图片描述


FIZLIN
514 声望8 粉丝

跟我走吧,天亮就出发


« 上一篇
Python WSGI
下一篇 »
python MRO

引用和评论

0 条评论