【问题标题】:Passing context to django admin index page将上下文传递给 django 管理索引页面
【发布时间】:2020-08-25 17:57:38
【问题描述】:

我正在尝试在 django 管理员的索引页面上创建一个表格,列出在特定时间范围内注册的所有用户。我已经设法编辑索引页面以包含我的表格,但我现在想填充表格。我尝试声明 extra_context 变量,但它仍然没有将它传递给模板。我一直在这个问题上几天,仍然无法弄清楚我做错了什么。这是我的admin.py 文件

from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from .forms import SignUpForm, EditUserForm
from .models import CustomUser
from django.urls import path
from datetime import datetime, timedelta
from django.utils import timezone


class CustomUserAdmin(UserAdmin):
    list_filter = ['created_at',]
    list_display = ['username', 'email', 'created_at', 'is_active']
    # index_template = 'admin/my_index.html'

    def time_threshold(num):
        num = int(num)
        thresh = datetime.now(tz=timezone.utc) - timedelta(hours=num)
        return thresh


    print(time_threshold(30))       
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path("user_metrics/", self.user_metrics),
        ]
        return custom_urls + urls

    def user_metrics(self, request, extra_context=None):
        extra_context = extra_context or {}
        user_24 = CustomUser.objects.filter(created_at__gt=time_threshold(730))
        extra_context['users_in_past_24_hours'] = CustomUser.objects.filter(created_at__gt=time_threshold(24))
        extra_context['users_in_past_week'] = CustomUser.objects.filter(created_at__gt=time_threshold(168))
        extra_context['users_in_past_month'] = CustomUser.objects.filter(created_at__gt=time_threshold(730))
        print(user_24)
        return super(CustomUserAdmin, self).user_metrics(request, extra_context=extra_context)


admin.site.register(CustomUser, CustomUserAdmin)
admin.site.unregister(Group)
admin.site.site_header = "Savests Custom Admin"

这是我在模板/管理文件夹中的 index.html 文件

{% extends "admin/base_site.html" %}
{% load i18n static %}

{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}">{% endblock %}

{% block coltype %}colMS{% endblock %}

{% block bodyclass %}{{ block.super }} dashboard{% endblock %}

{% block breadcrumbs %}{% endblock %}

{% block nav-sidebar %}{% endblock %}

{% block content %}
<div id="content-main">
  {% include "admin/app_list.html" with app_list=app_list show_changelinks=True %}
</div>

<div>
    <h5>Users in the last 24 hours</h5>
        <table class="table table-hover table-bordered">
            <caption>User Information</caption>
            <thead class="thead-dark">
                <th>User ID</th>
                <th>Username</th>
                <th>Email Address</th>
                <th>Active Status</th>
                <th>Staff Status</th>
            </thead>
            {% for a in users_in_past_24_hours %}
                <tr>
                    <td>{{ a.id }}</td>
                    <td>{{ a.username }}</td>
                    <td>{{ a.email }}</td>
                    <td>
                        {% if a.is_active %}
                            <form action="{% url 'toggle_user_status_false' user_id=a.id %}" method="post">
                                {% csrf_token %}
                                    <button class="btn btn-danger" type="submit">
                                        Deactivate
                                    </button>
                            </form>
                        {% else %}
                            <form action="{% url 'toggle_user_status_true' user_id=a.id %}" method="post">
                                {% csrf_token %}
                                    <button class="btn btn-primary" type="submit">
                                        Activate
                                    </button>
                            </form>
                        {% endif %}
                    </td>
                    <td>
                        {% if a.is_staff %}
                            Staff
                        {% else %}
                            Not Staff
                        {% endif %}
                    </td>
                </tr>
            {% endfor %}
        </table>
        <br>
        <hr>

        <h5>Users in the past week</h5>
        <table class="table table-hover table-bordered">
            <caption>User Information</caption>
            <thead class="thead-dark">
                <th>User ID</th>
                <th>Username</th>
                <th>Email Address</th>
                <th>Active Status</th>
                <th>Staff Status</th>
            </thead>
            {% for a in users_in_past_week %}
                <tr>
                    <td>{{ a.id }}</td>
                    <td>{{ a.username }}</td>
                    <td>{{ a.email }}</td>
                    <td>
                        {% if a.is_active %}
                            <form action="{% url 'toggle_user_status_false' user_id=a.id %}" method="post">
                                {% csrf_token %}
                                    <button class="btn btn-danger" type="submit">
                                        Deactivate
                                    </button>
                            </form>
                        {% else %}
                            <form action="{% url 'toggle_user_status_true' user_id=a.id %}" method="post">
                                {% csrf_token %}
                                    <button class="btn btn-primary" type="submit">
                                        Activate
                                    </button>
                            </form>
                        {% endif %}
                    </td>
                    <td>
                        {% if a.is_staff %}
                            Staff
                        {% else %}
                            Not Staff
                        {% endif %}
                    </td>
                </tr>
            {% endfor %}
        </table>
        <br>
        <hr>

        <h5>Users in the past month</h5>
        <table class="table table-hover table-bordered">
            <caption>User Information</caption>
            <thead class="thead-dark">
                <th>User ID</th>
                <th>Username</th>
                <th>Email Address</th>
                <th>Active Status</th>
                <th>Staff Status</th>
            </thead>
            {% for a in users_in_past_month %}
                <tr>
                    <td>{{ a.id }}</td>
                    <td>{{ a.username }}</td>
                    <td>{{ a.email }}</td>
                    <td>
                        {% if a.is_active %}
                            <form action="{% url 'toggle_user_status_false' user_id=a.id %}" method="post">
                                {% csrf_token %}
                                    <button class="btn btn-danger" type="submit">
                                        Deactivate
                                    </button>
                            </form>
                        {% else %}
                            <form action="{% url 'toggle_user_status_true' user_id=a.id %}" method="post">
                                {% csrf_token %}
                                    <button class="btn btn-primary" type="submit">
                                        Activate
                                    </button>
                            </form>
                        {% endif %}
                    </td>
                    <td>
                        {% if a.is_staff %}
                            Staff
                        {% else %}
                            Not Staff
                        {% endif %}
                    </td>
                </tr>
            {% endfor %}
        </table>
        <br>
        <hr>
