编写核心功能脚本
在./utils/script/下新建create_user_constructor.py
并新增代码
from utils.public.log import Log
class CreateUser(object):
"""
创建用户
"""
@staticmethod
def user(user_name, env, is_marital, birthdate, weight, sex, personality_label, interest='无', motto='无'):
"""
本功能无具体业务,只是个模板例子
"""
try:
info = f'用户名:{user_name},\n' \
f'执行环境:{env},\n' \
f'婚姻状况:{is_marital},\n' \
f'出生日期:{birthdate},\n' \
f'年龄:{weight},\n' \
f'性别:{sex},\n' \
f'个性标签:{personality_label},\n' \
f'爱好:{interest},\n' \
f'座右铭:{motto}'
result = f'创建用户成功:\n' \
f'{info}'
except Exception as e:
result = f'创建用户失败,{e}'
finally:
Log().info(result)
return result
编写视图(前端请求后的处理)
在./apps/user/下新建user_view.py并新增代码
from django.shortcuts import render
from user.form import createUserForm
from user.models import CreateUserTable
from utils.script.create_user_constructor import CreateUser
def add_user(request):
"""
创建用户
:param request:
:return:
"""
is_marital_dict = {
True: '已婚',
False: '未婚'
}
sex_dict = {
1: '男',
2: '女'
}
try:
if request.method == 'GET':
return render(request, 'create_user.html')
else:
create_user_form = createUserForm(request.POST)
if create_user_form.is_valid():
user_name = create_user_form.cleaned_data['user_name']
env = create_user_form.cleaned_data['environment']
is_marital = create_user_form.cleaned_data['is_marital']
birthdate = create_user_form.cleaned_data['birthdate']
weight = create_user_form.cleaned_data['weight']
sex = create_user_form.cleaned_data['sex']
personality_label = create_user_form.cleaned_data['personality_label']
interest = create_user_form.cleaned_data['interest1'] + create_user_form.cleaned_data['interest2'] + \
create_user_form.cleaned_data['interest3'] + create_user_form.cleaned_data['interest4'] + \
create_user_form.cleaned_data['interest5']
motto = create_user_form.cleaned_data['motto']
# 调用业务核心脚本
result = CreateUser.user(user_name, env, is_marital_dict[is_marital], birthdate, weight, sex_dict[sex],
personality_label, interest, motto)
# 保存数据至表
mysql_info = CreateUserTable()
mysql_info.user_name = user_name
mysql_info.environment = env
mysql_info.is_marital = is_marital
mysql_info.birthdate = birthdate
mysql_info.weight = weight
mysql_info.sex = sex
mysql_info.personality_label = personality_label
mysql_info.interest = interest
mysql_info.motto = motto
mysql_info.save()
return render(request, 'create_user.html', {
'msg': result
})
else:
return render(request, 'create_user.html', {
'add_product_form': create_user_form
})
except:
return render(request, 'create_user.html', {
'msg': result
})
添加路由(页面地址)
在./apps/user/urls.py新增页面地址
from django.conf.urls import include, url
from .user_views import add_user
urlpatterns = [
url(r'^adduser/$', add_user, name='add_user'),
]
版权声明:如无特殊说明,文章均为本站原创,转载请注明出处
本文链接:http://zhangyanc.club/subject/article/tool_django_views/
许可协议:署名-非商业性使用 4.0 国际许可协议