python django bootstrap_导入 201901

参考 http://www.liujiangblog.com/course/django/124

 

AdminLTE-2.4.5


http://www.liujiangblog.com/course/django/125

 

1.

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]


mkdir static

为了以后扩展的方便,将AdminLTE源文件包里的bootstrap (bower_components)、dist和plugins三个文件夹,全部拷贝到 static目录中,这样做的话文件会比较大,比较多,但可以防止出现引用文件找不到、插件缺失等情况的发生,等以后对AdminLTE非常熟悉了,可以对static中无用的文件进行删减。

 

2.
mkdir templates

在cmdb根目录下的templates目录下,新建base.html文件,

将AdminLTE源文件包中的index.html中的内容拷贝过去。
然后,根据我们项目的具体情况修改文件引用、页面框架、title、CSS、主体和script块。

cp index.html base.html

 


3.
二、创建路由、视图
这里设计了三个视图和页面,分别是:

dashboard:仪表盘,图形化的数据展示
index:资产总表,表格的形式展示资产信息
detail:单个资产的详细信息页面

/urls.py修改成下面的样子:

#!/usr/bin/env python
# -*- coding:utf-8 -*-


from people import views

app_name = 'people'

urlpatterns = [
path('admin/', admin.site.urls),
# path(r'^report/', views.report, name='report'),
path(r'^dashboard/', views.dashboard, name='dashboard'),
path(r'^index/', views.index, name='index'),
path(r'^detail/(?P<asset_id>[0-9]+)/$', views.detail, name="detail"),
path(r'^$', views.dashboard),
]

 

############
https://blog.csdn.net/wjy397/article/details/48976137

django 模板找不到TemplateDoesNotExist报错!
然后需要先获取settings文件的上一级目录也就是AssetsPool同级目录
之后设
置TEMPLATE_DIRS将AssetsPool同级目录AssetsPoolApp下加入到模板路径中,

BASE_TEMPLATE_DIRS = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))#
获取当前脚本的父目录

TEMPLATE_DIRS = (
os.path.join(BASE_TEMPLATE_DIRS,'AssetsPoolApp'),
)
之后再views之中就可以写入
return render_to_response('AppHtml/Login.html', {})
如果TEMLATE_DIRS中是‘AssetsPoolApp/AppHtml’
那么在views之中就不用谢AppHtml了
就是:return render_to_response(''Login.html,{})
---------------------

#########

html feeedback
Template-loader postmortem
Django tried loading these templates, in this order:

Using engine django:

django.template.loaders.filesystem.Loader: D:\Program Files\JetBrains\learn_models\learn_models\templates\people\dashboard.html (Source does not exist)

 


########

settings.py 静态文件相关示例代码及说明:

1https://code.ziqiangxuetang.com/django/django-static-files.html

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'

# 当运行 python manage.py collectstatic 的时候
# STATIC_ROOT 文件夹 是用来将所有STATICFILES_DIRS中所有文件夹中的文件,以及各app中static中的文件都复制过来
# 把这些文件放到一起是为了用apache等部署的时候更方便
STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static')

# 其它 存放静态文件的文件夹,可以用来存放项目中公用的静态文件,里面不能包含 STATIC_ROOT
# 如果不想用 STATICFILES_DIRS 可以不用,都放在 app 里的 static 中也可以
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "common_static"),
'/path/to/others/static/', # 用不到的时候可以不写这一行
)

# 这个是默认设置,Django 默认会在 STATICFILES_DIRS中的文件夹 和 各app下的static文件夹中找文件
# 注意有先后顺序,找到了就不再继续找了
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder"
)


静态文件放在对应的 app 下的 static 文件夹中 或者 STATICFILES_DIRS 中的文件夹中。

 

################
0118
https://blog.csdn.net/u012041204/article/details/80208949?utm_source=blogxgwz7

