Django(三)url和返回
location 最后一个文件夹名就是project名,我用了Django_Plan。
Application 是自动加入的APP名字,我用了Plan
编辑Django_Plan\Django_Plan\urls.py
from django.contrib import admin
from django.urls import path
from Plan import views
urlpatterns = [
path('admin/', admin.site.urls),
path('plan', views.plan) #此行为增加的
]
编辑Django_Plan\Plan\views.py
from django.shortcuts import render from django.shortcuts import HttpResponse #此行增加 # Create your views here. def plan(request): #此函数增加 return HttpResponse('hello')
好了,我们增加了一个url解析,解析到plan函数,进行http返回给浏览器。
试一下,浏览器http://localhost:8000/plan,会看到hello。用的是HttpResponse函数。
平时访问的页面那么多内容,我们不能都写在HttpResponse中呀。
我们用模板吧。
建立一个hello.html文件放在Django_Plan\templates\hello.html
内容为:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello</title> </head> <body> <h1>hello</h1> </body> </html>
编辑Django_Plan\Plan\views.py
from django.shortcuts import render from django.shortcuts import HttpResponse #此行增加 # Create your views here. def plan(request): #此函数增加 return render(request,'hello.html')
检查Django_Plan\Django_Plan\settings.py(难道我用最新的django2.0,pycharm就不自动创建了?)
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], #注意此行 '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', ], }, }, ]
好了,这下浏览器返回的就是我们的模板文件内容,h1格式的hello
我们还需要动态生成页面,继续编辑hello.html,给输出的hello加上两个大括号
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello</title> </head> <body> <h1>{{ hello }}</h1> </body> </html>
编辑Django_Plan\Plan\views.py
from django.shortcuts import render from django.shortcuts import HttpResponse #此行增加 # Create your views here. def plan(request): #此函数增加 return render(request,'hello.html',{'hello':'hello jack'})
这里就是在render的参数中又加了一个字典,把hello换成hello jack,再返回给客户端浏览器。
打开页面试试吧。
作者:上官飞鸿
出处:https://www.cnblogs.com/jackadam/p/8094093.html
版权:本作品采用「知识共享-署名-非商业性-禁止演绎(CC-BY-NC-ND)」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!