第11章節-Python3.5-Django的Model使用10

阿啦卜發表於2018-07-21
app:
        migrations     資料修改表結構
        admin          Django為我們提供的後臺管理
        apps           配置當前app
        models         ORM,寫指定的類  通過命令可以建立資料庫結構
        tests          單元測試
        views          業務程式碼
  • 接下來在

    image.png
  • 修改models.py 檔案:
from django.db import models

# Create your models here.


class UserType(models.Model):
    name = models.CharField(max_length=32)


class UserInfo(models.Model):

    username = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)
    email = models.CharField(max_length=32)
    user_type = models.ForeignKey(UserType)
  • 然後在

    image.png
  • 修改settings.py 檔案:
# Application definition

INSTALLED_APPS = [
    `django.contrib.admin`,
    `django.contrib.auth`,
    `django.contrib.contenttypes`,
    `django.contrib.sessions`,
    `django.contrib.messages`,
    `django.contrib.staticfiles`,
    `cmdb`,
]
image.png
  • 然後在Terminal 執行以下命令:
    (python manage.py makemigrations)
    (python manage.py migrate)
(python3) C:UsersAdministratorPycharmProjectss14django>python manage.py makemigrations
Migrations for `cmdb`:
  cmdbmigrations 001_initial.py:
    - Create model UserInfo
    - Create model UserType
    - Add field user_type to userinfo

(python3) C:UsersAdministratorPycharmProjectss14django>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, cmdb, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK

  Applying contenttypes.0002_remove_content_type_nam
e... OK
  Applying auth.0002_alter_permission_name_max_lengt
h... OK
  Applying auth.0003_alter_user_email_max_length...
OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying cmdb.0001_initial... OK
  Applying sessions.0001_initial... OK

(python3) C:UsersAdministratorPycharmProjectss14django>

  • 如下圖:

  • 接下來在:

    image.png
  • 在admin.py 修改程式碼如下(建立後臺管理):

from django.contrib import admin

from cmdb import models
# Register your models here.

admin.site.register(models.UserInfo)
admin.site.register(models.UserType)

在在Terminal 執行以下命令:

image.png
  • 建立超級管理員(python manage.py createsuperuser)
(python3) C:UsersAdministratorPycharmProjectss14
django>python manage.py createsuperuser
Username (leave blank to use `administrator`): alex
Email address: 123@qq.com

Password:  asdfzxcv
Password (again):asdfzxcv

  • 然後執行

    image.png
image.png


相關文章