django不同app同名html文件冲突问题

创建Templates时,会在每个Application下都创建一个Templates文件,然后在Templates文件下创建html文件。

错误示例:

1、有两个app,创建了相同的html文件,路径如下:

app1/templates/index.html

app2/templates/index.html

2、在根目录下settings.py文件中按照如下顺序加入app

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app1',
    'app2'
]

3、满足1和2的情况后,在两个app中views.py使用render调用index.html,如下

def index(request):
    return render(request, 'index.html', {'app1': 'app1'})
def index(request):
    return render(request, 'index.html', {'app2': 'app2'})

运行后发现,在app2的路径下,返回的结果永远是  app1,没有找到app2

 

注意,这是因为

django查找templates时,会按照INSTALLED_APPS中的添加顺序查找Templates;

如果不同APP下Templates目录中的 同名.html 文件会造成冲突!!!

 

解决Templates冲突方法:

1、在APP的Templates目录下创建以APP名为名称的目录;

2、将html文件放入新创建的目录下;

路径如下:

app1/templates/app1/index.html

app2/templates/app2/index.html

然后在两个app中views.py使用render调用index.html,如下

def index(request):
    return render(request, 'app1/index.html', {'app1': 'app1'})
def index(request):
    return render(request, 'app2/index.html', {'app2': 'app2'})

再次运行,解决!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章