python学习

目录

[TOC]

判断字段值是否包含某个数字,如果是字符,建议用icontains

Entry.objects.filter(Q(id__contains='1') & Q(id__contains='2') & Q(id__contains='3'))

Entry.objects.filter(Q(id__contains=1) & Q(id__contains=2) & Q(id__contains=3))

Entry.objects.filter(reduce(Q(id__contains=x) for x in [1, 2, 3]))

管理员身份运行cmd配置虚拟环境

  1. mkvirtualenv youpinmodel
  2. pip install django==1.9.8
  3. 下载python的mysql驱动,进入到文件目录cd /d C:\Users\Administrator\Desktop
    pip install mysql(tab)
  4. 在虚拟环境youpinmodel中新建项目
  5. pip install pillow

根据项目需求设计app

  • users-用户管理
  • employee-考核对象管理
  • institution-制度管理
  • informationinput-考核信息录入

配置数据库连接

#数据库连接配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "youpin1",
        'USER':'root',
        'PASSWORD':'',
        'HOST':'127.0.0.1'
    }
}

新建users app

新建users app

startapp users

model配置

#载入utf8编码
# _*_ encoding:utf-8 _*_
#继承app
from django.contrib.auth.models import AbstractUser
#新建模型,CharField要定义max_length
class UserProfile(AbstractUser):
    nick_name = models.CharField(max_length=50, verbose_name=u"昵称", default="")
    birday = models.DateField(verbose_name=u"生日", null=True, blank=True)
    gender = models.CharField(max_length=6, choices=(("male",u"男"),("female","女")), default="female")
    image = models.ImageField(upload_to="image/%Y/%m",default=u"image/default.png", max_length=100)
    user_id = models.CharField(max_length=11, null=True, blank=True)

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

    def __unicode__(self):
        return self.username

将UserProfile注册到app中,并重载setting方法

此步前一定要restart一下,否则后面xadmin就要重新生成auth_user,或者注释掉下面一句重新生成下表

AUTH_USER_MODEL = "users.UserProfile"

生成user表

makemigrations users
migrate users

新建剩余app

考核对象表

class w_section(models.Model):
    w_sectionid = models.CharField(max_length=2, verbose_name=u"工段ID")
    name = models.CharField(max_length=50, verbose_name=u"工段名")

    class Meta:
        verbose_name = u"工段"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.name

class w_team(models.Model):
    w_teamid = models.CharField(max_length=4, verbose_name=u"车间班组ID",default=0)
    name = models.CharField(max_length=50, verbose_name=u"车间班组名")

    class Meta:
        verbose_name = u"车间班组"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.name


class w_employee(models.Model):
    w_employeeid = models.CharField(max_length=10, verbose_name=u"员工编号",default=0)
    name = models.CharField(max_length=50, verbose_name=u"员工姓名")
    w_sectionid = models.ForeignKey(w_section, verbose_name=u"所属工段")
    w_teamid = models.ForeignKey(w_team, verbose_name=u"所属车间班组")

    class Meta:
        verbose_name = u"员工信息管理"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.name

制度表

class inscategory(models.Model):
    categoryid = models.CharField(max_length=2, verbose_name=u"制度类别ID")
    category = models.CharField(max_length=50, verbose_name=u"制度类别")

    class Meta:
        verbose_name = u"制度分类"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.category

class institution(models.Model):
    categoryid = models.ForeignKey(inscategory, verbose_name=u"制度类别ID")
    institution = models.CharField(max_length=50, verbose_name=u"制度内容")
    institutionid = models.CharField(max_length=10, verbose_name=u"制度ID")
    score = models.CharField(max_length=2, verbose_name=u"加扣分")

    class Meta:
        verbose_name = u"制度"
        verbose_name_plural = verbose_name
    def __unicode__(self):
        return self.institutionid

考核信息录入,操作上面两张表

