在Eclipse中創建Django項目


  在以前的分享中,我們是在命令行模式下創建Django項目的,那么,如何在IDE中使用Django呢?

  本文將介紹如何在Eclipse中創建Django項目。

  首先,新建Django項目mysite,如下圖:

注意上圖中的划紅線部分,應該選擇“Add project directory to the PYTHONPATH”,之后一直點next和finish即可,建好的mysite項目如下圖:

  在mysite模塊下,新建views.py,代碼如下:

 1 from django.http import HttpResponse
 2 
 3 def output(request):
 4     title = "<h1>When You Are Old</h1>"
 5     author = "<h2>William Butler Yeats</h2>"
 6     content = """
 7                  When you are old and grey and full of sleep,<br/>
 8                  And nodding by the fire, take down this book,<br/>
 9                  And slowly read, and dream of the soft look<br/>
10                  Your eyes had once, and of their shadows deep;<br/>
11                  How many loved your moments of glad grace,<br/>
12                  And loved your beauty with love false or true,<br/>
13                  But one man loved the pilgrim soul in you,<br/>
14                  And loved the sorrows of your changing face;<br/>
15                  And bending down beside the glowing bars,<br/>
16                  Murmur, a little sadly, how love fled<br/>
17                  And paced upon the mountains overhead<br/>
18                  And hid his face amid a crowd of stars.<br/>
19                """
20     return HttpResponse([title, author, content])

  在urls.py增加url路徑:

1 from django.conf.urls import include, url
2 from django.contrib import admin
3 
4 urlpatterns = [
5     url(r'^admin/', include(admin.site.urls)),
6     url(r'^$','mysite.views.output'),
7 ]

  最后,我們需要在manage.py中,修改代碼,將execute_from_command_line(sys.argv)命令改為自己做需要的命令,如下代碼:

 1 #!/usr/bin/env python
 2 import os
 3 import sys
 4 
 5 if __name__ == "__main__":
 6     os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
 7 
 8     from django.core.management import execute_from_command_line
 9 
10     execute_from_command_line(['manage.py','runserver','0.0.0.0:8000'])

保存,並運行,在Eclipse中運行結果如下:

  最后,我們在本地瀏覽器中輸入localhost:8000即可,顯示如下圖:
  這樣,我們就成功地在Eclipse中創建Django項目並順利運行了,簡單又方便,不需要再在命令行模式下去操作。
  那么,如何新建Django app呢?我們只需在原項目下,新建PyDev Package,這就是一個Django app.
  那么,又該如何實現python manage.py makemigrations和python mange.py migrate呢?和上面的操作一樣,我們只需要在manage.py新增代碼:
1 execute_from_command_line('manage.py','makemigrations')
2 execute_from_command_line('manage.py','migrate')
  本次分享到此結束,歡迎大家交流~~




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM