Django学习1 hello world

用Django写第一个页面hello与hello xxx

首先创建Django项目

Django学习1 hello world_第1张图片
project.jpg

_init_.py初始化文件

settings.py 项目的设置/配置

urls.py路由配置文件(URL分发器)

urlpatterns = [

url(正则表达式, view函数, 参数, 别名, 前缀),

]

1:不带参数

urlpatterns = [

url(r'^hello/$',hello),

]

2:带参数

urlpatterns = [

url(r'^hello/$', hello, {'name':'Gudolf'}),

]

正则表达式

r是raw的简写,rawstring 意思是这个字符串中间的特殊字符不用转义。

比如表示‘\n’,可以这样:r'\n'

但是如果你不用原生字符 而是用字符串你得这样:‘\\n’

^为匹配输入字符串的开始位置。

$为匹配输入字符串的结束位置。


view.py视图

不带参数

from django.shortcuts import render

defhello(request,name):

context  = {}#创建字典

context['hello'] ='Hello'#为字典添加元素

returnrender(request,'hello.html',context)

带参数

from django.shortcuts import render

defhello(request,name):

context  = {}#创建字典

context['hello'] ='Hello '+name#为字典添加元素,name为传递的参数

returnrender(request,'hello.html',context)

这里用到了render方法

render(request, template_name, context=None, content_type=None, status=None, using=None)

Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments.

此方法的作用---结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象。

通俗的讲就是把context的内容, 加载进templates中定义的文件, 并通过浏览器渲染呈现.

参数讲解:

request: 是一个固定参数, 没什么好讲的。

template_name: templates 中定义的文件, 要注意路径名. 比如'templates\polls\index.html', 参数就要写‘polls\index.html’

context: 要传入文件中用于渲染呈现的数据, 默认是字典格式

content_type:生成的文档要使用的MIME 类型。默认为DEFAULT_CONTENT_TYPE 设置的值。

status: http的响应代码,默认是200.

using: 用于加载模板使用的模板引擎的名称。


hello.html

   

    Title

   

{{hello }}

运行project


Django学习1 hello world_第2张图片
project2.jpg

访问 :http://127.0.0.1:8000/hello/

urls.py详解

你可能感兴趣的:(Django学习1 hello world)