django 学习之路
离线添加数据库
-
123456789101112131415
# 启动django
import
os
import
sys
import
django
base_dir
=
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault(
'DJANGO_SETTINGS_MODULE'
,
'day06.settings'
)
django.setup()
# 伪造让django启动
from
web
import
models
from
utils.encrypt
import
md5
models.Administrator.objects.create(username
=
'root'
, password
=
md5(
"root"
), mobile
=
"1888888889"
)
顶端导航
- html文件
1234567891011121314151617181920212223
<
div
class="nav">
<
div
class="logo-area left">
<
a
href="{% url 'home' %}">
<
span
style="font-size: 18px;">NB的管理平台 </
span
>
</
a
>
</
div
>
<
div
class="right-menu right clearfix">
<
div
class="user-info right">
<
a
href="#" class="avatar" style="text-decoration: none;">
<
span
style="color: white;margin-right: 5px;">{{ request.nb_user.name }}</
span
>
<
img
class="img-circle" style="width: 35px;height: 35px;" src="{% static 'images/default.png' %}">
</
a
>
<
div
class="more-info">
<
a
href="{% url 'logout' %}" class="more-item">注销1</
a
>
<
a
href="{% url 'logout' %}" class="more-item">注销2</
a
>
<
a
href="{% url 'logout' %}" class="more-item">注销3</
a
>
<
a
href="{% url 'logout' %}" class="more-item">注销</
a
>
</
div
>
</
div
>
</
div
>
</
div
>
- css文件
1 .nav .right-menu .user-info { 2 padding: 0 30px 0 10px; 3 height: 48px; 4 position: relative; 5 } 6 7 /* hover 鼠标经过出现*/ 8 .nav .right-menu .user-info:hover .avatar { 9 background-color: #337ab7; 10 } 11 12 .nav .right-menu .user-info .avatar { 13 display: inline-block; 14 padding: 0 10px; 15 height: 48px; 16 } 17 18 .nav .right-menu .user-info .avatar img { 19 /* margin-top: 2px;*/ 20 } 21 22 .nav .right-menu .user-info .more-info { 23 display: none; 24 position: absolute; 25 top: 48px; 26 right: 20px; 27 border: 1px solid rgba(0, 0, 0, .15); 28 -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175); 29 box-shadow: 0 6px 12px rgba(0, 0, 0, .175); 30 background-color: #fff; 31 color: #333; 32 z-index: 1002; 33 } 34 35 .nav .right-menu .user-info:hover .more-info { 36 display: block; 37 } 38 39 .nav .right-menu .user-info .more-info .more-item { 40 display: block; 41 min-width: 160px; 42 padding: 0 15px; 43 line-height: 35px; 44 text-decoration: none; 45 color: #000000; 46 47 } 48 49 .nav .right-menu .user-info .more-info .more-item:hover { 50 background-color: #f1f0f0; 51 }
展示效果:
前端路径导航点击直接跳转

text_list = []
# 将级别text和别名存储在text_list
text_list.append([user_permission_dict[current_name]['text'], current_name])
menu_name = current_name
while user_permission_dict[menu_name]['parent']:
menu_name = user_permission_dict[menu_name]['parent']
text = user_permission_dict[menu_name]['text']
text_list.append([text, menu_name])
text_list.append(["首页", "home"])
text_list.reverse() # 列表反转
中间件

{# 路径导航#} {% if request.nb_user.text_list %} <ol class="breadcrumb"> {% for text in request.nb_user.text_list %} {# 获取级别《路径》text和别名《转换成url》#} {% if text.1 %} <li><a href="{% url text.1 %}">{{ text.0 }}</a></li> {% else %} <li><a>{{ text.0 }}</a></li> {% endif %} {% endfor %} </ol> {% endif %}
手机号验证的3种方式:
-
123456
# forms验证
mobile
=
forms.CharField(
label
=
"手机号"
,
required
=
True
,
validators
=
[RegexValidator(r
'^1\d{10}$'
,
'手机格式错误'
), ]
)
-
12345678
# forms验证方法:
def
clean_mobile():
mobile
=
self
.cleaned_data[
'mobile'
]
import
re
from
django.core.exceptions
import
ValidationError
if
not
re.match(r
'^\d{11}$'
,mobile):
raise
ValidationError(
"格式错误"
)
return
mobile
-
123
# models.py表类中
mobile
=
models.CharField(verbose_name
=
"手机号"
, max_length
=
11
, db_index
=
True
,
validators
=
[RegexValidator(r
'^\d{11}$'
,
'手机号格式错误'
), ])
serialize() 前端直接取form表单的data,包含csrf_token
-
12345678910111213141516171819202122232425262728293031
<
form
class="form-horizontal" id="addForm">
{% csrf_token %}
{% for field in form %}
<
div
class="form-group">
<
label
class="col-sm-2 control-label">{{ field.label }}</
label
>
<
div
class="col-sm-10" style="position: relative;margin-bottom: 25px">
{{ field }}
<
span
class="error-message" >{{ field.errors.0 }}</
span
>
</
div
>
</
div
>
{% endfor %}
</
form
>
$.ajax({
url: "{% url 'customer_charge_add' pk=pk %}",
type: 'POST',
data: $("#addForm").serialize(),
dataType: "JSON",
success: function (res) {
console.log(res);
if (res.status) {
window.location.reload();
} else {
$.each(res.detail, function (k, v) {
$("#id_" + k).next().text(v[0]);
})
}
}
})
事务(上下文操作) -> 原子性操作
-
(多用在交易记录,需要操作两个或多个表,要成功都成功,要失败都失败)
-
1234567891011121314151617181920212223242526
from
django.db
import
transaction
try
:
# 事务,上下文管理。
with transaction.atomic():
# 1.对当前操作的客户进行更新操作,账户余额:增加、减少 + 锁
cus_object
=
models.Customer.objects.
filter
(
id
=
pk, active
=
1
).select_for_update().first()
if
charge_type
=
=
2
and
cus_object.balance < amount:
return
JsonResponse(
{
'status'
:
False
,
'detail'
: {
"amount"
: [
"余额不足,账户总余额只有:{}"
.
format
(cus_object.balance)]}})
elif
amount <
=
0
:
return
JsonResponse({
'status'
:
False
,
'detail'
: {
"amount"
: [
"金额不能小于等于0"
]}})
if
charge_type
=
=
1
:
cus_object.balance
=
cus_object.balance
+
amount
else
:
cus_object.balance
=
cus_object.balance
-
amount
cus_object.save()
# 2.交易记录
form.instance.customer
=
cus_object
form.instance.creator_id
=
request.nb_user.
id
form.save()
except
Exception as e:
return
JsonResponse({
'status'
:
False
,
'detail'
: {
"amount"
: [
"操作失败"
]
锁
- 数据库排他锁 elect_for_update() 锁和事务结合使用,事务结束释放锁,再进行下一个事务
-
12
# 1.对当前操作的客户进行更新操作,账户余额:增加、减少 + 锁s
cus_object
=
models.Customer.objects.
filter
(
id
=
pk, active
=
1
).select_for_update().first()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现