简体   繁体   English

如何在Django中从views.py重复调用函数?

[英]How can I repeatedly call a function from a views.py in Django?

How can I repeatedly call a function from a views.py in Django? 如何在Django中从views.py重复调用函数?

urls.py urls.py

urlpatterns = [
    url(r'^$', views.index),
    url(r'^report/(?P<extension>\d+)/$', views.report),
]

views.py views.py

def report(request, extension):

    """
        I will do some logic here. I need the extension variable for 
        database purposes.
      EX: 
        my_array = Report.objects.fetching_reports(extension='3')
    """

    return render(request, 'report.html’)

If you notice in extension, I passed in 3. The idea is that each extension will have their own data. 如果您在扩展名中注意到,我传入了3。这个想法是每个扩展名都有自己的数据。 However, I want them to render on the same html template. 但是,我希望它们在相同的html模板上呈现。 I will begin rendering from extension 1, up to 12 then goes back to 1. Let's say extension 4 is missing, it will be redirected to extension 5.These extension will come from my database. 我将从扩展1开始渲染,直到12再回到1。假设扩展4丢失了,它将被重定向到扩展5。这些扩展将来自我的数据库。

Example:

…/report/1/
…/report/2/
…/report/3/    ## will skip 4 if not available 
…/report/5/
…/report/6/    ## and so on..

Each extension will render the same HMTL template. 每个扩展将呈现相同的HMTL模板。 Right now, I can successfully render these reports if I type the URL patter directly to the browser. 现在,如果直接在浏览器中键入URL模式,则可以成功呈现这些报告。 Is there a way to call report( ) continuously, let's say every 15 seconds? 有没有办法连续调用report(),比如说每15秒调用一次? Or should I have a different approach to this? 还是我应该采用其他方法?

Thank you very much for reading. 非常感谢您的阅读。

def report(request, extension):

    try:
        my_array = Report.objects.fetching_reports(extension=extension)
    except Report.DoesNotExist:
        my_array = None

    extension +=1

    if my_array = None:
        return HttpResponseRedirect(reverse('your_project_name':'your_app_name', kwargs = {'extension':extension}))
    else:
        return render(request, 'report.html', {'extension':extension})

that will skip to the next object if 4 doesn't exist, if you wanna skip after 15 seconds you can do a JavaScript redirecting to the next page and using extension var 如果不存在4,它将跳至下一个对象。如果您想在15秒后跳过,则可以执行JavaScript重定向到下一页并使用扩展名var

For each report, pass a next url to the template and use javascript to reload. 对于每个报告,将next URL传递到模板,然后使用javascript重新加载。

<script>
  function nextReport() { window.location.href = "{{ next }}"; }
  setTimeout(nextReport, 15000);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM