在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')
  本次分享到此结束,欢迎大家交流~~



原文地址:https://www.cnblogs.com/jclian91/p/8084546.html