Django开发速成

    • Ubuntu下开发环境的搭建
      • 1 virtualenv安装和配置
      • 2 MySQL的安装和使用
    • Django基础知识回顾
      • 1 Django目录介绍
      • 2 配置表单页面
    • 需求分析和Model设计
      • 1 创建Django-APP
      • 2 扩展Django默认表达到自定义userprofile表的目的
      • 3 user modelspy设计
        • 31 users modelspy
        • 32 courses modelspy
        • 33 organization modelspy 设计
        • 34 operation modelspy
        • 35 数据库生成以及apps目录建立
    • 通过xadmin快速搭建后台管理系统

1. Ubuntu下开发环境的搭建

1.1 virtualenv安装和配置

安装virtualenv

liang@l:~$ pip install virtualenv

创建一个虚拟环境

liang@l:~$ virtualenv testvir
New python executable in /home/liang/testvir/bin/python
Installing setuptools, pip, wheel...done.

进入该虚拟环境、退出

liang@l:~/testvir$ cd scripts
liang@l:~/testvir$ cd bin
liang@l:~/testvir/bin$ source activate、
(testvir) liang@l:~/testvir/bin$ deactivate

安装virtualenvwrapper并使用

liang@l:~$ sudo pip install virtualenvwrapper 

在用户根目录下(即/home/[username])有文件.bashrc,到该文件的末尾处,屏蔽 if~fi 间的内容,在最后添加下面内容:

if [ -f /usr/local/bin/virtualenvwrapper.sh ]; then
    export WORKON_HOME=$HOME/.virtualenvs
    source /usr/local/bin/virtualenvwrapper.sh
fi

image
保存后退出。 执行命令:

liang@l:~$ source .bashrc

1.2 MySQL的安装和使用

安装MySQL

sudo apt-get install mysql-server
sudo apt-get install mysql-client
sudo apt-get install libmysqlclient-dev

测试MySQL

sudo netstat -tap | grep mysql

修改MySQL密码

  1. 打开/etc/mysql/debian.cnf文件,在这个文件中有系统默认给我们分配的用户名和密码,通过这个密码就可以直接对mysql进行操作了。但是一般这个密码都比较怪,很长很长。

  2. 当进入mysql之后修改mysql的密码:这个方法比较好,具体的操作如下用命令:

mysql> set global validate_password_policy=0;
mysql> set password for 'root'@'localhost' = password('123ooo456');

当修改之后就可应正常对mysql进行操作了。

登录MySQL

liang@l:~$ mysql -u root -p
Enter password:

2. Django基础知识回顾

2.1 Django目录介绍

创建一个新的APP Tools>Run manage.py Task

manage.py@djangostart > startapp message

分别创建static文件夹用于存放静态文件,log文件夹用于存放日志文件,media文件夹用于存放用户上传文件,template文件夹用于存放HTML文件

2.2 配置表单页面

编辑settings文件数据库内容

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME':"testdjango",
        'USER':"root",
        'PASSWORD':"123ooo456",
        'HOST':"127.0.0.1"
    }
}#数据库连接
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users'#新创建的APP需要注册
]
AUTH_USER_MODEL = "users.UserProfile"#修改默认用户画像

安装MySQL的Python工具

liang@l:~/Downloads/navicat120_mysql_cs_x64$ pip install mysql-python

打开manage.py Task,创建数据库表

manage.py@djangostart > makemigratioon
manage.py@djangostart > migrate

3. 需求分析和Model设计

3.1 创建Django-APP

创建MxOnline Django项目

3.2 扩展Django默认表达到自定义userprofile表的目的

创建users APP,==所有网站的设计应该都从users开始设计==

用makemigration和migrate命令创建默认数据库,自动创建的用户表为==auth_user==

编写models.py文件,==注意一定要写utf-8格式==

#_*_ encoding:utf-8 _*_
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models here.


class UserProfile(AbstractUser):
    nick_name = models.CharField(max_length=50, verbose_name=u"昵称", default="")
    birthday = models.DateField(verbose_name=u"生日", null=True, blank=True)
    gender = models.CharField(max_length=5, choices=(("male",u"男"), ("female",u"女")), default="female")
    address = models.CharField(max_length=100, default=u"")
    mobile = models.CharField(max_length=11, null=True, blank=True)
    image = models.ImageField(upload_to="image/%Y/%m",default=u"image/default.png", max_length=100)

    class Meta:
        verbose_name = "用户信息"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.username、

执行过程中出现此问题,需要返回虚拟环境安装==Pillow库==

ERRORS:
users.UserProfile.image: (fields.E210) Cannot use ImageField because Pillow is not installed.
    HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow".

运行后提示

ValueError: Dependency on app with no migrations: users

