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时如下

相关推荐
摸鱼的春哥14 小时前
把白领吓破防的2028预言,究竟讲了什么?
前端·javascript·后端
南 阳14 小时前
Python从入门到精通day37
数据库·python·oracle
@atweiwei14 小时前
rust所有权机制详解
开发语言·数据结构·后端·rust·内存·所有权
树獭叔叔14 小时前
05-从隐藏向量到文字:LM Head如何输出"下一个词"?
后端·aigc·openai
绝无仅有14 小时前
计算机网络核心面试知识深入解析
后端·面试·架构
树獭叔叔14 小时前
03-大模型的非线性变化:从MLP到MOE,大模型2/3的参数都在这里
后端·aigc·openai
开发者小天14 小时前
python安装 Matplotlib 库 安装 Seaborn 库
开发语言·python·matplotlib
with-the-flow14 小时前
从数学底层的底层原理来讲 random 的函数是怎么实现的
c语言·python·算法
iOS开发上架14 小时前
系统架构-进程管理
python·腾讯云
多恩Stone14 小时前
【3D-AICG 系列-15】Trellis 2 的 O-voxel Shape: Flexible Dual Grid 代码与论文对应
人工智能·python·算法·3d·aigc