在以前的分享中,我们是在命令行模式下创建Django项目的,那么,如何在IDE中使用Django呢?
本文将介绍如何在Eclipse中创建Django项目。
首先,新建Django项目mysite,如下图:
注意上图中的划红线部分,应该选择“Add project directory to the PYTHONPATH”,之后一直点next和finish即可,建好的mysite项目如下图:
在mysite模块下,新建views.py,代码如下:
from django.http import HttpResponse
def output(request):
title = "<h1>When You Are Old</h1>"
author = "<h2>William Butler Yeats</h2>"
content = """
When you are old and grey and full of sleep,<br/>
And nodding by the fire, take down this book,<br/>
And slowly read, and dream of the soft look<br/>
Your eyes had once, and of their shadows deep;<br/>
How many loved your moments of glad grace,<br/>
And loved your beauty with love false or true,<br/>
But one man loved the pilgrim soul in you,<br/>
And loved the sorrows of your changing face;<br/>
And bending down beside the glowing bars,<br/>
Murmur, a little sadly, how love fled<br/>
And paced upon the mountains overhead<br/>
And hid his face amid a crowd of stars.<br/>
"""
return HttpResponse([title, author, content])
在urls.py增加url路径:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^/pre>,'mysite.views.output'),
]
最后,我们需要在manage.py中,修改代码,将execute_from_command_line(sys.argv)命令改为自己做需要的命令,如下代码:
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
from django.core.management import execute_from_command_line
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新增代码:
execute_from_command_line('manage.py','makemigrations')
execute_from_command_line('manage.py','migrate')</pre>
本次分享到此结束,欢迎大家交流~~