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

相关推荐
YJlio6 小时前
1.7 通过 Sysinternals Live 在线运行工具:不下载也能用的“云端工具箱”
c语言·网络·python·数码相机·ios·django·iphone
l1t6 小时前
在wsl的python 3.14.3容器中使用databend包
开发语言·数据库·python·databend
青云计划7 小时前
知光项目知文发布模块
java·后端·spring·mybatis
Victor3567 小时前
MongoDB(9)什么是MongoDB的副本集(Replica Set)?
后端
Victor3567 小时前
MongoDB(8)什么是聚合(Aggregation)?
后端
山塘小鱼儿7 小时前
本地Ollama+Agent+LangGraph+LangSmith运行
python·langchain·ollama·langgraph·langsimth
码说AI8 小时前
python快速绘制走势图对比曲线
开发语言·python
wait_luky8 小时前
python作业3
开发语言·python
yeyeye1118 小时前
Spring Cloud Data Flow 简介
后端·spring·spring cloud