Home > Mobile >  How to send user IP address from ListView to template?
How to send user IP address from ListView to template?

Time:11-13

i'm working on a blog project using django.I need to send User IP address from my class PostListView (which inheritance ListView class) to template, how can i do this ?????

This is my 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

I think i need to change in views.py, so what i need to 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

Template

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

I got a error from views.py

this is

CodePudding user response:

get_context_data is not called with the request, it is an attribute of the view. You thus can access the request with 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'] = self.request.session.get('ip', 0)
        return context
  • Related