Django项目搭建笔记

参考:https://www.cnblogs.com/liqu/p/9308966.html

工具

PyCharm
没错就是这么简单!`

创建项目

File-New Project
选择Django,选择项目目录,和Python版本
完事
在这里插入图片描述

项目说明

  1. 项目结构
文件结构说明
--DjangoTest(项目名)
----__init__.py			
----settings.py			//主配置文件
----urls.py				//路由文件,相当于controller
----wsgi.py				//网络通信接口
--templates				//模板目录
--manage.py				//项目管理主程序
  1. 创建APP
    在Terminal中执行

    python manage.py startapp testapp
    

    生成testapp文件夹
    在这里插入图片描述

  2. 写个路由试试
    在 生成的testapp目录下的views.py文件里,添加一个函数

    # Create your views here.
    from django.http import HttpResponse
    
    def hello(request):
        return HttpResponse("Hello World!")
    

    之后,在DjangoTest目录下的urls.py里面,添加一个路由

    from django.contrib import admin
    from django.urls import path
    from testapp import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        #新添加的
        path('hello',views.hello)
    ]
    

    启动项目之后,访问localhost:8000/hello路径,即可看到HelloWorld!
    在这里插入图片描述

  3. 返回模板页面
    新建一个路由

    def helloPage(request):
        context={}
        context['hello']='Hello!This is context'
        return render(request,'hello.html',context)
    
    path('helloPage',views.helloPage)
    

    templates目录下新建一个hello.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Test</title>
    </head>
    <body>
        <p>{{ hello }}</p>
    
    </body>
    </html>
    

    访问localhost:8000/helloPage显示
    在这里插入图片描述

  4. 配置静态资源路径
    当需要使用静态资源,如js,css等时,创建static目录,并需要在settings.py中配置配置静态资源路径

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.2/howto/static-files/
    	
    STATIC_URL = '/static/'
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, "static"),
        'Djago/static/',
    ]
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值