weixin_33699914 2017-10-31 01:17 采纳率: 0%
浏览 945

Django:页面刷新

Here's the view that updates the timestamp of a model in database whenever it's called,

def data(request):
    new = Data.objects.filter(user=request.user)
    new.update(timestamp=timezone.now())
    return HttpResponse('')

This view is related to this URL,

url(r'^go/$', views.data, name='data')

Everything is fine, but how can I call this view & update the database without refreshing the page?

  • 写回答

2条回答 默认 最新

  • weixin_33709590 2017-10-31 03:04
    关注

    This is a great question as its something that may not seem as logical in django as say node or js based server and client interactions. Let me give a generic response then go more detailed.

    Django is a web server. It has some newer functionality that allows it to more easily interact with javascript than it could in the past, but it is normally used in conjunction with a javascript framework. I'll normally build a django app w/ django-rest-framework and reactjs. So my workflow is normally to build the datamodel, serve up the page with compiled js as a static asset, and have those two communicate via a rest-api stood up with DRF.

    Specifically to your question, you can simply have your django model communicate with the server via ajax posting to endpoint in your app. An example of a jquery/ajax post is available at this link. The only other thing you will want to look into is supporting csrf which Django discusses in the docs.

    Let me know if this helps. If it does but requires specific snippets, let me know.

    评论

报告相同问题?