预期结果:
当用户访问 www.myapp.com/dashboard 时,Django应render
仪表板。同时,AJAX将(定期)调用视图getAccountInfo
,该视图通过模型AccountInformation
从PostgreSQL数据库查询数据。然后,该视图将返回最新数据,并且AJAX / JS将相应地更新DOM(保持在相同的页面/ URL)。
什么让我感到头晕:
考虑到Django MVT
架构,我只是不了解如何实现Ajax。
基本上每个URL都映射到一个视图。因此,一旦我访问/dashboard
,它就会调用视图render_Dashboard
。但是,当我现在将Ajax URL映射到该视图并将DB查询逻辑包含到同一视图中时,它将再次呈现整个站点,这将创建一个无限循环。因此,我必须将Ajax URL映射到第二个视图才能实现?但是此视图没有URL,因为我只想将/dashboard
作为URL供用户访问? 那么如何在该架构中实现第二个视图?
到目前为止我所拥有的:
仪表板应用程序内的views.py:
from Dashboard.models import AccountInformation
def getAccountInfo():
account_information = serializers.serialize('json', AccountInformation.objects.all())
print(account_information)
return HttpResponse()
getAccountInfo()
项目根目录内的views.py:
from django.shortcuts import render
def render_Dashboard(request, template="Dashboard_app.html"):
return render(request, template)
项目根目录内的urls.py:
urlpatterns = [
path('Dashboard/', views.render_Dashboard, name='Dashboard')
]
ajax部分:
var set_delay = 1000, // 1000ms = 1 second
callout = function () {
$.ajax('getAccountInfo/', {
method: 'GET',
async: "True",
dataType: "json",
success: function(response){
var accountInfo = response;
profit = response[0].fields[0].account_profit
print(profit)
$("#runningPL").html(profit)
}
})
.done(function (response) {
// update the page
})
.always(function () {
setTimeout(callout, set_delay);
});
};
// initial call
callout();
跟踪:
TypeError at /Dashboard/getAccountInfo/
getAccountInfo() takes 0 positional arguments but 1 was given
Request Method: GET
Request URL: http://127.0.0.1:8000/Dashboard/getAccountInfo/
Django Version: 3.0
Exception Type: TypeError
Exception Value:
getAccountInfo() takes 0 positional arguments but 1 was given
Exception Location: C:\Users\Jonas\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py in _get_response, line 113
Python Executable: C:\Users\Jonas\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.0
Python Path:
['C:\\Users\\Jonas\\Desktop\\Dashex',
'C:\\Users\\Jonas\\Desktop\\Dashex',
'C:\\Users\\Jonas\\Desktop\\Dashex',
'C:\\Users\\Jonas\\Desktop\\Dashex\\Dashex',
'C:\\Users\\Jonas\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\Jonas\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\Jonas\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\Jonas\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\Jonas\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
Server time: Wed, 4 Dec 2019 18:39:23 +0000
..当我将self
作为arg放入view函数时,它告诉我self
未定义。如果随后将视图包装到一个类中,则无法将该类导入到urls.py
中。.