使用Django,我在models.py中创建了Book类和BookManager类。 BookManager类具有计算包含关键字的书名数量的方法。如何使用基于类的视图将书名计数显示到HTML文件?
我知道如何使用基于函数的视图,而不是基于ListView类的视图。
library(reticulate)
py_config()
python: /usr/bin/python
libpython: /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config/libpython2.7.dylib
pythonhome: /System/Library/Frameworks/Python.framework/Versions/2.7:/System/Library/Frameworks/Python.framework/Versions/2.7
version: 2.7.10 (default, Feb 22 2019, 21:17:52) [GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)]
numpy: /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy
numpy_version: 1.8.0
keyword: /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/keyword.py
python versions found:
/usr/bin/python
/usr/local/bin/python3
/Users/jordan/anaconda3/bin/python
#I try and switch to Python 3.7.2
use_python("/usr/local/bin/python3")
#I still receive the message that I am using Py 2.7
py_config()
python: /usr/bin/python
libpython: /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config/libpython2.7.dylib
pythonhome: /System/Library/Frameworks/Python.framework/Versions/2.7:/System/Library/Frameworks/Python.framework/Versions/2.7
version: 2.7.10 (default, Feb 22 2019, 21:17:52) [GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)]
numpy: /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy
numpy_version: 1.8.0
keyword: /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/keyword.py
python versions found:
/usr/bin/python
/usr/local/bin/python3
/Users/jordan/anaconda3/bin/python
#Before I run python I follow the instructions from Rstudio presentation
Sys.setenv(PATH = "$HOME/anaconda3/bin:$PATH")
reticulate::use_condaenv("test-env")
#Now in a PY script I import Numpy which works but I get an error when trying to import pandas.
import numpy as np
import pandas as pd
ImportError: No module named pandas
#Note here is my current path
(base) jordans-MacBook-Air:~ jordan$ echo $PATH
/Users/jordan/anaconda2/bin:/Users/jordan/anaconda3/condabin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
我想使用基于Classe的视图在HTML文件上显示书名计数。
答案 0 :(得分:1)
您可以通过覆盖get_context_data
方法将项目添加到基于类的视图的上下文中。
class BookViewPage(ListView):
model = Book
def get_context_data(self, **kwargs):
context = super(BookViewPage, self).get_context_data(**kwargs)
context['title_number'] = Book.objects.title_count('django')
return context
现在您可以在模板中使用{{ title_number }}
。
在视图中放入title_number = Book.objects.title_count('django')
无效,因为此代码在模块加载时运行,而不是在视图处理请求时运行。