2020-04-08 Created: windows10 / Python-3.8.2-amd64 / Django-3.0.4
Logging the source IP address isn't enough for Django to analyze user behavior. To uniquely identify a user, it's easy to log who accessed it on the HTTP server.
Customize the response headers to keep the Django user ID in the HTTP server logs. Here's how to add the Django user ID to the request headers in the generic class view.
reference https://blog.howtelevision.co.jp/entry/2014/09/05/170917
If you're new to Django, click here. Practical tutorial on Django in 10 minutes
Add the response header userid you want to add to the generic view class.
custom_views.py
class CustomListView(generic.ListView):
def dispatch(self, *args, **kwargs):
response = super().dispatch(*args, **kwargs)
response['userid'] = self.request.user
return response
Instead of inheriting ListView, inherit CustomListView and declare the actual view class to use.
views.py
from .custom_views import *
from .models import MyClass
from django.contrib.auth.mixins import LoginRequiredMixin
class MemoListView(LoginRequiredMixin, CustomListView):
model = MyClass
The same can be done with other view classes as well as ListView.
If you change the settings of an HTTP server such as Nginx and leave the newly created response header in the log, the access source will be recorded in the log.
The end
Recommended Posts