Django框架课-写第一个页面

写第一个页面

git仓库-此版本代码地址

文件结构

image

进入到/acapp/game

新建urls.pytemplages/

touch urls.py
mkdir templates

之后写项目基本上就只在urls.pymodels.pyviews.pytemplages/里面写

templates存的是网页模板
如果后面业务量扩大,就把models.py改成文件夹,文件夹中再分类存放。

models 存放数据结构,数据库表、class(user,)、
views 存放函数
urls 存放路由(给了一个路由,调用哪个函数)
templates 存放网页模板html

第一个页面

我的目标是浏览器输入url:http://47.94.107.232:8000/game就跳转到我的gameapp首页(index页)

这个路由应该包含在urls.py中,当我输入这个url,urls.py解析这个path,执行views.py中相对应的函数返回字符串(html)

接下来在/game下,写urls.pyviews.py

views.py:

from django.http import HttpResponse

# views.py的功能就是传进来一个链接+参数,返回一个字符串

def index(request):
    return HttpResponse("我的第一个网页!!!")

urls.py:

from django.urls import path
from game.views import index #导入game/views.py中的index函数

urlpatterns = [
    path('',index,name="index") # path解析''这个路由,调用index函数
]

当然,还要把/game/urls.py中的路由include进总的路由表/acapp/urls.py
acapp/urls.py:

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('game/',include('game.urls')),
    path('admin/', admin.site.urls),
]

接下来浏览器访问urlhttp://47.94.107.232:8000/game/,可以发现,由内容了!

整个过程是这样的:

用户输入url->url传到acapp/urls.py->include到game.urls->调用view.py中的index函数->index函数返回字符串(html)

image


稍作修改:
views.py

def index(request):
    line1 = '<h1 style="text-align: center">术士之战</h1>'
    line2 = '<img src="https://www.mvprpg.com/upload/article2019-08/20190826102629_528.jpg" width=400>'
    return HttpResponse(line1+line2)

效果:
image

posted @ 2022-11-17 21:39  r涤生  阅读(40)  评论(0编辑  收藏  举报