</div>
{% endblock %}

{% block sidebar %}
<div id="content-related">
    <div class="module" id="recent-actions-module">
        <h2>{% translate 'Recent actions' %}</h2>
        <h3>{% translate 'My actions' %}</h3>
            {% load log %}
            {% get_admin_log 10 as admin_log for_user user %}
            {% if not admin_log %}
            <p>{% translate 'None available' %}</p>
            {% else %}
            <ul class="actionlist">
            {% for entry in admin_log %}
            <li class="{% if entry.is_addition %}addlink{% endif %}{% if entry.is_change %}changelink{% endif %}{% if entry.is_deletion %}deletelink{% endif %}">
                {% if entry.is_deletion or not entry.get_admin_url %}
                    {{ entry.object_repr }}
                {% else %}
                    <a href="{{ entry.get_admin_url }}">{{ entry.object_repr }}</a>
                {% endif %}
                <br>
                {% if entry.content_type %}
                    <span class="mini quiet">{% filter capfirst %}{{ entry.content_type.name }}{% endfilter %}</span>
                {% else %}
                    <span class="mini quiet">{% translate 'Unknown content' %}</span>
                {% endif %}
            </li>
            {% endfor %}
            </ul>
            {% endif %}
    </div>
</div>
{% endblock %}

【问题讨论】:

  • stackoverflow.com/questions/8893755/… - 第一个答案应该可以帮助你
  • @AndreyMaslov 我看到了这个答案,但我对如何实现它感到困惑。我是用 AdminSite 替换我正在扩展的 UserAdmin 类,还是应该创建一个扩展该类的新类?在答案的最后,他说要注册这个子类的实例并将其添加到 URLconf,我不确定他的意思是项目 url 文件还是应用程序拥有,以及我应该如何格式化它跨度>
  • 使用该答案中描述的方法和使用上下文处理器的方法添加答案

标签: python html django django-admin


【解决方案1】:

第一种方法是声明子类django.contrib.admin.site.AdminSite()并覆盖admin.py中的.index()方法

class MyAdminSite(django.contrib.admin.site.AdminSite):
    def index(self, request, extra_context=None):
        if extra_context is None:
            extra_context = {}
        user_24 = CustomUser.objects.filter(created_at__gt=time_threshold(730))
        extra_context['users_in_past_24_hours'] = CustomUser.objects.filter(created_at__gt=time_threshold(24))
        extra_context['users_in_past_week'] = CustomUser.objects.filter(created_at__gt=time_threshold(168))
        extra_context['users_in_past_month'] = CustomUser.objects.filter(created_at__gt=time_threshold(730))
        extra_context["app_list"] = get_app_list_in_custom_order()
        return super(MyAdminSite, self).index(request, extra_context)

那么您应该注册您的站点管理员(也在 admin.py 中) my_admin_site = MyAdminSite(name='myadmin') 当您创建自己的 AdminSite 时,您需要注册所有使用它的模型,所以而不是 admin.site.register(YourModel) 你应该使用my_admin_site.register(YourModel) 用于你使用的所有模型。您还需要在urls.py中添加到您的管理站点的路径

from pathtoyouradmin.admin import my_admin_site


urlpatterns = [
...
    path('admin/', my_admin_site.urls),
...
]

您可以通过其他方式解决您的问题。您可以创建contextprocessor,在其中检查当前页面的路径,如果它是管理索引,则提供所需的extra_context

def context_users_info(request):
    extra_context = {}
    if request.path == 'index admin page'# you need to put path to your index admin page
        user_24 = CustomUser.objects.filter(created_at__gt=time_threshold(730))
        extra_context['users_in_past_24_hours'] = CustomUser.objects.filter(created_at__gt=time_threshold(24))
        extra_context['users_in_past_week'] = CustomUser.objects.filter(created_at__gt=time_threshold(168))
        extra_context['users_in_past_month'] = CustomUser.objects.filter(created_at__gt=time_threshold(730))
        extra_context["app_list"] = get_app_list_in_custom_order()
    return extra_context

别忘了在settings.py注册你的上下文处理器

【讨论】:

  • 好的,我试试这个,尽快给反馈
  • 很高兴您在这里提供了多个实现选项。我正在尝试您的第二种方法来解决一些不同的情况。
猜你喜欢
  • 1970-01-01
  • 2017-01-21
  • 1970-01-01
  • 2015-05-10
  • 1970-01-01
  • 2016-05-12
  • 2012-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多