user324747
user324747

Reputation: 273

Django Match IP in database

I am trying to check if the user's IP is in a model object I have. I added my IP in the database, but am not getting my code to respond accordingly:

views.py

def view(request):
    try:
        ip = request.META['HTTP_X_FORWARDED_FOR']
    except:
        ip = request.META['REMOTE_ADDR']

    ignored_ips = IgnoredIP.objects.all()
    if str(ip) in ignored_ips:
        Ignore = True

Models.py

from django.db import models

class IgnoredIP(models.Model):
    ip = models.IPAddressField()

    def __unicode__(self):
    return self.ip

Upvotes: 0

Views: 336

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599590

You're comparing a string against a list of model instances. It will never match.

You don't want to fetch the entire table of IgnoredIPs anyway just to check a single one. Rather, query for that precise value:

if IgnoredIP.objects.filter(ip=ip).exists():

Upvotes: 2

Related Questions