2017-07-04 81 views
0

所以我试图在我的视图中获取模板路径。有没有这样做的动态方式,因为目前我正在对路径进行硬编码。如何在视图中获取模板路径django

html = 'C:/Users/user/Desktop/project/src/templates/project.html' 

模板路径

TEMPLATES = [ 
    'DIRS': [os.path.join(BASE_DIR, "templates")], 
] 

查看

html = 'C:/Users/user/Desktop/project/src/templates/project.html' 
open_html = open(html, 'r') 
soup = BeautifulSoup(open_html, "html5lib") 
image = soup.find('img', {'name':'image_url'}) 
img_url = image.get('src') 
open_html.close() 
+0

试试这个https://stackoverflow.com/questions/3092865/django-view-load-template-from-calling-apps-dir-first – badiya

+1

的Django的妙处在于,它会自动发现你的模板文件基于文件夹结构 - “app/templates/app/project.html”。 – joshlsullivan

回答

1

试试这个。从项目设置文件中获取模板位置。

from your_project_name.settings import BASE_DIR 

path = os.path.join(BASE_DIR+'templates/', 'project.html') 
open_html = open(path, 'r') 
soup = BeautifulSoup(open_html, "html5lib") 
image = soup.find('img', {'name':'image_url'}) 
img_url = image.get('src') 
open_html.close() 
+0

很高兴能帮到你!如果我的答案有帮助,不要忘记回答是有用的(上)。谢谢 – ammy