2017-09-13 2 views

답변

3

modeladmin 또는 snippet을 사용하여이 모델을 사용자에게 노출시키는 것은 스크린 샷에서 명확하지 않지만 이전 모델을 가정합니다.

머리글에 단추를 직접 추가 할 수있는 고리는 모르지만이 부분 만 덮어 쓸 수있는 uses blocks 템플릿을 사용해야합니다.

템플릿의 resolution order을 활용하고 보다 우선 적용되는 /modeladmin/app-name/model-name/index.html을 만들 수 있습니다.

{% extends "modeladmin/index.html %} 

{% block header_extra %} 
    <a href="#">My New Button</a> 
    {{ block.super }}{% comment %}Display the original buttons {% endcomment %} 
{% endblock %} 

이 지금 당신의 버튼을 많이하지 않습니다 그래서 feedler라는 응용 프로그램 및 Entry라는 모델, 다음과 같은 내용으로 /modeladmin/feedler/entry/index.html를 작성하여 주어진. 해당 모델 관리자와 상호 작용할 작업을 만들려면 버튼/URL/권한 helpers 및보기를 만들어야합니다.

조치로 개체를 CSV 파일로 내보내는 경우를 가정 해 보겠습니다. 자신을 지켜라. 앞으로 약간의 코드가있다.

/feedler/admin.py에서

, 버튼/URL/허가 도우미 및보기 작성 : /feedler/wagtail_hooks.py에서

from django.contrib.auth.decorators import login_required 
from django.core.urlresolvers import reverse 
from django.utils.decorators import method_decorator 
from django.utils.functional import cached_property 
from django.utils.translation import ugettext as _ 
from wagtail.contrib.modeladmin.helpers import AdminURLHelper, ButtonHelper 
from wagtail.contrib.modeladmin.views import IndexView 


class ExportButtonHelper(ButtonHelper): 
    """ 
    This helper constructs all the necessary attributes to create a button. 

    There is a lot of boilerplate just for the classnames to be right :(
    """ 

    export_button_classnames = ['icon', 'icon-download'] 

    def export_button(self, classnames_add=None, classnames_exclude=None): 
     if classnames_add is None: 
      classnames_add = [] 
     if classnames_exclude is None: 
      classnames_exclude = [] 

     classnames = self.export_button_classnames + classnames_add 
     cn = self.finalise_classname(classnames, classnames_exclude) 
     text = _('Export {}'.format(self.verbose_name_plural.title())) 

     return { 
      'url': self.url_helper.get_action_url('export', query_params=self.request.GET), 
      'label': text, 
      'classname': cn, 
      'title': text, 
     } 


class ExportAdminURLHelper(FilterableAdminURLHelper): 
    """ 
    This helper constructs the different urls. 

    This is mostly just to overwrite the default behaviour 
    which consider any action other than 'create', 'choose_parent' and 'index' 
    as `object specific` and will try to add the object PK to the url 
    which is not what we want for the `export` option. 

    In addition, it appends the filters to the action. 
    """ 

    non_object_specific_actions = ('create', 'choose_parent', 'index', 'export') 

    def get_action_url(self, action, *args, **kwargs): 
     query_params = kwargs.pop('query_params', None) 

     url_name = self.get_action_url_name(action) 
     if action in self.non_object_specific_actions: 
      url = reverse(url_name) 
     else: 
      url = reverse(url_name, args=args, kwargs=kwargs) 

     if query_params: 
      url += '?{params}'.format(params=query_params.urlencode()) 

     return url 

    def get_action_url_pattern(self, action): 
     if action in self.non_object_specific_actions: 
      return self._get_action_url_pattern(action) 

     return self._get_object_specific_action_url_pattern(action) 


class ExportView(IndexView): 
    """ 
    A Class Based View which will generate 
    """ 

    def export_csv(self): 
     data = self.queryset.all() 
     response = ... 
     return response 


    @method_decorator(login_required) 
    def dispatch(self, request, *args, **kwargs): 
     super().dispatch(request, *args, **kwargs) 
     return self.export_csv() 


class ExportModelAdminMixin(object): 
    """ 
    A mixin to add to your model admin which hooks the different helpers, the view 
    and register the new urls. 
    """ 

    button_helper_class = ExportButtonHelper 
    url_helper_class = ExportAdminURLHelper 

    export_view_class = ExportView 

    def get_admin_urls_for_registration(self): 
     urls = super().get_admin_urls_for_registration() 
     urls += (
      url(
       self.url_helper.get_action_url_pattern('export'), 
       self.export_view, 
       name=self.url_helper.get_action_url_name('export') 
      ), 
     ) 

     return urls 

    def export_view(self, request): 
     kwargs = {'model_admin': self} 
     view_class = self.export_view_class 
     return view_class.as_view(**kwargs)(request) 

생성, 및 registerModelAdmin : 모든 설치와

from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register 

from .admin import ExportModelAdminMixin 
from .models import Entry 

class EntryModelAdmin(ExportModelAdminMixin, ModelAdmin): 
    model = Entry 
    # ... 

modeladmin_register(EntryModelAdmin) 

, 당신은 할 수 있어야한다 위에 작성한 템플릿에 {% include 'modeladmin/includes/button.html' with button=view.button_helper.export_button %}을 사용하십시오.

+0

설명해 주셔서 감사합니다. 나는 당신의 지시에 따라 모든 것을했지만 불행히도 버튼이 나타나지 않았습니다. 나는 내가 어디에서라도 오해하지 않았 으면 좋겠다. 귀하의 코드에서이 행은 누락되었습니다 : 'from django.utils.decorators import method_decorator'. 내 모델 ** ** [github repo] (https://github.com/khashashin/public-health-ch/blob/fd2ccf68eb488365a97d6fc49d0e1c8d6f4a5b49/feedler/models/models.py#L57) ** 템플릿 : * * [템플릿] (https://github.com/khashashin/public-health-ch/blob/fd2ccf68eb488365a97d6fc49d0e1c8d6f4a5b49/modeladmin/feedler/entry/index.html#L1) – khashashin

+0

누락 된 가져 오기를 지적 해 주셔서 감사합니다. 답변을 업데이트했습니다. 지금 표시되는 버튼에 대해서는 새로운 [ModelAdmin] (https://github.com/khashashin/public-health-ch/blob/fd2ccf68eb488365a97d6fc49d0e1c8d6f4a5b49/feedler/models/models.py#L166)을 등록하지 않았기 때문에 표시됩니다.) 대신에 [구형] (https://github.com/khashashin/public-health-ch/blob/fd2ccf68eb488365a97d6fc49d0e1c8d6f4a5b49/feedler/wagtail_hooks.py#L8)을 등록하십시오. 'wagtail_hooks.py'에서'EntryModelAdmin'을 업데이트하고'ExportModelAdminMixin'에서 상속 받도록하십시오. –

+0

또한, 모든 모델 관리 로직을'wagtail_hooks.py' 또는'admin.py'로 옮길 수 있습니다. 계층 구조를 표시하고 모델 이름을 업데이트하는 대답을 업데이트하겠습니다. –