- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我想将 django-import-export
与基于类的 View 一起使用。
在 https://django-import-export.readthedocs.org/en/latest/getting_started.html 的文档中我看到一个导出为 csv 的示例
>>> dataset = BookResource().export()
>>> print dataset.csv
id,name,author,author_email,imported,published,price,categories
2,Some book,1,,0,2012-12-05,8.85,1
但是如果我想返回一个 Excel 文件,我应该使用哪个基于类的 View 呢?只是查看
?
最佳答案
果酱,
基于 https://github.com/bmihelac/django-import-export 的实现并以具有名称和缩写属性的模型“国家/地区”为例:
首先,在国家模型文件的末尾定义资源:
class CountryResource(resources.ModelResource):
class Meta:
model = Country
然后,实现基于类的 View :
class CountryExport(View):
def get(self, *args, **kwargs ):
dataset = CountryResource().export()
response = HttpResponse(dataset.csv, content_type="csv")
response['Content-Disposition'] = 'attachment; filename=filename.csv'
return response
class CountryImport(View):
model = Country
from_encoding = "utf-8"
#: import / export formats
DEFAULT_FORMATS = (
base_formats.CSV,
base_formats.XLS,
base_formats.TSV,
base_formats.ODS,
base_formats.JSON,
base_formats.YAML,
base_formats.HTML,
)
formats = DEFAULT_FORMATS
#: template for import view
import_template_name = 'Country/import.html'
resource_class = None
def get_import_formats(self):
"""
Returns available import formats.
"""
return [f for f in self.formats if f().can_import()]
def get_resource_class(self):
if not self.resource_class:
return modelresource_factory(self.model)
else:
return self.resource_class
def get_import_resource_class(self):
"""
Returns ResourceClass to use for import.
"""
return self.get_resource_class()
def get(self, *args, **kwargs ):
'''
Perform a dry_run of the import to make sure the import will not
result in errors. If there where no error, save the user
uploaded file to a local temp file that will be used by
'process_import' for the actual import.
'''
resource = self.get_import_resource_class()()
context = {}
import_formats = self.get_import_formats()
form = ImportForm(import_formats,
self.request.POST or None,
self.request.FILES or None)
if self.request.POST and form.is_valid():
input_format = import_formats[
int(form.cleaned_data['input_format'])
]()
import_file = form.cleaned_data['import_file']
# first always write the uploaded file to disk as it may be a
# memory file or else based on settings upload handlers
with tempfile.NamedTemporaryFile(delete=False) as uploaded_file:
for chunk in import_file.chunks():
uploaded_file.write(chunk)
# then read the file, using the proper format-specific mode
with open(uploaded_file.name,
input_format.get_read_mode()) as uploaded_import_file:
# warning, big files may exceed memory
data = uploaded_import_file.read()
if not input_format.is_binary() and self.from_encoding:
data = force_text(data, self.from_encoding)
dataset = input_format.create_dataset(data)
result = resource.import_data(dataset, dry_run=True,
raise_errors=False)
context['result'] = result
if not result.has_errors():
context['confirm_form'] = ConfirmImportForm(initial={
'import_file_name': os.path.basename(uploaded_file.name),
'input_format': form.cleaned_data['input_format'],
})
context['form'] = form
context['opts'] = self.model._meta
context['fields'] = [f.column_name for f in resource.get_fields()]
return TemplateResponse(self.request, [self.import_template_name], context)
def post(self, *args, **kwargs ):
'''
Perform a dry_run of the import to make sure the import will not
result in errors. If there where no error, save the user
uploaded file to a local temp file that will be used by
'process_import' for the actual import.
'''
resource = self.get_import_resource_class()()
context = {}
import_formats = self.get_import_formats()
form = ImportForm(import_formats,
self.request.POST or None,
self.request.FILES or None)
if self.request.POST and form.is_valid():
input_format = import_formats[
int(form.cleaned_data['input_format'])
]()
import_file = form.cleaned_data['import_file']
# first always write the uploaded file to disk as it may be a
# memory file or else based on settings upload handlers
with tempfile.NamedTemporaryFile(delete=False) as uploaded_file:
for chunk in import_file.chunks():
uploaded_file.write(chunk)
# then read the file, using the proper format-specific mode
with open(uploaded_file.name,
input_format.get_read_mode()) as uploaded_import_file:
# warning, big files may exceed memory
data = uploaded_import_file.read()
if not input_format.is_binary() and self.from_encoding:
data = force_text(data, self.from_encoding)
dataset = input_format.create_dataset(data)
result = resource.import_data(dataset, dry_run=True,
raise_errors=False)
context['result'] = result
if not result.has_errors():
context['confirm_form'] = ConfirmImportForm(initial={
'import_file_name': os.path.basename(uploaded_file.name),
'input_format': form.cleaned_data['input_format'],
})
context['form'] = form
context['opts'] = self.model._meta
context['fields'] = [f.column_name for f in resource.get_fields()]
return TemplateResponse(self.request, [self.import_template_name], context)
class CountryProcessImport(View):
model = Country
from_encoding = "utf-8"
#: import / export formats
DEFAULT_FORMATS = (
base_formats.CSV,
base_formats.XLS,
base_formats.TSV,
base_formats.ODS,
base_formats.JSON,
base_formats.YAML,
base_formats.HTML,
)
formats = DEFAULT_FORMATS
#: template for import view
import_template_name = 'Country/import.html'
resource_class = None
def get_import_formats(self):
"""
Returns available import formats.
"""
return [f for f in self.formats if f().can_import()]
def get_resource_class(self):
if not self.resource_class:
return modelresource_factory(self.model)
else:
return self.resource_class
def get_import_resource_class(self):
"""
Returns ResourceClass to use for import.
"""
return self.get_resource_class()
def post(self, *args, **kwargs ):
'''
Perform the actual import action (after the user has confirmed he
wishes to import)
'''
opts = self.model._meta
resource = self.get_import_resource_class()()
confirm_form = ConfirmImportForm(self.request.POST)
if confirm_form.is_valid():
import_formats = self.get_import_formats()
input_format = import_formats[
int(confirm_form.cleaned_data['input_format'])
]()
import_file_name = os.path.join(
tempfile.gettempdir(),
confirm_form.cleaned_data['import_file_name']
)
import_file = open(import_file_name, input_format.get_read_mode())
data = import_file.read()
if not input_format.is_binary() and self.from_encoding:
data = force_text(data, self.from_encoding)
dataset = input_format.create_dataset(data)
result = resource.import_data(dataset, dry_run=False,
raise_errors=True)
# Add imported objects to LogEntry
ADDITION = 1
CHANGE = 2
DELETION = 3
logentry_map = {
RowResult.IMPORT_TYPE_NEW: ADDITION,
RowResult.IMPORT_TYPE_UPDATE: CHANGE,
RowResult.IMPORT_TYPE_DELETE: DELETION,
}
content_type_id=ContentType.objects.get_for_model(self.model).pk
'''
for row in result:
LogEntry.objects.log_action(
user_id=request.user.pk,
content_type_id=content_type_id,
object_id=row.object_id,
object_repr=row.object_repr,
action_flag=logentry_map[row.import_type],
change_message="%s through import_export" % row.import_type,
)
'''
success_message = _('Import finished')
messages.success(self.request, success_message)
import_file.close()
url = reverse('%s_list' % (str(opts.app_label).lower()))
return HttpResponseRedirect(url)
模板 import.html 具有以下代码:
<h1>{% trans "Importar" %} {{ opts.app_label }}</h1>
{% if confirm_form %}
<form action="{% url "process_import" %}" method="POST">
{% csrf_token %}
{{ confirm_form.as_p }}
<p>
{% trans "Below is a preview of data to be imported. If you are satisfied with the results, click 'Confirm import'" %}
</p>
<div class="submit-row">
<input type="submit" class="btn" name="confirm" value="{% trans "Confirm import" %}">
</div>
</form>
{% else %}
<form action="{{ form_url }}" method="post" id="{{ opts.module_name }}_form" enctype="multipart/form-data">
{% csrf_token %}
<p>
{% trans "This importer will import the following fields: " %}
{% for f in fields %}
{% if forloop.counter0 %}
,
{% endif %}
<tt>{{ f }}</tt>
{% endfor %}
</p>
<fieldset class="module aligned">
{% for field in form %}
<div class="form-row">
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
{% if field.field.help_text %}
<p class="help">{{ field.field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
</fieldset>
<div class="submit-row">
<input type="submit" class="btn" value="{% trans "Submit" %}">
</div>
</form>
{% endif %}
{% if result %}
{% if result.has_errors %}
<h2>{% trans "Errors" %}</h2>
<ul>
{% for error in result.base_errors %}
<li>{{ error.error }}</li>
{% endfor %}
{% for line, errors in result.row_errors %}
{% for error in errors %}
<li>
{% trans "Line number" %}: {{ line }} - {{ error.error }}
<div class="traceback">{{ error.traceback|linebreaks }}</div>
</li>
{% endfor %}
{% endfor %}
</ul>
{% else %}
<h2>
{% trans "Preview" %}
</h2>
<table>
<thead>
<tr>
<th></th>
{% for field in fields %}
<th>{{ field }}</th>
{% endfor %}
</tr>
</thead>
{% for row in result.rows %}
<tr>
<td>
{% if row.import_type == 'new' %}
{% trans "New" %}
{% elif row.import_type == 'skip' %}
{% trans "Skipped" %}
{% elif row.import_type == 'delete' %}
{% trans "Delete" %}
{% elif row.import_type == 'update' %}
{% trans "Update" %}
{% endif %}
</td>
{% for field in row.diff %}
<td>
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% endif %}
{% endif %}
并且 urls.py 应该包含:
#export
url(r'export/$', login_required(CountryExport.as_view()), name='country_export'),
#import
url(r'import/$', login_required(CountryImport.as_view()), name='country_import'),
url(r'process_import/$', login_required(CountryProcessImport.as_view()), name='process_import'),
关于python - 将 django-import-export 与基于类的 View 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24008820/
在我的项目代码优化期间,我替换了 var 的所有实例关键词 let因为我认为 var 没有特别的用途.为此,我在所有文件中执行了“查找和替换”操作。 在一些自定义模块中,我使用了如下语句: var e
我遇到过使用“双”导出来创建当前组件的情况。您能否解释一下它是否有真正的用途,或者只是作者的偏好? import React from 'react' import DuckImage from '.
我编写了一个简单的脚本来创建用户 (TestV100)、在该架构中创建表 (Xy100) 并将制表符分隔的平面文件从 hadoop 导出到此 Oracle 表。 这是 shell 脚本:-Export
我真的很困惑: export const foo 导出默认 foo module.exports = foo; 我知道这些是非常基本的,但有人可以区分并向我解释这些。我真的很想明白。 最佳答案 让我们
今天我在我的 AngularJS 项目中采用了 Browserify,但是我还不清楚。在所有示例和博客文章中,我都看到了这样的东西: /app.js: require('./messages'); a
我正在寻找一种方法: 隐藏 HTML 页面结果上的标题 导出时在 highcharts 图表上显示标题(PDF、PNG、JPEG 或打印) 我不知道如何继续。有人可以帮助我吗? 最佳答案 您可以在导出
在我的应用程序的首选项中,我调用以特殊方式处理某些参数的 Activity 。到目前为止它运作良好。但是,为了创建试用版和专业版,我刚刚创建了一个包含所有代码的库和一个调用该库的新演示应用程序。除了由
pentaho cde 导出组件正在为我工作,它导出表数据,文件名为 cda-export.csv,我可以自动设置文件名吗? 最佳答案 尝试使用参数 {filename : 'myfilename
我想从 Gephi 的预览选项卡中导出 SVG/PDF/PNG。导出的网络包括所有节点,但切断了左右两侧的节点标签。如何获得不切断标签的导出 pdf? 最佳答案 您必须通过控制选项 来调整输出的大小。
如标题所述,我在尝试使用我的 perl 模块时遇到此错误,但我不知道它是什么意思,而且我似乎无法在 Internet 上找到任何明确的结果。我的代码由 3 个文件组成:一个脚本 (myApp.pl),
我曾经每天下载一个 firebase 实时数据库的节点,通过导出该节点的 .JSON 文件来监控一些输出。 JSON 文件本身大约 8MB。 最近,我开始收到一个错误: “导出 JSON 无法导出在单
之间有什么区别 export * as bar from 'foo' 和 export { default as bar } from 'foo' 在我的特殊情况下,我尝试了以下两种方法,它们都有效,
我想我要求的是不可能的OOB,但我想确认一下。 我们正在升级到 ES6(使用 Babel)。项目是一个网站,使用 AMD (requirejs)。我想将实用程序模块 (foolib) 转换为 ES6,
我一直在我的 React 中广泛使用命名导出和默认导出,我遇到了这 2 个相似的语法。 从'./Button'导出默认值; export { default } from './Button'; 有人
在此页面 ( http://docs.nodejitsu.com/articles/getting-started/what-is-require ) 上,它指出“如果要将导出对象设置为函数或新对象,
在此页面 ( http://docs.nodejitsu.com/articles/getting-started/what-is-require ) 上,它指出“如果要将导出对象设置为函数或新对象,
我在运行 flow check 时收到此错误,但我不确定这是什么意思。 Cannot use exports as a type because exports is a value. To get
module.export和export有什么区别? 如果module.export对象中有一些属性怎么办?export.xx 会无效吗? 最佳答案 首先是 exports 和 module.expo
我正在学习 typescript 。在研究一些源文件时,我发现声明文件 .d 中有时有 export declare ... 有时只有 export ... .ts. 经过一些测试,在我看来它们是等价
假设我有一个要导出的变量。有什么区别 export const a = 1; 对比 export let a = 1; 我理解const 和let 之间的区别,但是当你导出它们时,有什么区别? 最佳答
我是一名优秀的程序员,十分优秀!