2011-11-28 77 views
0

我是Python和Django的新手。Django - 如何調用模塊?

我在此目錄結構中創建了一個名爲 「utils.py」 文件:

- MyProject 
    - MyApp 
     * __init__.py 
     * forms.py 
     * models.py 
     * utils.py 
     * views.py 

的 「utils.py」 有這裏面:

import unicodedata # Para usar na strip_accents 

# Para substituir occorrencias num dicionario 
def _strtr(text, dic): 
    """ Replace in 'text' all occurences of any key in the given 
    dictionary by its corresponding value. Returns the new tring.""" 
    # http://code.activestate.com/recipes/81330/ 
    # Create a regular expression from the dictionary keys 
    import re 
    regex = re.compile("(%s)" % "|".join(map(re.escape, dic.keys()))) 
    # For each match, look-up corresponding value in dictionary 
    return regex.sub(lambda mo: str(dic[mo.string[mo.start():mo.end()]]), text) 

# Para remover acentos de palavras acentuadas 
def _strip_accents(text, encoding='ASCII'): 
    return ''.join((c for c in unicodedata.normalize('NFD', unicode(text)) if unicodedata.category(c) != 'Mn')) 


def elapsed_time (seconds): 
    """ 
    Takes an amount of seconds and turns it into a human-readable amount of time. 
    Site: http://mganesh.blogspot.com/2009/02/python-human-readable-time-span-give.html 
    """ 
    suffixes=[' ano',' semana',' dia',' hora',' minuto', ' segundo'] 
    add_s=True 
    separator=', ' 

    # the formatted time string to be returned 
    time = [] 

    # the pieces of time to iterate over (days, hours, minutes, etc) 
    # - the first piece in each tuple is the suffix (d, h, w) 
    # - the second piece is the length in seconds (a day is 60s * 60m * 24h) 
    parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52), 
     (suffixes[1], 60 * 60 * 24 * 7), 
     (suffixes[2], 60 * 60 * 24), 
     (suffixes[3], 60 * 60), 
     (suffixes[4], 60), 
     (suffixes[5], 1)] 

    # for each time piece, grab the value and remaining seconds, and add it to 
    # the time string 
    for suffix, length in parts: 
    value = seconds/length 
    if value > 0: 
     seconds = seconds % length 
     time.append('%s%s' % (str(value), 
         (suffix, (suffix, suffix + 's')[value > 1])[add_s])) 
    if seconds < 1: 
     break 

    return separator.join(time) 

我怎麼能調用的函數在我的「models.py」中的「utils.py」裏面?我試圖導入這樣但它不工作...

from MyProject.MyApp import * 

我該如何做這項工作?

最好的問候,

回答

1

你需要你的import語句更改爲:

from MyProject.MyApp.utils import * 
+0

你不應該向新手推薦'import *'表單。最好從myproject.myapp中導入utils,並將所有內容都稱爲'utils.foo'。 –

0

你的一個問題是:

- MyProject 
    - MyApp 
     * __init__.py 
     * forms.py 
     * models.py 
     * utils.py 
     * views.py 

應該是:

- MyProject 
    - __init__.py 
    - MyApp 
     * __init__.py 
     * forms.py 
     * models.py 
     * utils.py 
     * views.py 

注意前tra __init__.py

第二個是德米特里指出的。