第一个 django helloworld视图函数

manage.py:一个命令行工具,通过它可以调用Django shell和数据库等。键入python manage.py -h,查看它的相关功能。

init.py:让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。这是一个空文件,一般你不需要修改它。

settings.py:项目的默认设置,包括数据库信息,调试标志以及其他一些工作的变量。

urls.py:django项目的URL设置。 可视其为你的django网站的目录, 负责把URL模式映射到应用程序。

wsgi.py: 服务器网关接口(Python Web Server Gateway Interface),web服务器和web服务程序或者框架之间的一种简单而通用的接口。

运行python manage.py runserver出现错误:
ImportError: No module named django.core.management
未指定python版本。
更改方法 python3 manage.py runserver

更改这个 Development Server 的主机地址或端口

默认情况下, runserver 命令在 8000 端口启动开发服务器,且仅监听本地连接。 要想要更改服务器端口的话,可将端口作为命令行参数传入:

python manage.py runserver 8080
通过指定一个 IP 地址,你可以告诉服务器–允许非本地连接访问。 如果你想和其他开发人员共享同一开发站点的话,该功能特别有用。 0.0.0.0 这个 IP 地址,告诉服务器去侦听任意的网络接口。

python manage.py runserver 0.0.0.0:8000
完成这些设置后,你本地网络中的其它计算机就可以在浏览器中访问你的 IP 地址了。比如: http://192.168.1.103:8000/ . (注意,你将需要校阅一下你的网络配置来决定你在本地网络中的IP 地址) Unix用户可以在命令提示符中输入ifconfig来获取以上信息。 使用Windows的用户,请尝试使用 ipconfig 命令。

新建views.py 写入:

from django.http import HttpResponse

def hello(request):
return HttpResponse(“Hello world”)

一个视图就是Python的一个函数。这个函数第一个参数的类型是HttpRequest;它返回一个HttpResponse实例。为了使一个Python的函数成为一个Django可识别的视图,它必须满足这两个条件。

第一个URLconf:
URLconf 就像是 Django 所支撑网站的目录。 它的本质是 URL 模式以及要为该 URL 模式调用的视图函数之间的映射表。 你就是以这种方式告诉 Django,对于这个 URL 调用这段代码,对于那个 URL 调用那段代码

在工程里新建views.py 写入如下代码:
from django.http import HttpResponse
def hello(request):
return HttpResponse(“Hello world”)
在urls.py里更改为如下代码:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
# Examples:
# url(r’^’, ‘mysite.views.home’, name=’home’),  
    # url(r’^blog/’, include(‘blog.urls’)),  
    url(r’^hello/
’, ‘mysite.views.hello’),
url(r’^admin/’, include(admin.site.urls)),
]

更改后 在终端运行python3 manage.py runserver 得到正确结果。
url为:http://127.0.0.1:8000/hello/

你可能感兴趣的:(django)