django-excel, pyexcel, save_to_database ['function' 对象没有属性 '_meta']

django-excel, pyexcel, save_to_database ['function' object has no attribute '_meta']

我想将 excel 数据传输到数据库(postgres 数据库)。

作为pyexcel的引导线,我使用函数save_to_database

但它不起作用,我不知道哪里出了问题..请帮助我

我收到这个错误: 内部服务器错误:/weekly_upload 追溯(最后一次通话):... AttributeError: 'function' 对象没有属性 '_meta' [04/Nov/2018 21:53:55] "POST /weekly_upload HTTP/1.1" 500 138219

form.py

from django import forms
from .models import Documents, Weekly_upload
from .models import Project_code

class UploadFileForm(forms.Form):
file=forms.FileField()

view.py

from __future__ import unicode_literals
from .forms import UploadFileForm, DocumentForm
from django.shortcuts import render, get_object_or_404
import openpyxl, pyexcel

from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse
from .models import Weekly_upload

def weekly_upload(request):
if request.method=='POST':
    #form=UploadFileForm(request.POST, request.FILES)
    form=UploadFileForm(request.POST, request.FILES)
    if form.is_valid():               
        print(form.is_valid())
        print("save to database...")
        request.FILES['file'].save_to_database(model=weekly_upload,
                                               initilaizers = None,
                                               mapdict={'project_id':'project_id',
                                                        'plan_indicator':'plan_indicator',
                                                        'region':'region',
                                                        'country':'country',
                                                        'priority':'priority',
                                                        'desc_kr':'desc_kr',
                                                        'desc_en':'desc_en',
                                                        'continuity':'continuity',
                                                        'business_period':'business_period',
                                                        'plan_pers_num':'plan_pers_num',
                                                        'noted_continue':'noted_continue',
                                                        'train_org':'train_org',
                                                        'invitation_local':'invitation_local',
                                                        'start_month':'start_month',
                                                        'start_time':'start_time',
                                                        'end_time':'end_time',
                                                        'train_period':'train_period',
                                                        'koica_resp':'koica_resp',
                                                        'association_resp':'association_resp',
                                                        'accounting_resp':'accounting_resp' }
                                                              )   
        return HttpResponse("OK")  
print("hello1")
return render(request, 'rndsettle/weekly_upload.html', {})

urls.py

from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^company_code', views.company_code, name='company_code'),
url(r'^department_code', views.department_code, name='department_code'),
url(r'^project_code', views.project_code, name='project_code'),
url(r'^account_code', views.account_code, name='account_code'), 
url(r'^common_code', views.common_code, name='common_code'),
url(r'^weekly_report', views.weekly_report, name='weekly_report'),
url(r'^weekly_upload', views.weekly_upload, name='weekly_upload'),

]

weekly.html

{% extends 'rndsettle/base.html' %}
{% load staticfiles%}
{% block content %}


<div class="col-sm-9">        
    <body style="margin-top: 30px; margin-left: 30px;">
        <!--<form action="{% url 'weekly_upload' %}" method="post" enctype="multipart/form-data">-->
        <form action="{% url 'weekly_upload' %}" method="post" enctype="multipart/form-data" >
            {%csrf_token%}
            <input multiple 
                   type="file"
                   name="file" 
                   style="border: 1px solid black; padding: 5px;"
                   required="required"/>
            <p>
            </p>
            <input type="submit"
                   style="border: 1px solid green; padding:5px; border-radius: 2px; cursor:pointer;"/>            
        </form>
        <p>
        </p>
        <hr>
        {% if uploaded_file_url %}
        <p>
            File uploaded at : <a href="{{uploaded_file_url}}">{{uploaded_file_url}}</a>
        </p>
        {%endif%}
        <p>
            <a href="{% url 'index' %}"> Return to Main Screen </a>
        </p>

    {% for row in excel_data %}
        {% for cell in row %}
            {{ cell }}&nbsp;&nbsp;
        {% endfor %}
        <br>
    {% endfor %}
        <br>           
    </body>
</div>

{% 端块 %}

回溯

Internal Server Error: /weekly_upload 
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/workspace/rnd/rndsettle/views.py", line 107, in weekly_upload
'accounting_resp':'accounting_resp' }
File "/usr/local/lib/python2.7/dist-packages/django_excel/__init__.py", line 49, in save_to_database
pe.save_as(**params)
File "/usr/local/lib/python2.7/dist-packages/pyexcel/core.py", line 83, in save_as
return sources.save_sheet(sheet, **dest_keywords)
File "/usr/local/lib/python2.7/dist-packages/pyexcel/internal/core.py", line 43, in save_sheet
return _save_any(a_source, sheet)
File "/usr/local/lib/python2.7/dist-packages/pyexcel/internal/core.py", line 55, in _save_any
a_source.write_data(instance)
File "/usr/local/lib/python2.7/dist-packages/pyexcel/plugins/sources/db_sources.py", line 64, in write_data
**self._keywords
File "/usr/local/lib/python2.7/dist-packages/pyexcel/plugins/renderers/django.py", line 33, in render_sheet_to_stream
importer.append(adapter)
File "/usr/local/lib/python2.7/dist-packages/pyexcel_io/database/common.py", line 135, in append
self.__adapters[import_adapter.get_name()] = import_adapter
File "/usr/local/lib/python2.7/dist-packages/pyexcel_io/database/common.py", line 44, in get_name
return self.model._meta.model_name
AttributeError: 'function' object has no attribute '_meta'
[04/Nov/2018 21:53:55] "POST /weekly_upload HTTP/1.1" 500 138219

我不知道django-excel或save_to_database方法,但很明显model=weekly_upload这里是不正确的。 weekly_upload 是您的视图函数,但您可能打算使用的模型 class 称为 Weekly_upload(大写字母 W)。

尝试在此处更改最后一行:

from .models import Weekly_upload
...
def weekly_upload(request):
    ...
    request.FILES['file'].save_to_database(model=weekly_upload, ...)

至:

    request.FILES['file'].save_to_database(model=Weekly_upload, ...)

此外,我建议为 classes 采用 python pep8 约定命名约定:WeeklyUpload.

这样可以更容易地避免这种错误。也许尝试为模型或视图函数找到一个不同的、更具描述性的名称,这样您就不会将它们相互混淆。