iT邦幫忙

0

Django views 內的路徑問題

我想利用抓取資料夾內所有檔案名稱的方式,讓url的設置可以簡化,但是在正式部屬時os.listdir()會抓不到路徑

def page_view(request,page=None): 
	import os
	path = 'templates/'
	dir_list=['dashboard','event','other']
	_dir ={}
	for d in dir_list:
		dirs = os.listdir(path+d)
		_dir.update(dict.fromkeys(dirs,d))
	temp = page+'.html'
	return render(request,_dir[temp]+'/'+temp)

我的settings內已經設定如下

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

於是我用os.getcwd(),發現抓到的路徑在'/'

def re_where(request):
	import os
	_dir = os.getcwd()
	return render(request,'print.html',{
		'var':_dir,
		})

我的環境是ububtu + apache2,請問該怎麼解決,或是有更好的做法?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
froce
iT邦大師 1 級 ‧ 2020-05-22 12:02:35

ㄜ...urls.py寫3行的東西,你這樣寫要多少行啊?
通常沒人會這麼用,因為:
1.同一類頁面用同一個template就行了。動態網頁不就是這樣?
2.靜態網頁沒啥人用django放,效能不會好,你直接apache/nginx設定就行。

真的要這麼用,我的code應該會是這樣:

def page_view(request,page=None): 
    dir_list=['dashboard','event','other']
    if page in dir_list:
        return render(request, "{}.html".format(page))
    else:
        from django.http import Http404
        return Http404

settings.py

把你建的app加到 INSTALLED_APPS
johnywalk iT邦新手 5 級 ‧ 2020-05-22 13:20:11 檢舉

這是我templates的目錄
│ index.html

├─dashboard
│ option_oi.html
│ pattern_select.html
│ quote_sort.html
│ stock_volatility.html
│ stock_volumn.html
│ strong_long_pattern.html
│ strong_short_select.html
│ technical_indicators.html
│ txf_toptrader.html

├─event
│ calendar.html
│ holiday.html
│ research.html

├─html
│ footer.html
│ header.html

└─other
about_us.html
learning_map.html
我實在不知道views以外的寫法@@,請問單用url要怎麼寫呢?

froce iT邦大師 1 級 ‧ 2020-05-22 15:17:42 檢舉

views不是給你做路由的,就這樣...
如果你的資料夾裡面都是靜態的,請設定web server的路由。
如果你的網頁都是動態的,那本來就是一條路由對應一個view。

johnywalk iT邦新手 5 級 ‧ 2020-05-27 11:43:44 檢舉

謝謝回復~

我要發表回答

立即登入回答