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'})

再次運行,解決!

 

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