说明:该篇博客是博主一字一码编写的,实属不易,请尊重原创,谢谢大家!
接着上一篇博客继续往下写 :https://blog.csdn.net/qq_41782425/article/details/90141577
目录
一丶常见web攻击及防范
二丶Xadmin多种配置
三丶Xadmin插件开发(富文本编辑器)
四丶Xadmin插件开发(导出excel)
五丶项目部署上线
六丶项目总结
1.sql注入攻击与防范
① sql注入的危害
② sql注入登录演示
# sql注入登录演示
class UnsafeLoginView(View):
"""不安全登录,使用最原始的方法进行登录"""
def get(self, request):
return render(request, "login.html")
def post(self, request):
user_name = request.POST.get("username", "")
pass_word = request.POST.get("password", "")
import MySQLdb
conn = MySQLdb.connect(host="127.0.0.1", user="root", passwd="mysql", db="mxonline", charset="utf8")
cursor = conn.cursor()
sql = "select * from users_userprofile where username = '{0}' and password = '{1}' ".format(user_name, pass_word)
res = cursor.execute(sql)
# 获取用户所有数据
all_users = cursor.fetchall()
url(r'^login/$', UnsafeLoginView.as_view(), name="login"), # 登录页
2.xss攻击原理及防范
① xss跨站脚本攻击(Cross Site Scripting)的危害
② xss攻击原理
③ xss攻击流程图
④ xss攻击防范
3.csrf攻击与防范
① csrf跨站请求伪造(Cross-site request forgery)的危害
② csrf攻击原理
③ csrf防范
1.导航栏icon的修改
2.xadmin后台表数据设定默认字段排序
class CourseAdmin(object):
list_display = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students', 'click_nums']
search_fields = ['name', 'desc', 'detail', 'degree', 'students']
list_filter = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students']
ordering = ['-click_nums']
3.xadmin后台管理中字段设置为只读
readonly_fields = ['students', 'click_nums', 'fav_nums']
4.在xadmin后台中不显示某些字段
readonly_fields = ['students', 'fav_nums']
exclude = ['click_nums']
5.增加课程时修改外键选择的样式
relfield_style = 'fk-ajax'
6.inline的使用
class LessonInline(object):
model = Lesson
extra = 0
class CourseAdmin(object):
list_display = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students', 'click_nums']
search_fields = ['name', 'desc', 'detail', 'degree', 'students']
list_filter = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students']
ordering = ['-click_nums']
readonly_fields = ['students', 'fav_nums']
exclude = ['click_nums']
inlines = [LessonInline]
class LessonInline(object):
model = Lesson
extra = 0
class CourseResourceInline(object):
model = CourseResource
extra = 0
class CourseAdmin(object):
list_display = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students', 'click_nums']
search_fields = ['name', 'desc', 'detail', 'degree', 'students']
list_filter = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students']
ordering = ['-click_nums']
readonly_fields = ['students', 'fav_nums']
exclude = ['click_nums']
inlines = [LessonInline, CourseResourceInline]
7.自定义列表返回数据,同一个model注册两个管理器
class BannerCourse(Course):
class Meta:
verbose_name = "轮播课程"
verbose_name_plural = verbose_name
proxy = True
class BannerCourseAdmin(object):
list_display = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students', 'click_nums']
search_fields = ['name', 'desc', 'detail', 'degree', 'students']
list_filter = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students']
ordering = ['-click_nums']
readonly_fields = ['students', 'fav_nums']
exclude = ['click_nums']
inlines = [LessonInline, CourseResourceInline]
xadmin.site.register(BannerCourse, BannerCourseAdmin)
class BannerCourseAdmin(object):
list_display = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students', 'click_nums']
search_fields = ['name', 'desc', 'detail', 'degree', 'students']
list_filter = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students']
ordering = ['-click_nums']
readonly_fields = ['students', 'fav_nums']
exclude = ['click_nums']
inlines = [LessonInline, CourseResourceInline]
def queryset(self):
qs = super(BannerCourseAdmin, self).queryset()
qs = qs.filter(is_banner=True)
return qs
class CourseAdmin(object):
list_display = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students', 'click_nums']
search_fields = ['name', 'desc', 'detail', 'degree', 'students']
list_filter = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students']
ordering = ['-click_nums']
readonly_fields = ['students', 'fav_nums']
exclude = ['click_nums']
inlines = [LessonInline, CourseResourceInline]
def queryset(self):
qs = super(CourseAdmin, self).queryset()
qs = qs.filter(is_banner=False)
return qs
8.list_editable属性
list_editable = ['name', 'degree']
9.在课程列表中显示对应课程的章节数
def get_zj_nums(self):
#获取课程章节数
return self.lesson_set.all().count()
get_zj_nums.short_description = "章节数"
list_display = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students', 'click_nums', "get_zj_nums"]
10.在课程列表字段添加跳转按钮,指定跳转的链接地址
def go_to(self):
from django.utils.safestring import mark_safe
return mark_safe("跳转")
go_to.short_description = "跳转"
list_display = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students', 'click_nums', "get_zj_nums", "go_to"]
11.页面定时刷新插件
refresh_times = [3, 5]
12.在保存课程的时候统计课程机构的课程数
def save_models(self):
# 在保存课程的时候统计课程机构的课程数
obj = self.new_obj
obj.save()
if obj.course_org is not None:
course_org = obj.course_org
course_org.course_nums = Course.objects.filter(course_org=course_org).count()
course_org.save()
说明: django ueditor富文本编辑器的集成
1.Xadmin插件制作官方中文文档 https://xadmin.readthedocs.io/en/docs-chinese/make_plugin.html
2.DjangoUeditor源码文档 https://github.com/zhangfisher/DjangoUeditor
3.DjangoUeditor使用
INSTALLED_APPS = [
'django.contrib.admin',
.......,
.......,
"pure_pagination",
"DjangoUeditor"
]
url(r'^ueditor/',include('DjangoUeditor.urls' )),
detail = UEditorField(verbose_name=u"课程详情",width=600, height=300, imagePath="courses/ueditor/",
filePath="courses/ueditor/", default='')
import xadmin
from xadmin.views import BaseAdminPlugin, CreateAdminView, ModelFormAdminView, UpdateAdminView
from DjangoUeditor.models import UEditorField
from DjangoUeditor.widgets import UEditorWidget
from django.conf import settings
class XadminUEditorWidget(UEditorWidget):
def __init__(self,**kwargs):
self.ueditor_options=kwargs
self.Media.js = None
super(XadminUEditorWidget,self).__init__(kwargs)
class UeditorPlugin(BaseAdminPlugin):
def get_field_style(self, attrs, db_field, style, **kwargs):
if style == 'ueditor':
if isinstance(db_field, UEditorField):
widget = db_field.formfield().widget
param = {}
param.update(widget.ueditor_settings)
param.update(widget.attrs)
return {'widget': XadminUEditorWidget(**param)}
return attrs
def block_extrahead(self, context, nodes):
js = '' % (settings.STATIC_URL + "ueditor/ueditor.config.js") #自己的静态目录
js += '' % (settings.STATIC_URL + "ueditor/ueditor.all.min.js") #自己的静态目录
nodes.append(js)
xadmin.site.register_plugin(UeditorPlugin, UpdateAdminView)
xadmin.site.register_plugin(UeditorPlugin, CreateAdminView)
PLUGINS = (
'actions',
'.......',
'ueditor',
)
4.错误修正
说明:DjangoUeditor是基于Python 2.7的进行开发的,博主这里的开发环境为python3,所以需要对DjangoUeditor安装包下的models.py丶settings.py丶widgets.py丶commands.py丶urls.py丶views.py进行修改
# from widgets import UEditorWidget,AdminUEditorWidget
from .widgets import UEditorWidget, AdminUEditorWidget
更新配置:从用户配置文件settings.py重新读入配置UEDITOR_SETTINGS,覆盖默认
def UpdateUserSettings():
UserSettings=getattr(gSettings,"UEDITOR_SETTINGS",{}).copy()
# if UserSettings.has_key("config"):UEditorSettings.update(UserSettings["config"])
# if UserSettings.has_key("upload"):UEditorUploadSettings.update(UserSettings["upload"])
if UserSettings.get("config"):UEditorSettings.update(UserSettings["config"])
if UserSettings.get("upload"):UEditorUploadSettings.update(UserSettings["upload"])
# import settings as USettings
# from commands import *
from . import settings as USettings
from .commands import *
# import settings as USettings
from . import settings as USettings
#coding:utf-8
# from django import VERSION
# if VERSION[0:2]>(1,3):
# from django.conf.urls import patterns, url
# else:
# from django.conf.urls.defaults import patterns, url
#
# from views import get_ueditor_controller
#
# urlpatterns = patterns('',
# url(r'^controller/$',get_ueditor_controller)
# )
from .widgets import UEditorWidget, AdminUEditorWidget
from .views import get_ueditor_controller
from django.conf.urls import url
urlpatterns = [
url(r'^controller/$', get_ueditor_controller),
]
# import settings as USettings
from . import settings as USettings
#保存上传的文件
def save_upload_file(PostFile,FilePath):
try:
f = open(FilePath, 'wb')
for chunk in PostFile.chunks():
f.write(chunk)
# except Exception,E:
# f.close()
# return u"写入文件错误:"+ E.message
# f.close()
# return u"SUCCESS"
except Exception as E:
f.close()
return u"写入文件错误:"+ E.message
f.close()
return u"SUCCESS"
解决方法有三种:第一种就是在github上将别人修正好的适合python3的DjangoUeditor源码拷贝进行源码安装;第二种就是自己下载DjangoUeditor免安装源码放在项目extra_apps目录下;第三种就是下载DjangoUeditor源码安装,在对其下的模块进行修正
{% autoescape off %}
{{ course.detail }}
{% endautoescape %}
5.总结步骤:
安装
1.pip install DjangoUeditor
2.settings.py 中加入DjangoUeditor
3.url(r'ueditor/', include('DjangoUeditor.urls'))
4.detail = UeditorField()
xadmin
1.plugins中添加ueditor.py文件,在__init__中加入ueditor
2.adminx中添加style_fields = {'detail':'ueditor'}
说明:excel的导入插件开发
1.在xadmin/plugins中创建excel.py文件,拷贝如下内容
import xadmin
from xadmin.views import BaseAdminPlugin, ListAdminView
from django.template import loader
from xadmin.plugins.utils import get_context_dict
#excel 导入
class ListImportExcelPlugin(BaseAdminPlugin):
import_excel = False
def init_request(self, *args, **kwargs):
return bool(self.import_excel)
def block_top_toolbar(self, context, nodes):
nodes.append(loader.render_to_string('xadmin/excel/model_list.top_toolbar.import.html', context=get_context_dict(context)))
xadmin.site.register_plugin(ListImportExcelPlugin, ListAdminView)
2.在xadmin/templates/xadmin目录下创建excel目录,在目录下创建model_list.top_toolbar.import.html文件,文件内容如下
{% load i18n %}
3.在courses/adminx下的CourseAdmin类中添加import_excel = True属性,并定义一个post方法,在这个方法中可以任意添加任何逻辑代码,这里就不进行逻辑代码的演示了,直接pass,但必须返回如下调用,不然会出错
def post(self, request, *args, **kwargs):
if 'excel' in request.FILES:
pass
return super(CourseAdmin, self).post(request, args, kwargs)
4.在plugins/__init__.py中注册此插件
PLUGINS = (
'actions',
'filters',
'bookmark',
'export',
'ueditor',
'excel',
)
1.指定python3版本创建django_py3虚拟环境,并进入此环境
2.安装项目所需的包
3.查看当前虚拟环境下的包
4.运行项目
5.将windows上的mxonline数据库数据传输到ubuntu中
6.安装nginx
说明:安装过程不用演示,很简单
7.安装uwsgi
8.nginx配置
server {
listen 80;
server_name 192.168.4.63 www.mxonline.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location /static {
alias /home/taogang/Desktop/MxOnline/static;
}
location /media {
alias /home/taogang/Desktop/MxOnline/media;
}
location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:8000;
}
}
9.将项目所用到的所有静态资源文件收集到static目录下
10.创建并配置uwsgi.ini文件
DEBUG = False
ALLOWED_HOSTS = ['*']
11.测试使用uwsgi启动项目
12.在windows中使用域名访问网站
1.数据库设计
2.后台管理系统开发
3.登录和注册以及找回密码
4.课程机构
5.课程功能
6.讲师功能
7.个人中心
8.全局功能
9.web攻击及防范
10.xadmin进阶开发