如何将用户 IP 地址从 ListView 发送到模板?

How to send user IP address from ListView to template?

我正在使用 django.I 开发一个博客项目,需要将用户 IP 地址从我的 class PostListView(继承 ListView class)发送到模板,我该怎么做这 ??????

这是我的signals.py

from django.contrib.auth.signals import user_logged_in
from django.contrib.auth.models import User
from django.dispatch import receiver

@receiver(user_logged_in,sender=User)
def login_success(sender,request,user,**kwargs):
    print("____________________________")
    print("log in")
    ip = request.META.get('REMOTE_ADDR')
    print(" ip: ",ip)
    request.session['ip'] = ip

我想我需要在 views.py 中进行更改,所以我需要 add/change...

views.py

class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html' 
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 5
    
    def get_context_data(self,request, **kwargs):
        ip = request.session.get('ip',0)
        context = super().get_context_data(**kwargs)
        context['ip'] = ip
        return context

模板

<p>ip{{ip}}</p>

我从 views.py

中收到一个错误

get_context_data 而不是 request 调用的,它是视图的一个属性。因此,您可以使用 self.request:

访问请求
class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html' 
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 5
    
    #                   no request ↓
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['ip'] = <strong>self.request.session.get('ip', 0)</strong>
        return context