此时要做一下users的migration,打开manage.py

manage.py@MxOnline > makemigrations users
bash -cl "/home/liang/.virtualenvs/mxonline/bin/python2.7 /home/liang/pycharm-2017.2.4/helpers/pycharm/django_manage.py makemigrations users /home/liang/PycharmProjects/MxOnline"
Migrations for 'users':

manage.py@MxOnline > migrate users
bash -cl "/home/liang/.virtualenvs/mxonline/bin/python2.7 /home/liang/pycharm-2017.2.4/helpers/pycharm/django_manage.py migrate users /home/liang/PycharmProjects/MxOnline"
Operations to perform:
  Apply all migrations: users
Running migrations:
  Rendering model states... DONE
  Applying users.0001_initial... OK
The following content types are stale and need to be deleted:

    auth | user

Any objects related to these content types by a foreign key will also
be deleted. Are you sure you want to delete these content types?
If you're unsure, answer 'no'.

    Type 'yes' to continue, or 'no' to cancel:  yes

Process finished with exit code 0

再次打开数据库的users_profile表,显示创建成功

3.3 user models.py设计

User models.py 和Courses models.py存在循环引用

解决循环import最常用的方法是分层设计:
1. django app设计
2. users models.py编写
3. courses models.py编写
4. organization models.py编写
5. operaion models.py编写(最上层)

3.3.1 users models.py

  1. 自定义usersprofile覆盖默认user表
  2. EmailVerifyRecord-邮箱验证码(保存到数据库中)
  3. PageBanner-轮播图

编辑Django文件时,应注意遵循PEP8规范的==导入顺序==

#_*_ encoding:utf-8 _*_
#第一个区域,放Python自带的包
from __future__ import unicode_literals
from datetime import datetime

#第二个区域,放第三方的包
from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models her第三个区域,自己定义的model

class UserProfile(AbstractUser):
    nick_name = models.CharField(max_length=50, verbose_name=u"昵称", default="")
    birthday = models.DateField(verbose_name=u"生日", null=True, blank=True)
    gender = models.CharField(max_length=5, choices=(("male",u"男"), ("female",u"女")), default="female")
    address = models.CharField(max_length=100, default=u"")
    mobile = models.CharField(max_length=11, null=True, blank=True)
    image = models.ImageField(upload_to="image/%Y/%m",default=u"image/default.png", max_length=100)

    class Meta:
        verbose_name = "用户信息"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.username

class EmailVerifyRecord(models.Model):
    code = models.CharField(max_length=20, verbose_name=u"验证码")
    email = models.EmailField(max_length=50, verbose_name=u"邮箱")
    send_type = models.CharField(choices=(("register",u"注册"),("forget",u"找回密码")),max_length=10)
    send_time = models.DateTimeField(default=datetime.now)
    #now加括号的话会生成实际编译的时间,不加括号的话生成类实例化的时间

    class Meta:
        verbose_name = u"邮箱验证码"
        verbose_name_plural = verbose_name

class Banner(models.Model):
    title = models.CharField(max_length=100, verbose_name=u"标题")
    image = models.ImageField(upload_to="banner/%Y/%m",verbose_name=u"轮播图",max_length=100)
    #image在数据库当中存取的是图片的路径地址
    url = models.URLField(max_length=200, verbose_name=u"访问地址")
    index = models.IntegerField(default=100, verbose_name=u"顺序")
    add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")

    class Meta:#表的名字
        verbose_name = u"轮播图"
        verbose_name_plural = verbose_name

形成以下结构图:

3.3.2 courses models.py

设计内容:

  1. Course - 课程基本信息
  2. Lesson - 章节信息
  3. Video - 视频
  4. CourseResource - 课程资源

课程存在多层嵌套关系

graph LR
课程-->章节
章节-->视频

代码如下:

#_*_ encoding:utf-8 _*_
from __future__ import unicode_literals
from datetime import datetime

from django.db import models

# Create your models here.

class Course(models.Model):
    name = models.CharField(max_length=50, verbose_name=u"课程名")
    desc = models.CharField(max_length=300, verbose_name=u"课程描述")
    detail = models.TextField(verbose_name=u"课程详情")
    degree = models.CharField(choices=(("cj",u"初级"),("zj",u"中级"),("gj",u"高级")),max_length=2)
    learn_times = models.IntegerField(default=0, verbose_name=u"学习时长(分钟数)")
    students = models.IntegerField(default=0, verbose_name=u"学习人数")
    fav_nums = models.IntegerField(default=0, verbose_name=u"收藏人数")
    image = models.ImageField(upload_to="courses/%Y%m", verbose_name=u"封面数", max_length=100)
    click_nums = models.IntegerField(default=0, verbose_name=u"点击数")
    add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")

    class Meta:
        verbose_name = u"课程"
        verbose_name_plural = verbose_name


