首页 > 解决方案 > 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:

enter image description here

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'),
]

标签: djangoeclipseglobal-variablesunused-variables

解决方案


推荐阅读