WARNINGS:
?: (2_0.W001) Your URL pattern '^$' has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to
django.urls.path().
?: (2_0.W001) Your URL pattern '^detail/(?P<asset_id>[0-9]+)/$' [name='detail'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. Thi
s was likely an oversight when migrating to django.urls.path().

今天在使用Django时遇到上面的警告,虽然只是警告,但是却会导致网站无法访问。这问题是Django新版本改变导致URL中不需要再使用正则表达式了,只需要路径就OK了。


urlpatterns = [
path('admin/', admin.site.urls),

path('login/', views.login,name='login'),

path('',views.index,name='index'),

#此处设置为首页,以前写法是'^$',新版本不再使用^、$,只需要''就可以
]
---------------------

 

https://blog.csdn.net/judyge/article/details/49618147?utm_source=blogkpcl8

django--静态文件路径和模板路径配置

https://blog.csdn.net/jzdzhiyun/article/details/5282512


https://docs.djangoproject.com/en/2.1/howto/static-files/
https://docs.djangoproject.com/en/2.1/ref/contrib/staticfiles/

python manage.py findstatic dist\css\adminlte.css
Found 'dist\css\adminlte.css' here:
D:\Program Files\JetBrains\learn_models\learn_models\static\dist\css\adminlte.css
D:\Program Files\JetBrains\learn_models\learn_models\people\static\dist\css\adminlte.css

 

python manage.py collectstatic

return os.path.exists(self.path(name))
File "D:\Program Files\JetBrains\learn_models\venv\lib\site-packages\django\contrib\staticfiles\storage.py", line 43, in path
raise ImproperlyConfigured("You're using the staticfiles app "
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.


STATIC_ROOT = os.path.join(BASE_DIR,'static')

 

0124
https://code.ziqiangxuetang.com/django/django-static-files.html

clone 项目,基本测试 python manage.py runserver (重要,学习造车)


STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static')

STATICFILES_DIRS = (
os.path.join(BASE_DIR, "common_static"),
)

静态文件放在对应的 app 下的 static 文件夹中 或者 STATICFILES_DIRS 中的文件夹中。

当 DEBUG = True 时,Django 就能自动找到放在里面的静态文件。(Django 通过 STATICFILES_FINDERS 中的“查找器”,找到符合的就停下来,寻找的过程 类似于 Python 中使用 import xxx 时,找 xxx 这个包的过程)。

示例项目 dj18static, 应用 app 下面有一个 static 里面有一个 zqxt.png 图片:

按照文件夹的顺序,自上而下的找。

 


base.html 是在根目录下
{% extends 'base.html' %}
{% block title %}仪表盘{% endblock %}
{% load static %}

 

0126 导入models

TypeError: __init__() missing 1 required positional argument: 'on_delete'
将第十一行的代码改为:

herobook=models.ForeignKey('BookInfo',on_delete=models.CASCADE,)
即在外键值的后面加上 on_delete=models.CASCADE 'on_delete'


举例说明:
user=models.OneToOneField(User)
owner=models.ForeignKey(UserProfile)
需要改成:
user=models.OneToOneField(User,on_delete=models.CASCADE) --在老版本这个参数(models.CASCADE)是默认值
owner=models.ForeignKey(UserProfile,on_delete=models.CASCADE) --在老版本这个参数(models.CASCADE)是默认值

 

# Django 1.7 及以上的版本需要用以下命令 blogs.py 解析数据库
python manage.py makemigrations
python manage.py migrate

 


people.Article.tags: (fields.E300) Field defines a relation with model 'Tag', which is either not installed, or is abstract.
people.Asset.tags: (fields.E300) Field defines a relation with model 'Tag', which is either not installed, or is abstract.

solution:
comment old tables;

解释forgrin-key ,aand ManyToManyField


ForeignKey¶
https://docs.djangoproject.com/en/1.8/ref/models/fields/

class ForeignKey(othermodel, **options)[source]¶
A many-to-one relationship. Requires a positional argument: the class to which the model is related.

To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self').

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:

from django.db import models

class Car(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
# ...

class Manufacturer(models.Model):
# ...
pass

 


#sample

class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()

class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)


当有一对多,多对一,或者多对多的关系的时候,先把相关的对象查询出来

>>> from blog.models import Entry
>>> entry = Entry.objects.get(pk=1)
>>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
>>> entry.blog = cheese_blog
>>> entry.save()

 

 

https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_many/
https://www.cnblogs.com/zhaogaolong/p/5220975.html

class Publication(models.Model):
title = models.CharField(max_length=30)

def __str__(self): # __unicode__ on Python 2
return self.title

class Meta:
ordering = ('title',)

class Article(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)

 


>>> p1 = Publication(title='The Python Journal')
>>> p1.save()
>>> p2 = Publication(title='Science News')
>>> p2.save()
>>> p3 = Publication(title='Science Weekly')
>>> p3.save()

>>> a1 = Article(headline='Django lets you build Web apps easily')


a1.publications.add(p1)

 

>>> a2 = Article(headline='NASA uses Python')
>>> a2.save()
>>> a2.publications.add(p1, p2)
>>> a2.publications.add(p3)

 


Create and add a Publication to an Article in one step using create():

>>> new_publication = a2.publications.create(title='Highlights for Children')

 

>>> a1.publications.all()
[<Publication: The Python Journal>]
>>> a2.publications.all()
[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]

 


使用UTF-8 建库
mysql> show create database people
-> ;
+----------+----------------------------------------------------------------+
| Database | Create Database |
+----------+----------------------------------------------------------------+
| people | CREATE DATABASE `people` /*!40100 DEFAULT CHARACTER SET gbk */ |
+----------+----------------------------------------------------------------+
1 row in set (0.00 sec)

mysql>drop database people;


mysql>create database people default character set=utf8;

 

admin 平台添加超级管理员
python manage.py createsuperuser


下面,我们通过后台admin界面,多增加几个服务器实例,并修改其类型、业务线、状态、厂商、机房、标签,再刷新资产总表,可以看到效果如下:

add following in <app_name>/admin.py
people/admin.py

from django.contrib import admin
# Register your models here.
from .models import Asset
admin.site.register(Asset)

and visit:
http://127.0.0.1:8000/admin/people/

 

 


django.urls.exceptions.NoReverseMatch: 'assets' is not a registered namespace


点击local vars:
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) ...

▼ Local vars
view_name
'assets:detail'

index url 含有如下字块:
<td><a href="{% url 'assets:detail' asset.id %}">{{ asset.name }}</a></td>


解决办法:

URLS 拆分每个app 有urls , template 拆分,主目录和app目录都有template

根目录URL 加入name.space https://blog.csdn.net/mwmoo/article/details/53783140
path('assets/', include('people.urls', namespace='asset')),

 

 

 

https://www.cnblogs.com/qunxiadexiaoxiangjiao/p/8891227.html
Django中使用locals()函数的技巧
对 current_datetime 的一次赋值操作:

1
2
3
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response('current_datetime.html', {'current_date': now})
很多时候,就像在这个范例中那样,你发现自己一直在计算某个变量,保存结果到变量中(比如前面代码中的 now ),然后将这些变量发送给模板。 尤其喜欢偷懒的程序员应该注意到了,不断地为临时变量和临时模板命名有那么一点点多余。 不仅多余,而且需要额外的输入。

如果你是个喜欢偷懒的程序员并想让代码看起来更加简明,可以利用 Python 的内建函数 locals() 。它返回的字典对所有局部变量的名称与值进行映射。 因此,前面的视图可以重写成下面这个样子:

1
2
3
def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response('current_datetime.html', locals())
在此,我们没有像之前那样手工指定 context 字典,而是传入了 locals() 的值,它囊括了函数执行到该时间点时所定义的一切变量。 因此,我们将 now 变量重命名为 current_date ,因为那才是模板所预期的变量名称。 在本例中, locals() 并没有带来多 大 的改进,但是如果有多个模板变量要界定而你又想偷懒,这种技术可以减少一些键盘输入。

使用 locals() 时要注意是它将包括 所有 的局部变量,它们可能比你想让模板访问的要多。 在前例中, locals() 还包含了 request 。对此如何取舍取决你的应用程序。

 


##########
demo.js:14 Uncaught TypeError: $(...).controlSidebar is not a function
at HTMLDocument.<anonymous> (demo.js:14)
at i (jquery-2.2.3.min.js:2)
at Object.fireWith [as resolveWith] (jquery-2.2.3.min.js:2)
at Function.ready (jquery-2.2.3.min.js:2)
at HTMLDocument.J (jquery-2.2.3.min.js:2)

替代APP下的static 的 demo.js ,原先是19k, 替代完成是17K
D:\Program Files\JetBrains\learn_models\learn_models\people\static\dist\js


参考https://stackoverflow.com/questions/36025814/sidebar-is-not-a-function-error
Ask Question

1


I'm trying to get the most basic sidebar example running using examples from here. Here's my HTML:

<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="./css/sidebar.min.css" />
<script type="text/javascript" src="./css/sidebar.min.js"></script>
</head>
<body>
<div class="ui right vertical menu sidebar">
<div class="item">foo</div>
<div class="item">bar</div>
</div>
<div class="pusher">
Your site's actual content
</div>
</body>
</html>
This shows no sidebar; when I type $('.ui.sidebar').sidebar('toggle') into the developer console I get this error:

VM387:2 Uncaught TypeError: $(...).sidebar is not a function(…)
Using Chrome 49 on Windows 8.

How do I get the sidebar to show correctly?

jquery sidebar semantic-ui
shareimprove this question
asked Mar 16 '16 at 2:30

Nate Glenn
3,27952978
First off, in the network tab, are you getting a 200 OK status code from the sidebar js file? – Ben Sewards Mar 16 '16 at 2:32
Plz check the path of js file included. Are you sure it is in the css folder? – Aju John Mar 16 '16 at 2:33
@BenSewards yes, resources are loading correctly. – Nate Glenn Mar 16 '16 at 2:34
2
@NateGlenn Could be that you're not including the Jquery lib – Robin Carlo Catacutan Mar 16 '16 at 2:43
@RobinCarloCatacutan You're right. I thought it was included, since $('.ui.sidebar') didn't throw an error. Now that this is working, it looks completely crazy though. The entire page except for the line where "Your site's actual content" is is all grayed out. – Nate Glenn Mar 16 '16 at 2:52


###########20190129


###########20190130
模板语言
注意是占比,不是数量!

############
js 说明:
1.
按照AdminLTE中提供的示例,在HTML中添加相应的标签,在script中添加相应的JS代码(jQueryKnob)。JS代码基本照抄,不需要改动。对于显示的圆圈,可以修改其颜色、大小、形态、是否只读等属性,可以参照AdminLTE中的范例。

最重要的是,需要从数据库中获取相应的数据,修改assets/views.py中的dashboard视图,最终如下:


2.
关键是series列表,其中的type指定该charts是什么类型,bar表示柱状图,而data就是至关重要的具体数据了,利用模板语言,将从数据库中获取的具体数值传入进来,Echarts插件会根据数值进行动态调整。

 

3.
series中的type指定为pie类型表示饼图,data列表动态传入各种资产类型的数量。其它的设置可参考官方文档。

为了展示的方便,我们在admin中新建一些网络设备、安全设备、软件资产等其它类型的资产,然后查看资产总表和饼图。这里我分别添加了一台网络、安全和存储设备和两个软件资产。

 

######
模型说明:

4.机房、制造商、业务线、合同、资产标签等数据模型
说明:

每台安全、网络、存储设备都通过一对一的方式唯一关联这一个资产对象。 (asset_id 来关联)
通过sub_asset_type又细分设备的子类型
对于软件,它没有物理形体,因此无须关联一个资产对象;
软件只管理那些大型的收费软件,关注点是授权数量和软件版本。对于那些开源的或者免费的软件,显然不算公司的资产

 

 


说明
机房可以有很多其它字段,比如城市、楼号、楼层和未知等等,如有需要可自行添加;
业务线可以有子业务线,因此使用一个外键关联自身模型;
合同模型主要存储财务部门关心的数据;
资产标签模型与资产是多对多的关系。

 


########项目需求

二、项目需求分析
本项目不是一个完整的的CMDB系统,重点针对服务器资产的自动数据收集、报告、接收、审批、更新和展示,搭建一个基础的面向运维的主机管理平台。

下面是项目需求的总结:

尽可能存储所有的IT资产数据,但不包括外设、优盘、显示器这种属于行政部门管理的设备;
硬件信息可自动收集、报告、分析、存储和展示;
具有后台管理人员的工作界面;
具有前端可视化展示的界面;
具有日志记录功能;
数据可手动添加、修改和删除。
当然,实际的CMDB项目需求绝对不止这些,还有诸如用户管理、权限管理、API安全认证、REST设计等等。

三、资产分类
资产种类众多,不是所有的都需要CMDB管理,也不是什么都是CMDB能管理的。

下面是一个大致的分类,不一定准确、全面:

资产类型包括:

服务器
存储设备
安全设备
网络设备
软件资产
服务器又可分为:

刀片服务器
PC服务器
小型机
大型机
其它
存储设备包括:

磁盘阵列
网络存储器
磁带库
磁带机
其它
安全设备包括:

防火墙
入侵检测设备
互联网网关
漏洞扫描设备
数字签名设备
上网行为管理设备
运维审计设备
加密机
其它
网络设备包括:

路由器
交换器
负载均衡
VPN
流量分析
其它
软件资产包括:

操作系统授权
大型软件授权
数据库授权
其它
其中,服务器是运维部门最关心的,也是CMDB中最主要、最方便进行自动化管理的资产。

服务器又可以包含下面的部件:

CPU
硬盘
内存
网卡
除此之外,我们还要考虑下面的一些内容:

机房
业务线
合同
管理员
审批员
资产标签
其它未尽事宜
大概对资产进行了分类之后,就要详细考虑各细分数据条目了。

共有数据条目:

有一些数据条目是所有资产都应该有的,比如:

资产名称
资产sn
所属业务线
设备状态
制造商
管理IP
所在机房
资产管理员
资产标签
合同
价格
购买日期
过保日期
批准人
批准日期
数据更新日期
备注
另外,不同类型的资产还有各自不同的数据条目,例如服务器:

服务器:

服务器类型
添加方式
宿主机
服务器型号
Raid类型
操作系统类型
发行版本
操作系统版本
其实,在开始正式编写CMDB项目代码之前,对项目的需求分析准确与否,数据条目的安排是否合理,是决定整个CMDB项目成败的关键。这一部分工作看似简单其实复杂,看似无用其实关键,做好了,项目基础就牢固,没做好,推到重来好几遍很正常!

 

( 重要
通过前面的内容,我们可以看出CMDB数据模型的设计非常复杂,我们这里还是省略了很多不太重要的部分,就这样总共都有400多行代码。其中每个模型需要保存什么字段、采用什么类型、什么关联关系、定义哪些参数、数据是否可以为空,这些都是踩过各种坑后总结出来的,不是随便就能定义的。所以,请务必详细阅读和揣摩这些模型的内容。

一切没有问题之后,注册app,然后makemigrations以及migrate!)

 


#######################20190207

( 今天学习实习下windows 收集信息和linux 下收集信息,封装字典,二级路由,json格式,构造,转换,csrf安全令牌,打包到data字典)
(分散管理,函数报错,调试单个.py 文件)

本模块基于windows操作系统,依赖wmi和win32com库,需要提前使用pip进行安装,
或者下载安装包手动安装。

pip install wmi
pip install win32com

conf/setting.conf
30.1.245.138
or
21.15.26.211


python manage.py runserver 30.1.245.138:8000
or
python manage.py runserver 21.15.26.211:8000

 

File "main.py", line 16, in <module>
handler.ArgvHandler(sys.argv)

 

#######################20190219

( 今天学习实习下django 的后端构造,admin 展示管理,创建,逻辑,流程,对象,方法,views 过于庞大,.py 核心业务,特别好用的update_or_create(),字典,发送数据)
(自定义admin,调用实例方法,创建测试用例,如何上线,添加,入口方法,利用request.user,提前获取,核心方法,资产对象,扩展接口)


#######################20190220

(今天继续学习django 后台端构造,Exception,report_data,扩展接口,日志类型,反射,更新方法,记录日志,字典格式,复用的函数,set类型的差集功能,key,
defaults数据字典,内存对象,运行脚本,报告数据,pass)

posted @ 2019-02-11 16:16  feiyun8616  阅读(759)  评论(0编辑  收藏  举报