dgango项目实现登录日志
时间: 2023-07-17 15:08:35 浏览: 29
实现登录日志可以通过以下步骤:
1. 创建一个LoginLog模型来存储登录日志信息,例如:
```python
from django.db import models
from django.contrib.auth.models import User
class LoginLog(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
login_time = models.DateTimeField(auto_now_add=True)
ip_address = models.CharField(max_length=20)
```
2. 在用户登录成功后,在视图函数中创建LoginLog对象并保存到数据库中,例如:
```python
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .models import LoginLog
@login_required
def home(request):
# 创建LoginLog对象
login_log = LoginLog(user=request.user, ip_address=request.META['REMOTE_ADDR'])
login_log.save()
# 返回首页
return render(request, 'home.html')
```
3. 在管理后台中添加LoginLog模型的管理界面,例如:
```python
from django.contrib import admin
from .models import LoginLog
@admin.register(LoginLog)
class LoginLogAdmin(admin.ModelAdmin):
list_display = ('user', 'login_time', 'ip_address')
```
这样,每次用户登录成功后,都会自动记录登录日志信息,并且可以在管理后台中查看。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)