Search code examples
pythondjangocounter

implementing a counter that counts requests with django


I'm just trying with Django, how can i implement a counter that stores the count of requests served on the database?

I want to count the GET requests, what should I do make it work?

my template,

<form action="/submit/" method="GET">
    <input type="text" name="q">
    <input type="submit" value="Submit">
</form>

my view

def result(request):
    name = request.GET['q']
    message = 'your name is %r ' % name
    return render(request, 'result.html', {'message': message})

I want to count the number of times i press the submit button. should I start a new app counter or there exist some other way to implement a counter?


Solution

  • This might be a little messed up but you should get the basic concept you get it from the session not the get methods model/.py the model that tracts your friend

    friend = models.ForeignKey("self", related_name="referral", null=True, blank=True) 
    

    view.py this is how many friends you have counted

    cool_obj = cool.objects.get(ref_id=ref_id)
    obj = cool.objects.filter(friend=cool_obj)
    count = cool_obj.referral.all().count()
    

    this how you get your stuff through the middleware

    def home(request):
    try:
        cool_id = request.session['cool_id_ref']
        obj = cool.objects.get(id=cool_id)
    except:
        obj = None 
    form = CoolJoin(request.POST or None)
    if form.is_valid():
        new_cool = form.save(commit=False)
        email = form.cleaned_data['email']
        new_cools, created = cool.objects.get_or_create(email=email)
        if created:
            new_cools.ref_id = get_ref_id()
            if not obj == None:
                new_cools.friend = obj
            new_cools.ip_adress = get_ip(request)
            new_cools.save()
    
        return HttpResponseRedirect("/%s" %(new_cools.ref_id))
    context = {"form": form}
    template = "home.html"
    return render(request, template, context)
    

    middleware/py.

    class ReferMiddleware():
    def process_request(self, request):
            ref_id = request.GET.get("ref")
            try:
                obj = cool.objects.get(ref_id = ref_id)
            except:
                obj = None   
            if obj:
                request.session['cool_id_ref'] = obj.id