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

相关推荐
Albert Edison6 小时前
【Python】学生管理系统
开发语言·数据库·python
love530love8 小时前
【ComfyUI】解决 ModuleNotFoundError: No module named ‘inference_core_nodes‘ 问题
人工智能·windows·python·comfyui·inference-core
亚亚的学习和分享10 小时前
python基础语法----条件语句
python
山岚的运维笔记10 小时前
SQL Server笔记 -- 第73章:排序/对行进行排序
数据库·笔记·后端·sql·microsoft·sqlserver
苍何11 小时前
豆包还能这么玩?附 13 大隐藏玩法,效率起飞(建议收藏)
后端
苍何11 小时前
Kimi 版 OpenClaw 来了,5000+ Skills 随便用,确实给力!
后端
Zzz 小生11 小时前
LangChain Streaming-Overview:流式处理使用完全指南
人工智能·python·语言模型·langchain·github
yzx99101311 小时前
Python数据结构入门指南:从基础到实践
开发语言·数据结构·python
百锦再11 小时前
Jenkins 全面精通指南:从入门到脚本大师
运维·后端·python·servlet·django·flask·jenkins
FYKJ_201012 小时前
springboot大学校园论坛管理系统--附源码42669
java·javascript·spring boot·python·spark·django·php