将django admin中编辑用户权限以及组后的操作记录在指定数据库中
时间: 2023-05-27 20:07:36 浏览: 70
要记录django admin中编辑用户权限以及组后的操作记录在指定数据库中,可以使用django的内置信号来监听用户权限和组的更改操作,并将这些操作记录到指定的数据库中。
首先,在你的应用程序中创建一个`signals.py`文件,并导入django的内置信号:
```python
from django.db.models.signals import post_save
from django.contrib.auth.models import User, Group, Permission
from django.dispatch import receiver
```
然后,定义一个`Record`模型表示编辑用户权限和组的操作记录,并将其记录到指定的数据库中:
```python
from django.db import models
from django.contrib.auth.models import User, Group, Permission
class Record(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
permission = models.ForeignKey(Permission, on_delete=models.CASCADE)
action = models.CharField(max_length=50)
time = models.DateTimeField(auto_now_add=True)
```
接下来,使用`@receiver`装饰器监听`post_save`信号,当用户权限和组的更改操作完成后,记录这些操作到数据库中:
```python
@receiver(post_save, sender=Permission)
def record_permission_change(sender, instance, **kwargs):
action = 'add' if kwargs.get('created') else 'change'
Record.objects.create(user=instance.user, group=instance.group, permission=instance, action=action)
@receiver(post_save, sender=Group)
def record_group_change(sender, instance, **kwargs):
action = 'add' if kwargs.get('created') else 'change'
Record.objects.create(user=instance.user, group=instance, action=action)
@receiver(post_save, sender=User)
def record_user_change(sender, instance, **kwargs):
action = 'add' if kwargs.get('created') else 'change'
Record.objects.create(user=instance, action=action)
```
最后,在`settings.py`文件中配置数据库信息:
```python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '3306',
}
}
```
这样,当管理员在django admin中编辑用户权限和组时,这些操作记录将被记录到指定的数据库中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)