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

相关推荐
专注仿真4 分钟前
梯度提升类(XFBoost)算法详解与代码实例
开发语言·人工智能·python·算法·大模型训练·控制算法
外收内放16 分钟前
Python基础语法练习题(75)
开发语言·python·学习
IT_陈寒19 分钟前
JavaScript的this坑人实录,这次我真的记下来了
前端·人工智能·后端
starzy19901 小时前
Scala类和对象:从构造器到样例类的完整指南
开发语言·后端·scala
梦影_1 小时前
MySQL进阶教程(五)—— SQL调优(下)
android·大数据·数据库·后端·sql·mysql·database
考虑考虑1 小时前
mariadb数据库
数据库·后端·mariadb
黑十2 小时前
PyTorch 报 “no CUDA GPUs are available“ 怎么办?3 步排查
服务器·网络·人工智能·pytorch·python
明月_清风2 小时前
用自然语言操控真机:Google Artemis 移动端 AI Agent 上手与实践
人工智能·后端
怪我冷i2 小时前
Rust 的impl语法详解
开发语言·后端·rust
threelab2 小时前
开源图片去水印代码
python