class informationinput(models.Model):
    "考核信息录入"
    user=models.ForeignKey(UserProfile,verbose_name=u"考核员")
    category=models.ForeignKey(institution,verbose_name="制度ID和加扣分")
    sketch=models.CharField(max_length=500,verbose_name=u"简述")
    w_employeeid = models.ForeignKey(w_employee, verbose_name=u"考核对象")
    add_time=models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")
    image = models.ImageField(upload_to="information/%y/%m", default=u"information/default.png", max_length=100)
    has_agree=models.BooleanField(default=False,verbose_name=u"是否审查通过")

    class Meta:
        verbose_name = u"考核信息"
        verbose_name_plural = verbose_name

将所有app放到apps文件夹下

import sys
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
python manage.py runserver 0.0.0.0:8000

后台管理配置

createsuperuser
LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False
#使用本地时间

安装xadmin

pip install xadmin
#注册app
    'xadmin',
    'crispy_forms',
#url注册
import xadmin
    url(r'^xadmin/', xadmin.site.urls),
#同步表
makemigrations
migrate
#移动xadmin到extra_apps中,并mark
sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))
pip uninstall xadmin
makemigrations xadmin
migrate xadmin

设置模板,注册其它app

# -*- coding: utf-8 -*-
__author__ = 'grl'
__date__ = '$DATE $TIME'
#制度app
import xadmin

from .models import inscategory,institution

class inscategoryAdmin(object):
    list_display = ['categoryid', 'category']
    search_fields = ['categoryid', 'category']
    list_filter = ['categoryid', 'category']

class institutionAdmin(object):
    list_display = ['categoryid', 'institution','institutionid','score']
    search_fields = ['categoryid', 'institution','institutionid','score']
    list_filter = ['categoryid', 'institution','institutionid','score']

xadmin.site.register(inscategory, inscategoryAdmin)
xadmin.site.register(institution, institutionAdmin)
#员工app
import xadmin

from .models import w_section,w_team,w_employee

class w_sectionAdmin(object):
    list_display = ['w_sectionid', 'name']
    search_fields = ['w_sectionid', 'name']
    list_filter = ['w_sectionid', 'name']

class w_teamAdmin(object):
    list_display = ['w_teamid', 'name']
    search_fields = ['w_teamid', 'name']
    list_filter = ['w_teamid', 'name']
    
class w_employeeAdmin(object):
    list_display = ['w_employeeid', 'name','w_sectionid','w_teamid']
    search_fields = ['w_employeeid', 'name','w_sectionid','w_teamid']
    list_filter = ['w_employeeid', 'name','w_sectionid','w_teamid']

xadmin.site.register(w_section, w_sectionAdmin)
xadmin.site.register(w_team, w_teamAdmin)
xadmin.site.register(w_employee, w_employeeAdmin)
#考核信息录入app
import xadmin

from .models import informationinput

class informationinputAdmin(object):
    list_display = ['user', 'category','sketch','w_employeeid','add_time','image','has_agree']
    search_fields = ['user', 'category','sketch','w_employeeid','add_time','image','has_agree']
    list_filter = ['user', 'category','sketch','w_employeeid','add_time','image','has_agree']

xadmin.site.register(informationinput, informationinputAdmin)
#用户adminx中配置全站基础
import xadmin
from xadmin import views

class BaseSetting(object):
    enable_themes = True
    use_bootswatch = True

class GlobalSettings(object):
    site_title = "信息后台管理系统"
    site_footer = ""


xadmin.site.register(views.BaseAdminView, BaseSetting)
xadmin.site.register(views.CommAdminView, GlobalSettings)
#apps.py中配置中文显示
# -*- coding: utf-8 -*-
    verbose_name = u"制度管理"
#_init_文件中配置
default_app_config = "institution.apps.InstitutionConfig"

问题总结

  1. 获取当前用户姓名:

重载save_models方法 直接在方法中通过self.request.user就可以获取到当前操作xadmin的用户了

  1. 外键过滤
def get_context(self):
   context = superCourseAdmin, self).get_context()
   if 'form' in context:
       context['form'].fields['course_org'].queryset = CourseOrg.objects.filter(is_main_stage=True)
   return context
#在adminx里面重载这个函数,在xadmin中可以直接配置外键过滤 比如course的teacher是外键 如果要通过teacher的name过滤 直接在filter中写 "teahcer__name"就行了, 注意是双下划线
  1. 设置mysql只能本地访问

