用到的包是virtualenv和vrtualenvwrapper-win
新建虚拟环境
mkvirtualenv mxonline
激活虚拟环境
workon mxonline
django-admin startproject MxOnline
python manage.py startapp user
pip install django==1.9
pip install mysqlclient #连接数据库
pip install pillow #图片的加载
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "mxonline",
'USER': "root",
'PASSWORD': "888888",
'HOST': "127.0.0.1",
}
}
数据迁移
python manage.py makemigrations
python manage.py migrate
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
AUTH_USER_MODEL = "user.UserProfile"
# _*_ encoding:utf-8 _*_
from django.db import models
from django.contrib.auth.models import AbstractUser #继承原有表user中的字段,新填个性化字段
# Create your models here.
class UserProfile(AbstractUser):
nick_name = models.CharField(max_length=50, verbose_name=u"昵称", default=u"")
birthday = models.DateField(verbose_name=u"生日", null=True, blank=True)
gender = models.CharField(max_length=5, choices=(("male", u"男"), ("female", "女")), default=u"")
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 EmailVerifiyRecord(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=(("regiser", u"注册"), ("forget", u"找回密码")), max_length=10)
send_time = models.DateField(default=datetime.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)
url = models.URLField(max_length=200, verbose_name=u"访问地址")
index = models.IntegerField(default=100, verbose_name=u"顺序")
add_time = models.DateField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
verbose_name = u"轮播图"
verbose_name_plural = verbose_name
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", "初级"), ("zj", "中级"), ("gj", "高级")), max_length=2)
learn_time = models.IntegerField(default=0, verbose_name=u"学习时长(分钟)")
student = models.IntegerField(default=0, verbose_name=u"学习人数")
fav_nums = models.IntegerField(default=0, verbose_name=u"收藏人数")
image = models.ImageField(upload_to="course/%Y/m", verbose_name=u"封面图", max_length=100)
click_nums = models.IntegerField(default=0, verbose_name=u"点击数")
add_time = models.DateField(default=datetime.now,verbose_name=u"添加时间")
class Meta:
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.DateField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
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.DateField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
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/%Y/%m", verbose_name=u"资源文件", max_length=100)
add_time = models.DateField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
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_nums = 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.DateField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
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_years = 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_nums = models.IntegerField(default=0, verbose_name=u"点击数")
fav_nums = models.IntegerField(default=0, verbose_name=u"收藏数")
add_time = models.DateField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
class Meta:
verbose_name = u"教师"
verbose_name_plural = verbose_name
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.DateField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
class Meta:
verbose_name = u"城市"
verbose_name_plural = verbose_name
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=20, 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, "课程"), (2,"课程机构"), (3,"讲师")), default=1, 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
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'))
python manage.py createsuperuser
#root
#root280010
LANGUAGE_CODE = 'zh-hans' #中文
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False #本地时间
在admin.py下注册
from .models import UserProfile
class UserProfileAdmin(admin.ModelAdmin):
pass
admin.site.register(UserProfile, UserProfileAdmin)
'OPTIONS': {
"init_command": "SET foreign_key_checks = 0;",
(1)新建空白文件README.rst
压缩进 zip 中替换掉同名文件
下载后,从错误中可以看到,是文件README.rst
出现了 Unicode 解码错误,这个文件时没有什么用处的,可以新建一个同名的空白文件替换掉。
(2). 然后我们通过 cd 命令切换到该文件夹目录下,通过下面命令安装:
python setup.py install
(3)安装完成后,通过 pip list 可以看到 xadmin 以及相关依赖包都安装完成了。
(4)安装 import_export的包
但是你实际运行的时候又会发现,所以继续 安装成功以后,xadmin就算安装成功了。
pip install django-import-export
(1)在settings文件下
INSTALLED_APPS = (
'xadmin',
'crispy_forms',
'reversion',
)
(2)在url文件下
import xadmin
# url(r'^admin/', admin.site.urls),
url(r'^xadmin/', xadmin.site.urls),
也可以将xadmin拷贝到项目中,修改源码,提供丰富的插件
在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'))
sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))
# _*_ coding: utf-8 _*_
import xadmin
from .models import CityDict, CourseOrg, Teacher
class CityDictAdmin(object):
list_display = ['name', 'desc', 'add_time'] #显示列
search_fields = ['name', 'desc'] #搜索
list_filter = ['name', 'desc', 'add_time'] #过滤器
class CourseOrgAdmin(object):
list_display = [' name', 'desc', 'click_nums', 'fav_nums', 'image', 'address', 'city', 'add_time'] # 显示列
search_fields = [' name', 'desc', 'click_nums', 'fav_nums', 'image', 'address', 'city'] # 搜索
list_filter = [' name', 'desc', 'click_nums', 'fav_nums', 'image', 'address', 'city', 'add_time'] # 过滤器
class TeacherAdmin(object):
list_display = ['org', 'name', 'work_years', 'work_company', 'work_position', 'points', 'click_nums', 'fav_nums', 'add_time'] # 显示列
search_fields = ['org', 'name', 'work_years', 'work_company', 'work_position', 'points', 'click_nums', 'fav_nums'] # 搜索
list_filter = ['org', 'name', 'work_years', 'work_company', 'work_position', 'points', 'click_nums', 'fav_nums', 'add_time'] # 过滤器
xadmin.site.register(CityDict, CityDictAdmin)
xadmin.site.register(CourseOrg, CourseOrgAdmin)
xadmin.site.register(Teacher, TeacherAdmin)
(1)显示主题修改页面风格
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)
(2)导航栏的设置以及更改apps为中文名
apps.py设置
# _*_ coding: utf-8 _*_
from django.apps import AppConfig
class OperationConfig(AppConfig):
name = 'operation'
verbose_name = u"用户操作"
__init__.py设置
default_app_config = "user.apps.UserConfig"
效果图
跳转页面login前没有/,将css,js,images导入到static,并配置static
from user.views import LoginView
urlpatterns = [
url(r'^xadmin/', xadmin.site.urls),
url('^$', TemplateView.as_view(template_name="index.html"), name="index"),
url('^login/$', LoginView.as_view(), name="login"),
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
("css", os.path.join(STATIC_ROOT, 'css')),
("images", os.path.join(STATIC_ROOT, 'images').replace('\\', '/')),
("js", os.path.join(STATIC_ROOT, 'js')),
("img", os.path.join(STATIC_ROOT, 'img')),
from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView
import xadmin
from user.views import LoginView
urlpatterns = [
url(r'^xadmin/', xadmin.site.urls),
url('^$', TemplateView.as_view(template_name="index.html"), name="index"),
url('^login/$', LoginView.as_view(), name="login"),
]
from django.contrib.auth import authenticate, login
from django.views.generic.base import View
#用户登陆模块
class LoginView(View):
def get(self, request):
return render(request, "login.html", {})
def post(self, request):
#提交到表单form里面做验证
login_form = LoginForm(request.POST)
if login_form.is_valid():
user_name = request.POST.get("username", "")
pass_word = request.POST.get("password", "")
user = authenticate(username=user_name, password=pass_word)
if user is not None:
login(request, user)
return render(request, "index.html")
else:
return render(request, "login.html", {"msg": "用户名或密码错误!"})
else:
return render(request, "login.html", {"login_form": login_form})
settings.py配置
# Application definition
AUTHENTICATION_BACKENDS = (
'user.views.CustomBackend',
)
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q #并集
from .models import UserProfile
#使用邮箱也可以登陆
class CustomBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
try:
user = UserProfile.objects.get(Q(username=username) | Q(email=username)) #完成自定义登陆
if user.check_password(password):
return user
except Exception as e:
return None
index.html设置
{% if request.user.is_authenticated %}
服务电话:18582854749
- 鹏鹏
{% else %}
注册
登录
{% endif %}
login.html 如果用户信息出错,则显示错误信息
{{ msg }}
(4)form表单
用于验证用户名和密码,减轻后台验证的负担
后台新建form.py
#表单,用来验证
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(required=True)
password = forms.CharField(required=True, min_length=5)
前端设置信息
#高亮
#错误提示
{% for key, error in login_form.errors.items %}{{ key }}:{{ error }}{% endfor %}{{ msg }}
#路径返回