DA
DealiAxy
2021年12月18日

Python-Web-Django:第一个Web-App的构建

View视图渲染 编辑App目录下的views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def hello(request): return HttpResponse(Hello Django!) URL解析配置 编辑urls

未分类
1323
5 分钟阅读
更新于 12-18

View视图渲染

编辑App目录下的views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def hello(request):
    return HttpResponse("Hello Django!")

URL解析配置

编辑urls.py: 在urlpatterns里增加一个URL解析规则path('', views.hello)

from django.contrib import admin
from django.urls import path
from hello_app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.hello)
]

打开浏览器测试

图片准备加载中...

通过模板构建

上面使用 django.http.HttpResponse() 来输出 "Hello Django!"。该方式将数据与视图混合在一起,不符合 Django 的 MVC 思想。 接下来使用html模板来构建App。 在前面的文章里面,我们已经在settings.py里配置好了模板(templates)目录,现在,在templates目录下新建home.html文件。

编写模板文件:

{% block main %}
    <h1>
        {{ home }}
    </h1>
{% endblock main %}

views.py里定义

def home(request):
    context = {}
    context['home'] = "home"
    return render(request, 'home.html', context)

urls.py里做URL解析

前面说过了,不再重复

浏览器测试

图片准备加载中...

About

图片准备加载中...

了解更多有趣的操作请关注我的微信公众号:DealiAxy 每一篇文章都在我的博客有收录:blog.deali.cn