2017-04-11 69 views
1

Django的1.11名稱 '集團' 沒有定義

的Python 3.6.1

我的項目將被部署,我將不得不預先設置一些東西。也就是說,我需要幾個用戶組。

所以,我做了一個目錄下的「部署」,並把它放在旁邊,項目的目錄。

當一個新的數據庫將被創建的,我只是執行:

python manage.py shell < ../deployment/initialize_project.py 

此代碼作品:

from django.contrib.auth.models import Group 

Group.objects.create(name="commentator") # Can only comment. 

Group.objects.create(name="contributor") # Can add, change and delete 
             # objects. 

此代碼

from django.contrib.auth.models import Group 


def initialize_roles(): 

    Group.objects.create(name="commentator") # line 6 

    Group.objects.create(name="contributor") 


initialize_roles() # line 12 

回溯:

Traceback (most recent call last): 
    File "manage.py", line 22, in <module> 
    execute_from_command_line(sys.argv) 
    File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line 
    utility.execute() 
    File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute 
    self.fetch_command(subcommand).run_from_argv(self.argv) 
    File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv 
    self.execute(*args, **cmd_options) 
    File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute 
    output = self.handle(*args, **options) 
    File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 101, in handle 
    exec(sys.stdin.read()) 
    File "<string>", line 12, in <module> 
    File "<string>", line 6, in initialize_roles 
NameError: name 'Group' is not defined 

我標記上面的代碼線6和12(內聯的評論)。

我試圖用pdb.set_trace(),但同樣的錯誤出現。就好像pdb沒有定義一樣。

我也儘量不喂manage.py上initialize_project.py,只是運行python manage.py殼和換行的代碼行。它工作完美。

你能在這裏給我一個踢嗎?

後來添加

這工作:

def initialize_roles(): 
    from django.contrib.auth.models import Group 
    Group.objects.create(name="commentator") # Can only comment. 

    Group.objects.create(name="contributor") # Can add, change and delete 
              # objects. 

initialize_roles() 
+1

您編輯過的行中顯然會出現一些問題。你有沒有重新定義組內的功能? –

+0

該函數內部沒有重定義。我會盡我所能地說 - 這些線條正如我在這裏給他們的。我只是複製它們。在整個文件中,除了該函數的評論之外沒有別的。 – Michael

+0

有趣!當在python manage.py shell中手動複製粘貼代碼時,這會起作用嗎? Imean'initialize_roles()'不起作用的樣式 – rrmerugu

回答

0

除非有更多的你在做什麼,這種感覺像什麼fixtures是爲了解決。如果還有更多內容,您可以添加custom data migrations作爲初始設置過程的一部分。這將避免擔心何時可以使用模型。

+0

湯姆,問題不在於燈具。這是一個python程序的奇怪行爲,不是嗎? – Michael