Django项目实践不定时更新

1、搭建环境

      • 安装python3
      • 安装/升级pip
      • 安装django

        pycharm页面操作&终端命令

2、创建项目

      • Pycharm 页面操作
      • 终端命令
      • django-admin.py startproject project-name
        
        python manage.py startapp app-name

3、配置数据库

      • 本机安装mysql
      • 更改项目配置文件settings
      • DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': 'hf',  # 要连接的数据库,连接前需要创建好
                'USER': 'root',  # 连接数据库的用户名
                'PASSWORD': 'YLs$PMv9TC!KJFx=',  # 连接数据库的密码
                'HOST': '127.0.0.1',  # 连接主机,默认本机
                'PORT': 3306,  # 端口 默认3306
            }
        }
      • 用pymysql代替默认的MySQLdb 连接MySQL数据库,settings同级__init__文件
      • importpymysql
        pymysql.install_as_MySQLdb()
      • 在app下面的models.py文件夹中定义一个类继承 models.Model
      • from django.db import models
        
        #Create your model shere.
        
        class hf(models.Model):
            name=models.CharField(max_length=20)
      • 迁移数据库
      • python3 manage.py makemigrations
        python3 manage.py migrate
      • 可能遇到的问题

问题一:  File "/Users/icourt/Desktop/hf/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 36, in <module>

    raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)

django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

解决办法:跳转进上面路径文件注释掉版本判断

 

问题二:  File "/Users/icourt/Desktop/hf/venv/lib/python3.7/site-packages/django/db/backends/mysql/operations.py", line 146, in last_executed_query

    query = query.decode(errors='replace')

AttributeError: 'str' object has no attribute 'decode'

解决办法:跳转上面文件路径将decode更换为encode

      • 数据迁移完成
      • 查看数据库

4、配置静态文件

      •  在app目录下创建static目录,将静态文件和相关文件夹放到此目录下,如your_project/static/img等
      •  
      • 2. 确保settings.py中的INSTALLED_APPS中包含django.contrib.staticfiles
      • 3. 设置settings.py中的STATIC_URL的值为“/static/”
    • 4. 在模版中使用{{ STATIC_URL }}作为静态文件路径前缀。比如纯在图片文件your_project/static/img/logo.png,那么应用代码为<img src=”{{ STATIC_URL }}img/logo.png”>
    • 5. 渲染模版的Context对象需要换成RequestContext,否则模版中无法引用到STATIC_URL对应的值。

猜你喜欢

转载自www.cnblogs.com/feizisy/p/11737436.html