配置mysql的bind-addr 只需要配置成127.0.0.1

获取用户名等

  1. 获取当前用户姓名:

重载save_models方法 直接在方法中通过self.request.user就可以获取到当前操作xadmin的用户了

  1. 外键过滤
def get_context(self):
   context = superCourseAdmin, self).get_context()
   if 'form' in context:
       context['form'].fields['course_org'].queryset = CourseOrg.objects.filter(is_main_stage=True)
   return context
#在adminx里面重载这个函数,在xadmin中可以直接配置外键过滤 比如course的teacher是外键 如果要通过teacher的name过滤 直接在filter中写 "teahcer__name"就行了, 注意是双下划线
  1. 设置mysql只能本地访问

配置mysql的bind-addr 只需要配置成127.0.0.1

管理员身份运行cmd配置虚拟环境

  1. mkvirtualenv youpinmodel
  2. pip install django==1.9.8
  3. 下载python的mysql驱动,进入到文件目录cd /d C:\Users\Administrator\Desktop
    pip install mysql(tab)
  4. 在虚拟环境youpinmodel中新建项目
  5. pip install pillow

根据项目需求设计app

  • users-用户管理
  • employee-考核对象管理
  • institution-制度管理
  • informationinput-考核信息录入

配置数据库连接

#数据库连接配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "youpin1",
        'USER':'root',
        'PASSWORD':'',
        'HOST':'127.0.0.1'
    }
}

新建users app

新建users app

startapp users

model配置

#载入utf8编码
# _*_ encoding:utf-8 _*_
#继承app
from django.contrib.auth.models import AbstractUser
#新建模型,CharField要定义max_length
class UserProfile(AbstractUser):
    nick_name = models.CharField(max_length=50, verbose_name=u"昵称", default="")
    birday = models.DateField(verbose_name=u"生日", null=True, blank=True)
    gender = models.CharField(max_length=6, choices=(("male",u"男"),("female","女")), default="female")
    image = models.ImageField(upload_to="image/%Y/%m",default=u"image/default.png", max_length=100)
    user_id = models.CharField(max_length=11, null=True, blank=True)

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

    def __unicode__(self):
        return self.username

将UserProfile注册到app中,并重载setting方法

此步前一定要restart一下,否则后面xadmin就要重新生成auth_user,或者注释掉下面一句重新生成下表

AUTH_USER_MODEL = "users.UserProfile"

生成user表

makemigrations users
migrate users

新建剩余app

考核对象表

class w_section(models.Model):
    w_sectionid = models.CharField(max_length=2, verbose_name=u"工段ID")
    name = models.CharField(max_length=50, verbose_name=u"工段名")

    class Meta:
        verbose_name = u"工段"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.name

class w_team(models.Model):
    w_teamid = models.CharField(max_length=4, verbose_name=u"车间班组ID",default=0)
    name = models.CharField(max_length=50, verbose_name=u"车间班组名")

    class Meta:
        verbose_name = u"车间班组"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.name


class w_employee(models.Model):
    w_employeeid = models.CharField(max_length=10, verbose_name=u"员工编号",default=0)
    name = models.CharField(max_length=50, verbose_name=u"员工姓名")
    w_sectionid = models.ForeignKey(w_section, verbose_name=u"所属工段")
    w_teamid = models.ForeignKey(w_team, verbose_name=u"所属车间班组")

    class Meta:
        verbose_name = u"员工信息管理"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.name

制度表

class inscategory(models.Model):
    categoryid = models.CharField(max_length=2, verbose_name=u"制度类别ID")
    category = models.CharField(max_length=50, verbose_name=u"制度类别")

    class Meta:
        verbose_name = u"制度分类"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.category

class institution(models.Model):
    categoryid = models.ForeignKey(inscategory, verbose_name=u"制度类别ID")
    institution = models.CharField(max_length=50, verbose_name=u"制度内容")
    institutionid = models.CharField(max_length=10, verbose_name=u"制度ID")
    score = models.CharField(max_length=2, verbose_name=u"加扣分")

    class Meta:
        verbose_name = u"制度"
        verbose_name_plural = verbose_name
    def __unicode__(self):
        return self.institutionid

