Django Admin用户更新页:如何传递自定义列表参数?
Alright, let's get those songname and songcount lists over to your Django Admin change form. Since you've already set up the template extension, the key step is modifying your UserAdmin class to inject these custom variables into the template context.
Step 1: Customize Your UserAdmin Class
You'll need to override the render_change_form method in your UserAdmin (or the Admin class for your custom user model). This method is responsible for preparing the context that gets passed to the change form template.
Here's a complete example:
from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.contrib import admin class CustomUserAdmin(UserAdmin): def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): # Replace this with your actual logic to fetch/generate songname and songcount # For example, pulling data from a related model tied to the current user songname = ["Bohemian Rhapsody", "Stairway to Heaven", "Imagine"] songcount = [120, 95, 150] # Add your custom lists to the context dictionary context.update({ 'songname': songname, 'songcount': songcount }) # Call the parent class method to proceed with rendering return super().render_change_form(request, context, add, change, form_url, obj) # Replace the default UserAdmin with your custom one admin.site.unregister(User) admin.site.register(User, CustomUserAdmin)
Step 2: Use the Variables in Your change_form.html
Now you can access songname and songcount directly in your template. Since you're using Chart.js, it's safest to convert the Python lists to JSON (to avoid escaping issues and XSS risks). Use Django's json_script filter for this:
{% extends "admin/change_form.html" %} {% load static %} {% block after_related_objects %} <div style="margin:20px"> <div class="chart_container" style="height: 200px; width: 200px; clear: both;"> <canvas id="myChart" width="50" height="50"></canvas> </div> </div> <!-- Convert Python lists to safe JSON script tags --> {{ songname|json_script:"song-names" }} {{ songcount|json_script:"song-counts" }} <script src="{% static 'path/to/chart.js' %}"></script> <script> // Retrieve the JSON data from the script tags const songNames = JSON.parse(document.getElementById('song-names').textContent); const songCounts = JSON.parse(document.getElementById('song-counts').textContent); // Initialize your Chart.js chart const ctx = document.getElementById('myChart').getContext('2d'); new Chart(ctx, { type: 'bar', data: { labels: songNames, datasets: [{ label: 'Play Count', data: songCounts, backgroundColor: 'rgba(75, 192, 192, 0.2)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> {% endblock %}
Key Notes:
- If you're using a custom user model, replace
UserAdminandUserwith your model's Admin class and model respectively. - The
render_change_formmethod gives you access toobj(the current user being edited), so you can dynamically fetch data specific to that user (e.g.,songname = obj.songs.values_list('name', flat=True)). - Using
json_scriptis the recommended way to pass complex Python data structures to JavaScript in Django templates—it handles escaping and prevents XSS vulnerabilities.
内容的提问来源于stack exchange,提问作者Mek Vala

