不用admin怎么显示
时间: 2024-03-14 07:49:17 浏览: 19
如果不使用Django后台管理界面,可以使用Django模板来自定义前端页面,以显示记录的操作日志。
首先,需要在views.py中定义一个视图函数,用来获取记录的操作日志并将其传递给模板。例如:
```python
from auditlog.models import LogEntry
def history(request, pk):
history = LogEntry.objects.filter(object_pk=pk).order_by('-timestamp')
context = {'history': history}
return render(request, 'history.html', context)
```
这里定义了一个名为history的视图函数,其中pk是模型对象的主键值。该视图函数通过LogEntry.objects.filter方法获取该模型对象的操作日志,并按照时间戳倒序排序。然后,将操作日志保存在context字典中,并将该字典传递给名为history.html的模板。
接下来,在templates目录下创建history.html模板文件,并编写以下代码:
```html
{% extends 'base.html' %}
{% block content %}
<h1>History for {{ object }}</h1>
<table>
<thead>
<tr>
<th>Timestamp</th>
<th>Actor</th>
<th>Changes</th>
</tr>
</thead>
<tbody>
{% for log in history %}
<tr>
<td>{{ log.timestamp }}</td>
<td>{{ log.actor }}</td>
<td>
<ul>
{% for field, value in log.changes_display.items %}
<li>{{ field }}: {{ value }}</li>
{% endfor %}
</ul>
</td>
</tr>
{% empty %}
<tr>
<td colspan="3">No history found.</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
```
这里定义了一个名为history的模板,其中使用了base.html作为基础模板。模板中使用了一个表格来显示操作日志的timestamp、actor和changes_display_dict信息,其中使用了for循环来遍历所有的操作日志条目,并使用if语句来判断是否有操作日志条目。如果没有,模板将会显示"No history found."。
最后,在urls.py中定义一个URL模式,用来将视图函数history关联到某个URL上,例如:
```python
from django.urls import path
from . import views
urlpatterns = [
path('history/<int:pk>/', views.history, name='history'),
# ...
]
```
这里定义了一个名为history的URL模式,其中<int:pk>表示模型对象的主键值,views.history表示要调用的视图函数,name='history'表示该URL模式的名称为history。
现在,当用户访问http://example.com/history/1/时,就会显示主键值为1的模型对象的操作日志。