考核信息录入,操作上面两张表

class informationinput(models.Model):
    "考核信息录入"
    user=models.ForeignKey(UserProfile,verbose_name=u"考核员")
    category=models.ForeignKey(institution,verbose_name="制度ID和加扣分")
    sketch=models.CharField(max_length=500,verbose_name=u"简述")
    w_employeeid = models.ForeignKey(w_employee, verbose_name=u"考核对象")
    add_time=models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")
    image = models.ImageField(upload_to="information/%y/%m", default=u"information/default.png", max_length=100)
    has_agree=models.BooleanField(default=False,verbose_name=u"是否审查通过")

    class Meta:
        verbose_name = u"考核信息"
        verbose_name_plural = verbose_name

将所有app放到apps文件夹下

import sys
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
python manage.py runserver 0.0.0.0:8000

后台管理配置

createsuperuser
LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False
#使用本地时间

安装xadmin

pip install xadmin
#注册app
    'xadmin',
    'crispy_forms',
#url注册
import xadmin
    url(r'^xadmin/', xadmin.site.urls),
#同步表
makemigrations
migrate
#移动xadmin到extra_apps中,并mark
sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))
pip uninstall xadmin
makemigrations xadmin
migrate xadmin

设置模板,注册其它app

# -*- coding: utf-8 -*-
__author__ = 'grl'
__date__ = '$DATE $TIME'
#制度app
import xadmin

from .models import inscategory,institution

class inscategoryAdmin(object):
    list_display = ['categoryid', 'category']
    search_fields = ['categoryid', 'category']
    list_filter = ['categoryid', 'category']

class institutionAdmin(object):
    list_display = ['categoryid', 'institution','institutionid','score']
    search_fields = ['categoryid', 'institution','institutionid','score']
    list_filter = ['categoryid', 'institution','institutionid','score']

xadmin.site.register(inscategory, inscategoryAdmin)
xadmin.site.register(institution, institutionAdmin)
#员工app
import xadmin

from .models import w_section,w_team,w_employee

class w_sectionAdmin(object):
    list_display = ['w_sectionid', 'name']
    search_fields = ['w_sectionid', 'name']
    list_filter = ['w_sectionid', 'name']

class w_teamAdmin(object):
    list_display = ['w_teamid', 'name']
    search_fields = ['w_teamid', 'name']
    list_filter = ['w_teamid', 'name']
    
class w_employeeAdmin(object):
    list_display = ['w_employeeid', 'name','w_sectionid','w_teamid']
    search_fields = ['w_employeeid', 'name','w_sectionid','w_teamid']
    list_filter = ['w_employeeid', 'name','w_sectionid','w_teamid']

xadmin.site.register(w_section, w_sectionAdmin)
xadmin.site.register(w_team, w_teamAdmin)
xadmin.site.register(w_employee, w_employeeAdmin)
#考核信息录入app
import xadmin

from .models import informationinput

class informationinputAdmin(object):
    list_display = ['user', 'category','sketch','w_employeeid','add_time','image','has_agree']
    search_fields = ['user', 'category','sketch','w_employeeid','add_time','image','has_agree']
    list_filter = ['user', 'category','sketch','w_employeeid','add_time','image','has_agree']

xadmin.site.register(informationinput, informationinputAdmin)
#用户adminx中配置全站基础
import xadmin
from xadmin import views

class BaseSetting(object):
    enable_themes = True
    use_bootswatch = True

class GlobalSettings(object):
    site_title = "信息后台管理系统"
    site_footer = ""


xadmin.site.register(views.BaseAdminView, BaseSetting)
xadmin.site.register(views.CommAdminView, GlobalSettings)
#apps.py中配置中文显示
# -*- coding: utf-8 -*-
    verbose_name = u"制度管理"
#_init_文件中配置
default_app_config = "institution.apps.InstitutionConfig"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,607评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,047评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,496评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,405评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,400评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,479评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,883评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,535评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,743评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,544评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,612评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,309评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,881评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,891评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,136评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,783评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,316评论 2 342

推荐阅读更多精彩内容