Search code examples
djangoviewcounter

View counter using IP address in Django app


I am working on Django app and I want to know how many people use it, so I decided to add view counter on the page. I created view counter (watched some tutorial) but it doesn't work. I don't know where is a problem. Here is the code:

models.py:

class User(models.Model):
    user=models.TextField(default=None)
    def __str__(self):
        return self-user

admin.py:

admin.site.register(User)

There is a problem with views.py. It says that "return can be used only within a function". I know that but what can I do to make this work?

def get_ip(request):
    address=request.META.get('HTTP_X_FORWARDED_FOR')
    if address:
        ip=address.split(',')[-1].strip()
    else:
        ip=request.META.get('REMOTE_ADDR')
    return ip

    ip=get_ip(request)
    u=User(user=ip)
    print(ip)
    result=User.objects.filter(Q(user__icontains=ip))
    if len(result)==1:
        print("user exist")
    elif len(result)>1:
        print("user exist more...")
    else:
        u.save()
        print("user is unique")
    count=User.objects.all().count()
    print("total user is", count)
    return render(request, 'index.html', {'count':count})

index.html:

{% load static %}
<html>
  <head>
    <title>Hello World Django App</title>
  </head>
  <h1>Hello World!</h1>
  <div>Total visits: {{count}} </div>
</html>


Solution

  • Your error is glaring. You have two return statements that are not conditional in single function.

    Your error is:

    return ip
    

    Remove that.

    I noticed, you mean to make two different functions because you're erroneously calling your current function to return an ip.

    What you should make a view function and then call get_ip in it. Remove everything from ip=get_ip down. Put them in a get view function.

    The new function is what you should put in your urls file