美文网首页
Hello Django

Hello Django

作者: 葛木瓜 | 来源:发表于2018-04-26 00:10 被阅读0次

    主题

    Django学习笔记之输出Hello Django

    方法一

    调用HttpResponse类向浏览器返回‘Hello Django’字符串

    实现:

    1. 准备工作(cmd.exe)
    # 创建一个Django项目
    >> django-admin startproject helloDj
    >> cd helloDj/helloDj/ # 进入helloDj/helloDj
    # 创建django视图文件,控制前段显示内容
    >> touch views.py 
    
    1. 配置url(urls.py)
    from django.contrib import admin
    from django.urls import path
    from . import views # 导入views模块
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('index/', views.hello), # 配置inde路由
    ]
    
    1. 定义index属性(views.py)
    from django.http import HttpResponse
    
    def hello(requeset):
        return HttpResponse('Hello Django !')
    
    1. 运行(cmd.exe)
    >> python manage.py runserver
    Performing system checks...
    System check identified no issues (0 silenced).
    You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
    Run 'python manage.py migrate' to apply them.
    April 25, 2018 - 22:53:31
    Django version 2.0.4, using settings 'helloDj.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CTRL-BREAK.
    
    1. 结果,ok!


      浏览器截图

    方法二

    使用HTML模板
    在helloDj/目录下创建templates/index.html文件

    文件路径
    1. index.html
    <html>
    <h1>Hello World !</h1>
    </html>
    
    1. views.py
    from django.shortcuts import render
    def hello(request):
        return render(request, "hello.html")
    
    1. urls.py保持不变
    2. 配置setting.py
    ...
    'DIRS': [BASE_DIR+"/templates", ], # 很重要,否则报TemplateDoesNotExist
    ...   
    
    1. 结果,ok!


      浏览器截图

    相关文章

      网友评论

          本文标题:Hello Django

          本文链接:https://www.haomeiwen.com/subject/calelftx.html