Why is my Django view being hit twice with every page view?

杀马特。学长 韩版系。学妹 提交于 2019-12-10 14:57:51

问题


I can't seem to find the problem for the life of me. Very simply, I have a database object that I'm pulling from the database, incrementing it's "views" by one, and saving. My view display's the incremented value, but then my logs show that the value is incremented AGAIN.

g=Game.objects.filter(slug=slug).distinct()[0]
g.views += 1
g.save()

Here's my logs:

[Fri Oct 29 15:15:49 2010] [error] DEBUG:root:Updating plays
[Fri Oct 29 15:15:49 2010] [error] DEBUG:root:plays: 40
[Fri Oct 29 15:15:50 2010] [error] DEBUG:root:Updating plays
[Fri Oct 29 15:15:50 2010] [error] DEBUG:root:plays: 41

My view shows that it has 40 hits. This causes that my view increments by 2 every time I refresh:

[Fri Oct 29 15:20:19 2010] [error] DEBUG:root:Updating plays 
[Fri Oct 29 15:20:19 2010] [error] DEBUG:root:plays: 42
[Fri Oct 29 15:20:19 2010] [error] DEBUG:root:Updating plays
[Fri Oct 29 15:20:19 2010] [error] DEBUG:root:plays: 43

Any hints as to what this could be?

EDIT:

Here's my view. I simplified it to the core elements (and it still behaves oddly).

def game(request, slug=None):

    g=Game.objects.filter(slug=slug)[0]

    if g:
        comments=GameComment.objects.filter(item=g, parent__isnull=True)
        g.plays+=1
        g.save()
    else:
        comments=None

    return render_to_response('goto/goto_game.html', {'g': g, 'comments':comments, 'cCount':len(comments) if comments else 0, 'newCCount':0}, request=request)

回答1:


AH! Turns out it was a missing url and ajax issue. It wasn't the favicon, as that only hits the root, and not my specific view.

The problem came when I had an AJAX command like this:

$.post('{{url("_submitcomment")}}', data, function(data) { ...

and that 'url' could not reverse '_submitcomment' so returned an empty string. Calling

$.post(''); 

will hit your current URL and try to fetch everything!

(I'm using Jinja2, btw, so the url command probably looks different from them traditional Django template system.)

Thanks for the help and the tips!




回答2:


Can you verify the second request is not for "/favicon.ico" ?




回答3:


In my case, each view was called twice, because my base template contained incorrect icon link in the <head> tag. It might look like this:

<link rel="icon" href="#">

So, after the page is loaded the browser sends a request to the current page again, which causes the second view call.

Remove the wrong <link> tag, and it should work.



来源:https://stackoverflow.com/questions/4056024/why-is-my-django-view-being-hit-twice-with-every-page-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!