class Lesson(models.Model):
    course = models.ForeignKey(Course, verbose_name=u"课程")
    name = models.CharField(max_length=100, verbose_name=u"章节名")
    add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")

    class Meta:
        verbose_name = u"章节"
        verbose_name_plural = verbose_name


class Video(models.Model):
    lesson = models.ForeignKey(Lesson, verbose_name=u"章节")
    name = models.CharField(max_length=100, verbose_name=u"视频名")
    add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")

    class Meta:
        verbose_name = u"视频"
        verbose_name_plural = verbose_name


class CourseResource(models.Model):
    course = models.ForeignKey(Course, verbose_name=u"课程")
    name = models.CharField(max_length=100, verbose_name=u"视频名")
    download = models.FileField(upload_to="course/resource/%Y/%m", verbose_name=u"资源文件", max_length=100)
    add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")

    class Meta:
        verbose_name = u"课程资源"
        verbose_name_plural = verbose_name

3.3.3 organization models.py 设计

课程机构结构如下:
1. CourseOrg - 课程机构基本信息
2. Teacher - 教师基本信息
3. CityDictionary - 城市信息

#_*_ encoding:utf-8 _*_
from __future__ import unicode_literals
from datetime import datetime

from django.db import models

# Create your models here.

class CityDict(models.Model):
    name = models.CharField(max_length=20, verbose_name=u"城市")
    desc = models.CharField(max_length=200, verbose_name=u"描述")
    add_time = models.DateTimeField(default=datetime.now)

    class Meta:
        verbose_name =u"城市"
        verbose_name_plural = verbose_name


class CourseOrg(models.Model):
    name = models.CharField(max_length=50, verbose_name=u"机构名称")
    desc = models.TextField(verbose_name=u"机构描述")
    click_num = models.IntegerField(default=0, verbose_name=u"点击数")
    fav_nums = models.IntegerField(default=0, verbose_name=u"收藏数")
    image = models.ImageField(upload_to="org/%Y%m", verbose_name=u"封面数", max_length=100)
    address = models.CharField(max_length=150,verbose_name=u"机构地址")
    city = models.ForeignKey(CityDict, verbose_name=u"所在城市")
    add_time = models.DateTimeField(default=datetime.now)

    class Meta:
        verbose_name = u"课程机构"
        verbose_name_plural = verbose_name


class Teacher(models.Model):
    org = models.ForeignKey(CourseOrg, verbose_name=u"所属机构")
    name = models.CharField(max_length=50, verbose_name=u"教师名")
    work_year = models.IntegerField(default=0, verbose_name=u"工作年限")
    work_company = models.CharField(max_length=50, verbose_name=u"就职公司")
    work_position = models.CharField(max_length=50, verbose_name=u"公司职位")
    points = models.CharField(max_length=50, verbose_name=u"教学特点")
    click_num = models.IntegerField(default=0, verbose_name=u"点击数")
    fav_nums = models.IntegerField(default=0, verbose_name=u"收藏数")
    add_time = models.DateTimeField(default=datetime.now)

    class Meta:
        verbose_name = u"教师"
        verbose_name_plural = verbose_name

3.3.4 operation models.py

设计结构:
1. UserAsk - 用户咨询
2. CourseComments - 用户评论
3. UserFavorite - 用户收藏
4. UserMessage - 用户消息
5. UserCourse - 用户学习的课程
设计代码如下:

#_*_ encoding:utf-8 _*_
from __future__ import unicode_literals
from datetime import datetime

from django.db import models

from users.models import UserProfile
from courses.models import Course
# Create your models here.


class UserAsk(models.Model):
    name = models.CharField(max_length=20, verbose_name=u"姓名")
    mobile = models.CharField(max_length=11, verbose_name=u"手机")
    course_name = models.CharField(max_length=50, verbose_name=u"课程名")
    add_time = models.DateTimeField(default=datetime.now,verbose_name=u"添加时间")

    class Meta:
        verbose_name = u"用户咨询"
        verbose_name_plural = verbose_name


class CourseComments(models.Model):#课程评论
    user = models.ForeignKey(UserProfile, verbose_name=u"用户")
    course = models.ForeignKey(Course, verbose_name=u"课程")
    comments = models.CharField(max_length=200, verbose_name=u"评论")
    add_time =models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")

    class Meta:
        verbose_name = u"课程评论"
        verbose_name_plural = verbose_name


class UserFavorite(models.Model):
    user = models.ForeignKey(UserProfile, verbose_name=u"用户")
    fav_id = models.IntegerField(default=0, verbose_name=u"数据ID")
    fav_type = models.IntegerField(choices=((1,u"课程"),(2,u"课程机构"),(3,u"讲师")),default=1, verbose_name=u"收藏类型")
    add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")

    class Meta:
        verbose_name = u"用户收藏"
        verbose_name_plural = verbose_name


