How to search for django admin_ Fields add search box prompt text


As shown in the above figure, django admin adds search in ModelAdmin_ Fields can display a search box, but the prompt text of the search box cannot be set. In the actual development, it is a way to quickly improve the user experience to let the user know what to input for rapid retrieval. We have found a lot on the Internet and have not solved this problem well. Today we will start to implement one!

I have created an app named dadmin here through the following command

python manage.py startapp dadmin

Create a new folder of templatetags under the dadmin directory, and create a search inside it_ with_ placeholder. Py. The internal code is as follows:

# dadmin/templatetags/search_with_placeholder.py

from django.contrib.admin.templatetags.admin_list import (register, search_form)
from django.contrib.admin.templatetags.base import InclusionAdminNode


def search_form_plus(cl, search_placeholder: str = ""):
    """
    Display a search form for searching the list with placeholder.
    """
    return dict(search_form(cl), search_placeholder=search_placeholder)


@register.tag(name='search_form_plus')
def search_form_tag(parser, token):
    return InclusionAdminNode(parser, token, func=search_form_plus, template_name='search_form_plus.html', takes_context=False)

At the same level as the project, that is, the root directory, create a templates directory, and then create an admin folder inside it. If you rewrite any default template of admin, you only need to put it in this folder. This is also the easiest way to modify the default template of django admin. We create a search inside it_ form_ plus. HTML file. The internal code is as follows:

{% load i18n static %}
{% if cl.search_fields %}
<div id="toolbar"><form id="changelist-search" method="get">
<div><!-- DIV needed for valid HTML -->
<label for="searchbar"><img src="{% static "admin/img/search.svg" %}" alt="Search"></label>
<input type="text" size="40" name="{{ search_var }}" value="{{ cl.query }}" placeholder="{{ search_placeholder }}" id="searchbar" autofocus>
<input type="submit" value="{% translate 'Search' %}">
{% if show_result_count %}
    <span class="small quiet">{% blocktranslate count counter=cl.result_count %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktranslate %} (<a href="?{% if cl.is_popup %}_popup=1{% endif %}">{% if cl.show_full_result_count %}{% blocktranslate with full_result_count=cl.full_result_count %}{{ full_result_count }} total{% endblocktranslate %}{% else %}{% translate "Show all" %}{% endif %}</a>)</span>
{% endif %}
{% for pair in cl.params.items %}
    {% if pair.0 != search_var %}<input type="hidden" name="{{ pair.0 }}" value="{{ pair.1 }}">{% endif %}
{% endfor %}
</div>
</form></div>
{% endif %}

Then create a folder path of templates/dadmin under the dadmin directory, and then create a change inside it_ list. HTML file. The internal code is as follows:

<!-- 
Full file path, which is a comment and can be deleted from the template
dadmin/templates/dadmin/change_list.html 
-->

{% extends 'admin/change_list.html' %}
{% load search_with_placeholder %}
{% block search %}{% search_form_plus cl search_placeholder %}{% endblock %}

After that, click admin. In the dadmin directory Py defines a BaseAdmin basic class for all ModelAdmin. In the future, we can inherit BaseAdmin where ModelAdmin is used. The code is as follows:

class BaseAdmin(admin.ModelAdmin):
	change_list_template = "dadmin/change_list.html"
	
	def changelist_view(self, request, extra_context=None):
        # List view, adding search_placeholder = ""
        # You can define the value of the search box or pass any data to the list page
        search_placeholder = getattr(self, "search_placeholder", False)
        if search_placeholder:
            extra_context = extra_context or {}
            extra_context["search_placeholder"] = search_placeholder
        return super().changelist_view(request, extra_context=extra_context)

It is also very simple to use. All modeladmins only need to inherit it, as shown in the following example:

class CategoryModelAdmin(BaseAdmin):
    """
    Classification management configuration
    """

    list_display = ('id', 'name', 'is_show', 'cate_icon',
                    'sort',  'add_date', 'operate')
    search_fields = ('name',)  # Set search box
    search_placeholder = 'Please enter a category name to search'  # Sets the prompt text for the search box

admin.site.register(CategoryModel, CategoryModelAdmin)

Other list pages also need to set the search box text. You can inherit BaseAdmin. It's very simple. Take it directly!

For relevant source code, please refer to: https://gitee.com/xingfugz/django-mall

If you are learning django, then welcome to the private letter Xiaobian to exchange study, welcome star above items, give encouragement, and welcome you to pay attention to my official account. Happy Guanzhong ”, learn and communicate together. There are a lot of learning materials on it!

Keywords: Python Django

Added by phpfanphp on Mon, 27 Dec 2021 18:03:44 +0200