扩展django import

编程入门 行业动态 更新时间:2024-10-22 22:59:23
本文介绍了扩展django import_export的管理员导入表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 Django import_export 在我的系统中实现CSV上传管理页面.现在,我有一个模型,其中包含一个外键列,但是每次导入时,外键列将只有一个值.因此,我希望允许用户从下拉列表中选择相关的模型实例,而不是强迫用户自己添加列.为此,我需要自定义导入表单,该表单需要覆盖默认方法import_action和process_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

本文发布于:2023-10-24 17:08:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524519.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:django   import

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!