django - How to declare and use global variables in Django (with Eclipse)
问题描述
I'm developing an application that needs a global variable. Fortunately, it is working despite Eclipse complaining about the way I used the global variable. To use as an example in this question, I created an application (which works!) that uses a global variable as a page counter. Here is the code:
My __init__.py file:
counter = 0
My views.py
from AccessCounter import counter
from django.shortcuts import render
def conterf(request):
global counter
counter +=1
context = {
'counter' : counter,
}
return render(request, 'AccessCounter/index.html', context)
And Eclipse is complaining that I have a "Unsed import: counter" at line "from AccessCounter import counter", but if I remove this line, the counter does not work with this error:
name 'counter' is not defined
I don't think that the following information is relevant, but here they are...
My index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Access counter: {{ counter }}
</body>
</html>
and my url.py file:
from django.contrib import admin
from django.urls import path
from AccessCounter import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.conterf, name='counter'),
]
解决方案
推荐阅读
- ruby-on-rails - 具有可覆盖树路径 slug 的 FriendlyID
- python-3.x - 如何从 matplotlib 获取轮廓处理程序?
- php - 无法使用 sqlserver 连接到数据库?
- flutter - 如何在 Flutter 的画布上的路径内绘制图案?
- ansible - Ansible - 环境变量剧本
- python - Flask - 更改现有数据库中的列类型
- swift - 复选框不能在 swift 中单独工作。我怎样才能让它分开?
- azure - 创建 Azure 管道时出现 ResourcePurchaseValidationFailed 错误
- c - C++ 表达式必须有一个常量值。(我在 Visual Studio 2019 中用 C 语言编写代码)
- javascript - 数组中每个项目的打印选项