class UserMessage(models.Model):
    user = models.IntegerField(default=0, verbose_name=u"接收用户")
    message = models.CharField(max_length=500, verbose_name=u"消息内容")
    has_read = models.BooleanField(default=False, verbose_name=u"是否已读")
    add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")

    class Meta:
        verbose_name = u"用户消息"
        verbose_name_plural = verbose_name


class UserCourse(models.Model):
    user = models.ForeignKey(UserProfile, verbose_name=u"用户")
    course = models.ForeignKey(Course, verbose_name=u"课程")
    add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")

    class Meta:
        verbose_name = u"用户课程"
        verbose_name_plural = verbose_name

3.3.5 数据库生成以及apps目录建立

打开manage.py task

manage.py@MxOnline > makemigrations
bash -cl "/home/liang/.virtualenvs/mxonline/bin/python2.7 /home/liang/pycharm-2017.2.4/helpers/pycharm/django_manage.py makemigrations /home/liang/PycharmProjects/MxOnline"
Migrations for 'courses':
  0001_initial.py:
    - Create model Course
    - Create model CourseResource
    - Create model Lesson
    - Create model Video
Migrations for 'operation':
  0001_initial.py:
    - Create model CourseComments
    - Create model UserAsk
    - Create model UserCourse
    - Create model UserFavorite
    - Create model UserMessage
Migrations for 'users':
  0002_banner_emailverifyrecord.py:
    - Create model Banner
    - Create model EmailVerifyRecord
Migrations for 'organization':
  0001_initial.py:
    - Create model CityDict
    - Create model CourseOrg
    - Create model Teacher
Following files were affected 
 /home/liang/PycharmProjects/MxOnline/organization/migrations/0001_initial.py
/home/liang/PycharmProjects/MxOnline/courses/migrations/0001_initial.py
/home/liang/PycharmProjects/MxOnline/operation/migrations/0001_initial.py
/home/liang/PycharmProjects/MxOnline/users/migrations/0002_banner_emailverifyrecord.py
Process finished with exit code 0

此时每个app文件夹下会生成migrations文件夹

当app数量过多时,应该把他们单独放入一个文件夹便于管理

然后执行==右击apps文件夹 > Mark Directory as > Sources Root==,这样,在根目录下找不到的表可以在apps目录下继续寻找,但是这样仍然不够,在命令行下运行python manage.py runserver 时,仍然会报错找不到users

liang@l:~/PycharmProjects/MxOnline$ python manage.py runserver
Unhandled exception in thread started by <function wrapper at 0x7ff40c02cc80>
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    autoreload.raise_last_exception()
  File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 251, in raise_last_exception
    six.reraise(*_exception)
  File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 94, in create
    module = import_module(entry)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named users

此时要编辑MxOnline/settings.py文件,将根目录注册到settings文件中

import os
import sys

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,os.path.join(BASE_DIR,'apps'))

此时,用PyCharm Debug该项目,正常

停止运行,在命令行中运行该项目,正常

(mxonline) liang@l:~/PycharmProjects/MxOnline$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

November 28, 2017 - 14:25:53
Django version 1.9, using settings 'MxOnline.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

4. 通过xadmin快速搭建后台管理系统

后台管理系统的特点:
- 权限管理
- 少前段样式
- 快速开发

xadmin是Django中的一个杀手级后台管理系统


这篇博文是我和我的小师弟一起写的(其实就是我师弟写的。。。)
原文链接:https://note.youdao.com/share/?id=ffe840560636f0e36ecad8422f7a3f85&type=note#/


Welcome to my blog column: Dive into ML/DL!


这里写图片描述


I devote myself to dive into typical algorithms on machine learning and deep learning, especially the application in the area of computational personality. My research interests include computational personality, user portrait, online social network, computational society, and ML/DL. In fact you can find the internal connection between these concepts:


这里写图片描述


In this blog column, I will introduce some typical algorithms about machine learning and deep learning used in OSNs(Online Social Networks), which means we will include NLP, networks community, information diffusion,and individual recommendation system. Apparently, our ultimate target is to dive into user portrait , especially the issues on your personality analysis.


All essays are created by myself, and copyright will be reserved. You can use them for non-commercical intention and if you are so kind to donate me, you can scan the QR code below. All donation will be used to the library of charity for children in Lhasa.


赏金将用于拉萨儿童图书公益募捐
社会公益,听IT人的声音

手机扫一扫,即可:

附:《春天里,我们的拉萨儿童图书馆,需要大家的帮助

你可能感兴趣的:(python)