Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to send user IP address from ListView to template?

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….

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading