【Python】Django学习1

 

按黑马程序员的美多商场作方向:

https://www.bilibili.com/video/BV1nf4y1k7G3

 

一、应用创建、注册处理、配置

Pycharm 创建Django项目:

 

自应用注册处理:

 

二、应用数据初始化

第一步:创建元数据初始化py脚本

python manage.py makemigrations

初始化的脚本会放在各个自应用的migrates目录中

 

第二步:执行初始化py脚本,把表结构信息同步到数据库中

sqlite不需要建库即可实现,mysql需要先把model源信息的库建好才可以同步

python manage.py migrate

  

三、站点配置:

 1、改成中文时区和语言编码

 

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

  

2、设置站点管理员账号

 必须要先通过初始化数据之后才能执行

python manage.py createsuperuser

  

更改密码:

 更改的密钥要求8位长度,且至少有字母和数字组成

python manage.py changepassword 用户名

  

3、配置自定义端口号:

 

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from django.core.management.commands.runserver import Command as RunserverCommand


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoProject.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    RunserverCommand.default_port = 9090
    main()

  

4、站点登陆:

http://127.0.0.1:9090/admin/

 

 

5、将模型信息注册到django-admin中:

 

 

刷新页面可以发现模型信息可以直接在admin中进行管理

 

6、URL视图配置

工程默认会绑上django-admin的url配置 

http://127.0.0.1:9090/admin/

我们可以在这里添加我们自己url配置,对应的,每个自应用也需要创建一个urls.py配置文件

 

内容填写,一个路由地址,对应视图的一个方法:

"""
URL configuration for DjangoProject project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from .views import index
urlpatterns = [
    path('index/', index)
]

 

views.py中的index方法,调用的是httpResponse进行返回:

from django.http import HttpResponse


# Create your views here.
def index(request):
    return HttpResponse("Hello, world. You're at the index page.")

访问页面进行测试:

http://127.0.0.1:9090/book_manager/index/

  

 

 

7、使用模版渲染处理

创建模版文件,templates为模版的路径根目录,也可以自己改成别的目录

 

 

用自应用名称区分开来,mustache语法来读取模版参数

 

更改index方法逻辑:

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


# Create your views here.
def index(request):
    # return HttpResponse("Hello, world. You're at the index page.")
    context = {'title': 'Django Book Manager'}
    return render(request, 'book_manager/index.html', context) 

刷新查看页面:

 

8、上线配置ALLOW_HOSTS和关闭Debug模式

 

Debug模式将会把报错信息直接打印在页面上

 关闭Debug模式后,仅简单输出内容

 

9、静态文件管理

静态文件默认配置位置(settings文件):

 

在Debug模式下可以直接访问:

 关闭Debug模式后不能访问:

 

解决方案见此博客:

https://blog.csdn.net/qq_41475058/article/details/105856148

 

1、设置STATIC_ROOT参数

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

# 静态资源url访问路径
STATIC_URL = 'static/'

# python manage.py collectstatic 收集后的资源目录位置
STATIC_ROOT = os.path.join(BASE_DIR, 'static_prod')

 

2、给静态目录追加url映射配置:

"""
URL configuration for DjangoProject project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.static import serve
from DjangoProject import settings

urlpatterns = [
    re_path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}, name='static'),
    path('admin/', admin.site.urls),
    path('book_manager/', include('book_manager.urls')),
    path('my_app/', include('my_app.urls')),
    path('my_app2/', include('my_app2.urls')),
]

 

3、执行collect命令,打包静态资源

python manage.py collectstatic

  

 

posted @ 2024-07-28 18:27  emdzz  阅读(24)  评论(0编辑  收藏  举报