首页 > 解决方案 > 如何跟踪用户所做的操作,甚至是使用 AJAX 所做的操作?

问题描述

在我的网站中,我正在跟踪用户所做的任何操作,以及一一查看的页面。

在某些观点中,我会执行一些 ajax 请求,例如:

def books_list(request):
    books_list = Book.objects.filter(published=True).order_by('-timestamp')
    if request.method == 'POST' and request.is_ajax():
         id_book = request.POST.get('id_book')
         try:
              book = books_list.get(id=id_book)
              book.delete()
         except Book.DoesNotExist:
              return JsonResponse({'error':True,'msg':'Book not found'})
    render(request,'book/books-list.html',context={'books_list':books_list})

这是它的外观的快速视图:

*# analytics *
- / # the home page
- /books/ # visits list of books
- /books/ # He deletes a book
- /books/ # back to list of books

如您所见,当用户删除一本书时,跟踪/books/显然会保持相同的 URL,我怎样才能拥有它:

*# analytics *
- / # the home page
- /books/ # visits list of books
- /books/delete # He deletes a book
- /books/ # back to list of books

我是否需要为简单的删除操作创建新的视图/url ?

标签: ajaxdjangoanalyticsdjango-urls

解决方案


您有两种记录用户正在做的事情的方法它基于跟踪的目的是什么,它只是用于记录还是在您的数据库中,但是第一个也可以解析为 db (no_sql) 或 (sql)您可以根据您的业务需求和项目需求获取这个抽象的答案并对其进行优化

第一种方式

视图.py

from .utils import get_client_ip
DELETED_FILES_LOGGER = logging.getLogger("deleted_files")
def books_list(request):
    books_list = Book.objects.filter(published=True).order_by('-timestamp')
    if request.method == 'POST' and request.is_ajax():
        id_book = request.POST.get('id_book')
        try:
          book = books_list.get(id=id_book)
          book.delete()
          DELETED_FILES_LOGGER.debug(
            'DELETION: %s by %s at %s from IP Address %s' % (
                book.filename(), request.user,
                datetime.datetime.now(), get_client_ip(request)))

        except Book.DoesNotExist:
          return JsonResponse({'error':True,'msg':'Book not found'})
    render(request,'book/books-list.html',context={'books_list':books_list})

实用程序.py

def get_client_ip(request):
    """
    to get client ip request
    :param request:
    :return: ip <str>
    """
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

第二种方式

模型.py

from django.contrib.admin.models import LogEntry as AbstractLogEntry


class LogEntry(AbstractLogEntry):
    class Meta:
        proxy = True
        app_label = 'data'
        verbose_name_plural = 'Log Entries'
        permissions = (("add_log", "add log entry"),
                       ("delete_log", "delete log entry"),
                       ("change_log", "change log entry"),
                       )

    def __str__(self):
        if self.action_flag == 5:
            return ugettext('Download "%(object)s."') % {'object': self.object_repr}
        if self.action_flag == 4:
            return ugettext('Uploaded "%(object)s."') % {'object': self.object_repr}
        elif self.is_addition():
            return ugettext('Added "%(object)s".') % {'object': self.object_repr}
        elif self.is_change():
            return ugettext('Changed "%(object)s" - %(changes)s') % {
                'object': self.object_repr,
                'changes': self.change_message,
            }
        elif self.is_deletion():
            return ugettext('Deleted "%(object)s."') % {'object': self.object_repr}

视图.py

def books_list(request):
books_list = Book.objects.filter(published=True).order_by('-timestamp')
if request.method == 'POST' and request.is_ajax():
     id_book = request.POST.get('id_book')
     try:
          book = books_list.get(id=id_book)

          book.delete()
          LogEntry.objects.log_action(user_id=request.user.id,
                                        change_message='Upload %s for category %s' % (
                                            book.filename(), book.category),
                                        content_type_id=ContentType.objects.get(model__exact='book').id,
                                        object_id=book.id,
                                        object_repr=request.user.username,
                                        action_flag=4
                                        )

     except Book.DoesNotExist:
          return JsonResponse({'error':True,'msg':'Book not found'})
render(request,'book/books-list.html',context={'books_list':books_list})

您还可以在管理器本身添加日志记录

class BookManager(models.Manager):
    def delete(self):
        # you logging as mentioned above
        super(BookManager).delete()
class Book(models.Model):
    .....
    ....
    objects = BookManager()

推荐阅读