开发者

how to limit one django view method to work in just one period?

Model question has a view_counts field to count the how many times one question viewed.

and thre is a click to bind the method

def count_views(request, question_id):
    quest开发者_如何学运维ion = Question.objects.get(pk=question_id)

    if request.is_ajax():
        question.views_count = question.views_count + 1
        question.save()  
    else:
        url = '/error/show_error/4'
        return HttpResponseRedirect(url)  

    count = question.views_count

    json = simplejson.dumps(count)

    return HttpResponse(json, mimetype='application/json')


    $('.question a').click(function () {
        pk = $(this).attr('pk');
        $.get("/question/count_views/" + pk, function(data) {
            location.href='/question/show_question/' + pk;
        });   
    });  

<div class='question'>{{ forloop.counter }}. [{{ question.country }}] <a pk={{ question.pk }}>{{ question.question }}</a></div>

but if the client with the same ip click the same question in 5 minutes, the views_count will not be increased

how to realize this?

It is just like in stackoverflow, you cannot edit one comment in 5 seconds.


Take my advise with a grain of salt, I'm rather new to django and python myself, and I haven't tested this, but I would go about implementing this like so:

Create a new model:

class LastViewed(models.Model):
    ip = models.IPAddressField()
    last_view = models.DateField()
    question = models.ForeignKey(Question)

    class Meta:
        unique_together = ('ip', 'question',)

Then before count_views increments the value, it should query the LastViewed table to check the last access time:

question = Question.objects.get(pk=question_id)
request_ip = request.META['REMOTE_ADDR']
last = LastViewed.objects.get(ip=request_ip)

if request.is_ajax() and (last.last_view - datetime.datetime.now() < datetime.timedelta(minutes=5)):
    question.views_count = question.views_count + 1
    question.save()
else:
    # etc

I hope that helps give you a general idea of how to go about it, I left out the code to actually add/update new entries to the LastViewed table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