export的管理员导入表单

export的管理员导入表单

本文介绍了扩展django import_export的管理员导入表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Django import_export 在我的系统中实现CSV上传管理页面.现在,我有一个模型,其中包含一个外键列,但是每次导入时,外键列将只有一个值.因此,我希望允许用户从下拉列表中选择相关的模型实例,而不是强迫用户自己添加列.为此,我需要自定义导入表单,该表单需要覆盖默认方法import_actionprocess_import,但是到目前为止,我的工作并未显示任何效果.这是我到目前为止的内容:

I'm using Django import_export to implement CSV upload in my admin pages. Now I have one model, that contains a foreign key column, but the foreign key column will have only one value for each import. Therefore I would like to allow the user to choose the related model instance from a drop-down instead of forcing the user to append the columns themselves. In order to do this I need to customize the import form, which requires overriding the default methods import_action and process_import, but my efforts so far have shown no effect. Here is what I have so far:

from django import forms
from import_export.forms import ImportForm
from .models import MyModel, RelatedModel

class CustomImportForm(ImportForm):
    """Add a model choice field for a given model to the standard form."""
    appended_instance = forms.ModelChoiceField(queryset=None)

    def __init__(self, choice_model, import_formats, *args, **kwargs):
        super(CustomImportForm, self).__init__(import_formats, *args, **kwargs)
        self.fields['appended_instance'].queryset = choice_model.objects.all()

@admin.register(MyModel)
class MyModelAdmin(ImportExportModelAdmin):
    resource_class = SomeResource


    def import_action(self, request, *args, **kwargs):
        super().import_action(self, request, *args, **kwargs)
        form = CustomImportForm(RelatedModel,
                                import_formats,
                                request.POST or None,
                                request.FILES or None)

现在,当我进入导入页面时,我得到了AttributeError MyModelAdmin has no attribute 'POST',并且在本地变量中,我可以看到request object实际上是MyModelAdmin类,我相信这不是应该的./p>

Now when I go the import page I get the AttributeError MyModelAdmin has no attribute 'POST' and in the local vars I can see that the request object is actually the MyModelAdmin class, which is I believe is not what it's supposed to be.

推荐答案

我知道,这是一篇旧文章,但是在研究如何覆盖import_action时,我遇到了这个问题.您的错误在这里:super().import_action(self, request, *args, **kwargs)

I know, this is an old post, but I ran into this, when looking on how to override the import_action.Your error is here:super().import_action(self, request, *args, **kwargs)

您应该在没有自我的情况下调用它:

You should call it without the self:

super().import_action(request, *args, **kwargs)

或对于较旧的python:

or for older python:

super(MyModelAdmin, self).import_action(request, *args, **kwargs)

这篇关于扩展django import_export的管理员导入表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 18:48