1. 第一步:定义视图函数(可以伪代码)
1.1 在自己定义的apps中的views.py文件中进行定义
HttpResponse 源码
class HttpResponseBase:
"""
An HTTP response base class with dictionary-accessed headers.
This class doesn't handle content. It should not be used directly.
Use the HttpResponse and StreamingHttpResponse subclasses instead.
"""
status_code = 200
def __init__(self, content_type=None, status=None, reason=None, charset=None):
# _headers is a mapping of the lowercase name to the original case of
# the header (required for working with legacy systems) and the header
# value. Both the name of the header and its value are ASCII strings.
self._headers = {}
self._closable_objects = []
# This parameter is set by the handler. It's necessary to preserve the
# historical behavior of request_finished.
self._handler_class = None
self.cookies = SimpleCookie()
self.closed = False
if status is not None:
try:
self.status_code = int(status)
except (ValueError, TypeError):
raise TypeError('HTTP status code must be an integer.')
if not 100 <= self.status_code <= 599:
raise ValueError('HTTP status code must be an integer from 100 to 599.')
self._reason_phrase = reason
self._charset = charset
if content_type is None:
content_type = '%s; charset=%s' % (settings.DEFAULT_CONTENT_TYPE,
self.charset)
self['Content-Type'] = content_type
代码
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
# 视图函数
def index(param):
# 视图函数必须有返回值,必须有参数
print('----->这是获取的参数')
print(param)
print('----->这是处理主页index的视图函数')
return HttpResponse('ok')
1.2 视图函数定义注意点
1.视图函数需要至少一个参数,用来接收框架自定传递过来的request对象
2.视图函数需要一个返回值,必须返回的是HttpResponse对象
2. 第二步:定义路径,家那个路径和视图函数进行映射
2.1 路径匹配
2.1.1 第一种配置
2.2 第一种路径定义方式(视图方式)
在项目所在的同名文件夹下的urls中进行定义
from django.contrib import admin
from django.urls import path
from collect import views
urlpatterns = [
# path(路径,视图映射)
path('admin/', admin.site.urls),
# 1.版本使用url 2.x版本用path
# django.urls.path()普通路径 and / or django.urls.re_path()带正则的路径
path('index/',views.index)# 只要开始写映射关系浏览器就会报错
]
2.3 第二种路径定义方式(基于视图类)
2.4 第三种路径定义方式
2.2.4.1 分别在每一个自定义APP中定义urls.py文件
from django.urls import path,include
urlpatterns = [
]
2.4.2 在初始urls.py中,分别加上二级路由匹配文件
from django.contrib import admin
from django.urls import path,include
from collect import views
from users import views
urlpatterns = [
# path(路径,视图映射)
path('admin/', admin.site.urls),
# 1.版本使用url 2.x版本用path
# django.urls.path()普通路径 and / or django.urls.re_path()带正则的路径
# path('index/',views.index)# 只要开始写映射关系浏览器就会报错
path('collect/',include('collect.urls')),
path('users/',include('users.urls'))
2.4.3 在二级urls.py 文件中进行真正的路由和视图映射关系
from django.urls import path, include
from collect.views import index
# 分别定义collect这个app相关的路径
urlpatterns = [
path('index/',index)
]
3. 定义模板
3.1 第一步:在项目下创建模板文件夹,文件夹名字固定为templates
3.2 第二步:将模板文件进行注册
在settings.py文件中,进行配置
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],# 使用os进行路径拼接,注意不要粘贴绝对路径
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
3.3 在视图中进行使用,注意返回的函数是render
render源码
def render(request, template_name, context=None, content_type=None, status=None, using=None):
"""
Return a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
content = loader.render_to_string(template_name, context, request, using=using)
return HttpResponse(content, content_type, status)
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
# 视图函数
def index(param):
print('----->这是获取的参数')
print(param)
print('----->这是处理主页index的视图函数')
# 视图函数必须有返回值,必须有参数
# return HttpResponse('ok')
return render(request=param,template_name='collect/index.html')