3

So I'm trying to get the template path in my view. Is there a dynamic way of doing this because at the moment I am hard-coding the path.

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

Templates Path

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

View

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()
lolz
  • 225
  • 2
  • 6
  • 18
  • try this https://stackoverflow.com/questions/3092865/django-view-load-template-from-calling-apps-dir-first – badiya Jul 04 '17 at 02:24
  • 1
    The beauty of Django is that it will autodiscover your template files based on the folder structure - `app/templates/app/project.html`. – joshlsullivan Jul 04 '17 at 02:50

3 Answers3

4

If you load the template....

mytemplate = loader.get_template('myapp/templatename.html')

What you get in return is a Template object.

One of the members of this object is the origin attribute, which itself has an attribute called 'name'

templatepath = mytemplate.origin.name

This is the full path to the template file that the template loader discovered.

Mars
  • 195
  • 1
  • 10
2

Try this. get template location from your project setting file.

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()
ammy
  • 618
  • 1
  • 5
  • 13
0

It's best to store your templates within your app. for example, if your app called polls your template should be at polls/templates/polls/

You can read more about it here: https://docs.djangoproject.com/en/1.11/intro/tutorial03/

Rani
  • 6,424
  • 1
  • 23
  • 31