【问题标题】:basic template not loading in Django基本模板未在 Django 中加载
【发布时间】:2016-03-11 22:14:31
【问题描述】:

我对 Django 真的很陌生。问题是我无法加载由两个基本 html 文件组成的模板。 这是我的模板文件的位置:

/home/usman/Django 项目/django-black/luckdrum/templates/

这是我的视图函数:

from django.shortcuts import render
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
def hello_template(request):
    t=get_template('signup.html')

    return HttpResponse(t) 

这里是 url.py 文件:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/','blog.views.hello'),
    url(r'^signup.html/','blog.views.hello_template'),

]

我还在我的 settings.py 中添加了路径作为 TEMPLATE_DIRS。 服务器显示错误模板不存在。请帮帮我!

【问题讨论】:

    标签: python django templates django-templates


    【解决方案1】:

    将您的模板放入templates/<app_name>/<app_name>/templates/<app_name>/。 Django 会自动找到它们。

    Django 将在主模板文件夹templates/<app_name>/<app_name>/templates/<app_name>/ 之后查找。

    然后在你看来:

    from django.shortcuts import render
    
    def hello_template(request):
        return render(request, '<app_name>/signup.html')
    

    这是您的 Django 项目的外观(Django 建议编写可重用的应用程序):

    mysite/
        manage.py
        mysite/
            __init__.py
            settings.py
            urls.py
            wsgi.py
        polls/
            __init__.py
            admin.py
            migrations/
                __init__.py
                0001_initial.py
            models.py
            static/
                polls/
                    images/
                        background.gif
                    style.css
            templates/
                polls/
                    detail.html
                    index.html
                    results.html
            tests.py
            urls.py
            views.py
        templates/
            admin/
                base_site.html
    

    阅读 django 文档:Organise templatesHow to write reusable apps

    【讨论】:

    • 我已将我的模板文件夹移动到我的应用程序目录 ieblog 并使我的视图类似于 "t=get_template('/signup.html') 。它仍然给我同样的错误跨度>
    • 我更新了我的答案,使用 dajngo.shortcut 中的 render 而不是 get_template
    • @Lois 它有效,但如果我在 vews.py 中删除应用程序名称 如你所述,它将完美运行。
    • 请添加相关项目结构
    • 是的,它有效,但如果我给您的解决方案不起作用,那么您似乎没有按照 Django 的建议组织您的应用程序。我更新了我的答案,阅读它:)
    猜你喜欢
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2016-09-28
    • 2019-08-21
    相关资源
    最近更新 更多