水痕 2019-12-01
上一篇文章已经把基础环境搭建好了
D:\学习\python3.7.3\python manage.py startapp blog
修改 博客的 models.py
class Blog(models.Model): title = models.CharField(max_length=50)#这里要注意外键关联 如果 关联的类没有在之前没用定义 那么一定要加引号 这里采用一个博客对应一个博客类型 一一对应blog_type = models.ForeignKey(‘BlogType‘,on_delete=models.DO_NOTHING) content = models.TextField() author = models.ForeignKey(User,on_delete=models.DO_NOTHING) created_time = models.DateTimeField(auto_now_add=True) last_updated_time = models.DateTimeField(auto_now=True)def __str__(self):return "<Blog: %s>" %self.titleclass BlogType(models.Model): type_name=models.CharField(max_length=15)def __str__(self):return self.type_name
模板修改好了 还需要修改settings.py 文件
加入
import pymysql # 一定要添加这两行!通过pip install pymysql! pymysql.install_as_MySQLdb() DATABASES = { ‘default‘: { ‘ENGINE‘: ‘django.db.backends.mysql‘, ‘NAME‘: ‘mysite‘, ‘HOST‘: ‘123.2X7.XX9.194‘, ‘USER‘: ‘root‘, ‘PASSWORD‘: ‘XXX‘, ‘PORT‘: ‘3306‘, } } #修改 LANGUAGE_CODE = ‘zh-Hans‘ TIME_ZONE = ‘Asia/Shanghai‘ USE_I18N = True USE_L10N = True USE_TZ = True INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘blog‘,]
安装 pymysql 包
将改变应用于 数据库
>D:\学习\python3.7.3\python manage.py makemigrations
>D:\学习\python3.7.3\python manage.py migrate
创建超级admin用户
python manage.py createsuperuserr
最后 为了能在admin里面显示 需要admin.py里面注册一下
from .models import BlogType,Blog @admin.register(BlogType) class BlogTypeAdmin(admin.ModelAdmin): list_display = ("id", "type_name") @admin.register(Blog) class BlogAdmin(admin.ModelAdmin): list_display = ("title","blog_type","author","create_time","last_updated_time" ) # Register your models here. ##也可以 #admin.site.register(BlogType) 这样注册的确定是 全部都会显示在后台
启动项目发现报错
raise ImproperlyConfigured(‘mysqlclient 1.3.13 or newer is required; you have %s.‘ % Database.__version__)
修改配置文件 注释报错
继续启动还是报错
query = query.decode(errors=‘replace‘) AttributeError: ‘str‘ object has no attribute ‘decode‘
继续修改配置文件 把decode 修改为encode
登陆后