LoginSignup
0
0

More than 3 years have passed since last update.

Djangoの管理者サイトを少しだけ改造したかった話

Last updated at Posted at 2020-07-08

やりたかったこと

  • 選択したlist_filterを一括クリアするボタンをlist_filterタイトル横に配置したい image.png

方法

  • Templateの「Change_list.html」をオーバーライドする

  • app構成

C:Project Name
│  db.sqlite3
│  manage.py
│  
├─.idea
│      
├─Project Name
│  │  authentication.py
│  │  settings.py
│  │  urls.py
│  │  utils.py
│  │  wsgi.py
│  │  __init__.py
│  │  
│  ├─locate
│  └─__pycache__
│          
├─App Name
│  │  admin.py
│  │  apps.py
│  │  context_processors.py
│  │  forms.py
│  │  models.py
│  │  tests.py
│  │  urls.py
│  │  views.py
│  │  __init__.py
│  │  
│  ├─locate
│  ├─migrations
│  │  └─__pycache__
│  ├─templatetags
│  │  │  mytag.py
│  │  │  
│  │  └─__pycache__
│  │          mytag.cpython-37.pyc
│  │          
│  └─__pycache__
│          
├─templates
  │  __init__.py
  │  
  └─admin
      │  base_site.html
      │  index.html
      │  __init__.py
      │  
      └─App Name
          │  change_form_help_text.html
          │  change_list.html          ←このファイルを追加
          │  __init__.py
          │  
          ├─model name1
          │      change_form.html
          │      __init__.py
          │      
          └─model name2
                  change_form.html
                  __init__.py
  • Change_list.html

以下のようにオーバーライドする

Change_list.html
{% extends 'admin/change_list.html' %}
{% load admin_list %}
{% search_form cl %}
{% load i18n %}
{{ block.super }}

  {% block filters %}
    {% if cl.has_filters %}
      <div id="changelist-filter">
          <h2>{% trans 'Filter' %} <button id="clear" onclick="location.href=location.href.replace(/\#.*$/, '').replace(/\?.*$/, '');">clear</button></h2>
        {% if cl.has_active_filters %}<h3 id="changelist-filter-clear">
          <a href="{{ cl.clear_all_filters_qs }}">&#10006; {% trans "Clear all filters" %}</a>
        </h3>{% endif %}
        {% for spec in cl.filter_specs %}{% admin_list_filter cl spec %}{% endfor %}
      </div>
    {% endif %}
  {% endblock %}

結果

  • list_filterの解除自体は、追加したボタンをクリックした際に、現在のurlから検索クエリを抜いたurlを再設定することで実現した

  • Templateのオーバーライドの方法がわかれば、adminサイトを少し改造するのに便利

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0