django中URL配置和视图渲染

前提:

使用django-admin startproject XXX创建了一个django项目【项目目录为project】

复制代码
django-admin startproject project

一:控制器配置

在项目的根目录创建一个Controller目录,后续所有的控制器方法都放在此目录下

这里我们在Controller目录下创建一个index.py文件

复制代码
# -*- coding: utf-8 -*-
 
from django.http import HttpResponse
from django.shortcuts import render_to_response
 
# 表单(用于渲染页面)
def index(request):
    return render_to_response('index/index.html')

二:视图配置

在项目的根目录创建一个VIew目录,后续所有的视图文件都放在此目录下,并且需要修改配置文件project/settings.py文件中的视图目录地址

复制代码
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR+"/View",],  #配置视图文件根目录
        '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',
            ],
        },
    },
]

根据上面的控制器我们在View目录下创建一个index目录并在index目录下创建一个index.html文件

复制代码
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>test</title>
</head>
<body>
	<div>
		测试视图渲染
	</div>
</body>
</html>

三:URL配置

修改路由配置文件project/urls.py文件中的路由配置

复制代码
from django.contrib import admin
from django.urls import path
from Controller import index

urlpatterns = [
    path('', index.index),
]

四:访问测试

这些运行服务命令

复制代码
python manage.py runserver 0.0.0.0:8000

这时候浏览器访问127.0.0.1:8000时如下

相关推荐
DanCheng-studio5 分钟前
网安毕业设计课题思路
python·毕业设计·毕设
Code_流苏11 分钟前
Python星球日记 - 第20天:数据分析入门
python·数据分析·数据可视化·数据清洗·pandas库
毕小宝23 分钟前
Python 使用 copy_from 完成批量插入postgre数据库脚本分享
python
Hesse27 分钟前
希尔排序:Python语言实现
python·算法
love530love33 分钟前
PyCharm Community社区版链接WSL虚拟环境
ide·python·pycharm
船长@Quant34 分钟前
VectorBT量化入门系列:第一章 VectorBT基础与环境搭建
python·量化策略·sklearn·ta-lib·量化回测·vectorbt
Ekreke43 分钟前
Linux下网络管理常用工具
后端
洛卡卡了43 分钟前
Go + Gin 优化动态定时任务系统:互斥控制、异常捕获与任务热更新
后端·go
hello早上好43 分钟前
3-Zookeeper基础应用和实战
后端·架构
惜鸟1 小时前
Elasticsearch文档标签检索方案设计
后端·elasticsearch