2016-04-28 95 views
2

我使用Django import_export在我的管理頁面中實現CSV上載。現在我有一個模型,它包含一個外鍵列,但外鍵列對於每個導入只有一個值。因此,我希望允許用戶從下拉列表中選擇相關的模型實例,而不是強制用戶自行追加列。爲了做到這一點,我需要自定義導入表單,這需要覆蓋默認方法import_actionprocess_import,但是迄今爲止我的努力沒有發揮作用。以下是我迄今爲止:爲django import_export擴展管理導入表單

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類,這是我認爲這不是什麼它應該是。

回答

1

我知道,這是一箇舊的帖子,但我碰到這個,當看着如何覆蓋import_action。 你的錯誤是在這裏: super().import_action(self, request, *args, **kwargs)

你應該把它叫做沒有自我:

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

還是老的Python:

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

0
def import_action(self, request, *args, **kwargs): 
     response = super(MyModelAdmin, self).import_action(request, *args, **kwargs) 
     context = response.context_data 
     import_formats = self.get_import_formats() 
     context['form'] = CustomImportForm(RelatedModel, import_formats, request.POST or None, request.FILES or None) 
     return TemplateResponse(request, [self.import_template_name], context)