简体   繁体   English

如何在Django的views.py和settings.py中为文件today.html添加路径

[英]How to add path for the file today.html in views.py and settings.py in django

I have a html file in my home directory named today.html 我的主目录中有一个html文件,名为Today.html。

I have to load that file on a click of a link using django. 我必须使用django单击链接来加载该文件。

How to add the file path in views.py and settings.py files. 如何在views.py和settings.py文件中添加文件路径。

You could add your home directory path to the TEMPLATE_DIRS setting in your project's settings.py file. 您可以将主目录路径添加到项目的settings.py文件中的TEMPLATE_DIRS设置中。 Then when you try to render the template in your view, Django will be able to find it. 然后,当您尝试在视图中呈现模板时,Django将能够找到它。

First of all you always have to keep your html files in template dir under django's project/root dir. 首先,您始终必须将html文件保存在django项目/根目录下的模板目录中。

Than you have to configure template path in settings.py such as 比您必须在settings.py中配置模板路径,例如

from unipath import Path
PROJECT_DIR = Path(__file__).ancestor(3) #ancestor value depends on number parent dir.

TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
PROJECT_DIR.child('templates')
)

now you can access that html file by interating into urls.py such as 现在您可以通过插入urls.py来访问该html文件,例如

from django.views.generic import TemplateView

 urlpatterns = patterns('',
        url(r'link_name_to_access^$', TemplateView.as_view(template_name="today.html")),
  )

Note: 注意:

Using TemplateView you don't need to write specific view to render the required html. 使用TemplateView,您无需编写特定的视图即可呈现所需的html。

First copy the file today.html into your projects template folder. 首先将文件today.html复制到您的项目模板文件夹中。

Add the path in settings.py file. 在settings.py文件中添加路径。 ie your project-path/your file-path(today.html). 即您的项目路径/您的文件路径(today.html)。

Then create a function to open today.html file in views.py. 然后创建一个函数以在views.py中打开today.html文件。

Now in urls.py file give the url. 现在在urls.py文件中提供url。

ie. 即。 url(r'^today/$', 'your project-path.views.today', name='today'), url(r'^ today / $','your project-path.views.today',name ='today'),

that's it 而已

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM