def register(request: HttpRequest): if request.method == 'POST': content_type = request.META.get('CONTENT_TYPE') # CONTENT_TYPE:application/json try: if 'json' in content_type: payload = simplejson.loads(request.body) username = payload['name'] password = payload['password'] email = payload['email'] if 'form-data' in content_type: username = request.POST.get('name') password = request.POST.get('password') email = request.POST.get('email') except Exception as e: print(e) return HttpResponseBadRequest('Error') password = tools.pwd_bcrypt(password) res = models.User.objects.filter(email=email).first() if res: return HttpResponseBadRequest('email is exists') user = models.User(name=username, password=password, email=email) try: user.save() token = tools.get_token(user.id) return JsonResponse({ 'user': user.id, 'name': user.name, 'email': user.email, 'token': token }) except: raise
def handle_user(request): form = Form(request.POST) verboseName = request.POST['username'] name = verboseName.replace(" ", "") if verboseName == '': return render(request, 'home/home.html', {'error_message': "Type in your summoner name!"}) if not models.User.objects.filter(name=name).exists(): curr_user = models.User(name=name, verbose_name=verboseName.capitalize()) curr_user.process() curr_user.save() return HttpResponseRedirect(reverse('user:results', args=(name, )))
def register(request): if request.session.get('is_login', None): return redirect('/index/') if request.method == 'POST': input_code = request.POST.get('check_code').upper() register_form = forms.RegisterForm(request.POST) message = "请检查填写的内容!" if register_form.is_valid(): username = register_form.cleaned_data.get('username') password1 = register_form.cleaned_data.get('password1') password2 = register_form.cleaned_data.get('password2') email = register_form.cleaned_data.get('email') sex = register_form.cleaned_data.get('sex') if password1 != password2: message = '两次输入的密码不同!' return render(request, 'login/register.html', locals()) else: same_name_user = models.User.objects.filter(username=username) if same_name_user: message = '用户名已经存在' return render(request, 'login/register.html', locals()) same_email_user = models.User.objects.filter(email=email) if same_email_user: message = '该邮箱已经被注册了!' return render(request, 'login/register.html', locals()) if request.session['CheckCode'].upper()==input_code: new_user = models.User() new_user.username = username new_user.password = hashlib.sha1(password1.encode('utf-8')).hexdigest() new_user.email = email new_user.sex = sex new_user.save() message="注册成功" return redirect('/login/',locals()) else: message='验证码输入错误' return render(request, 'login/register.html', locals()) else: return render(request, 'login/register.html', locals()) register_form = forms.RegisterForm() return render(request, 'login/register.html', locals())
def register(request): # 验证表单信息 if request.method == 'POST': # 验证验证码是否正确 session_code = request.session['CheckCode'].lower() code = request.POST['caption'] if session_code == code: user_info = models.User(username=request.POST['username'], password=request.POST['password'], truename=request.POST['truename'], email=request.POST['email'], ctime=int(time.time()), last_login_ip=request.META['REMOTE_ADDR']) user_info.save() if user_info.id: request.session['username'] = request.POST['username'] return HttpResponseRedirect('/index') return render(request, 'home/user/register.html') else: return render(request, 'home/user/register.html')
def register(request): if request.session.get('id') is not None: return redirect('/') if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') username = username.strip() password = password.strip() if models.User.objects.filter(username=username).exists(): message = '该用户名已被注册' return render(request, 'register.html', {"message": message}) if not match('[BHQ]\d{8}', username): message = '该用户名不合法' return render(request, 'register.html', {"message": message}) user = models.User() user.username = username user.password = password user.save() request.session['id'] = user.id # 记录用户已登录 return redirect('/') return render(request, 'register.html')
def handle(self, *args, **options): username = options['username'] password = options['password'] try: user = models.User.objects.get(username=username) except Exception as e: user = models.User(username=username, password=password) user.save() try: role = models.Role.objects.get(name="超级管理员") except Exception as e: role = models.Role(name="超级管理员") role.save() try: group = models.Group.objects.get(name="超级部门") except Exception as e: group = models.Group(name="超级部门") group.save() for v in models.Permission.permission_choices.values(): try: permission = models.Permission.objects.get(name=v[0], codename=v[1]) except Exception as e: permission = models.Permission(name=v[0], codename=v[1]) permission.save() role.permissions.add(permission) group.permissions.add(permission) role.save() group.save() user.role.add(role) user.groups.add(group) user.save() self.stdout.write(self.style.SUCCESS('基础信息创建成功'))
def post(self, request: HttpRequest): data = json.loads(request.body) username = data.get("username") password = data.get("password", "123456") default_password = password == "123456" realname = data.get("realname") telephone = data.get("telephone") email = data.get("email") if not all([username, realname, telephone]): return JsonResponse({"status": 1, "msg": "请设置正确的用户信息"}) try: models.User.objects.get(username=username) except Exception as e: return JsonResponse({"status": 2, "msg": "请设置正确的用户信息"}) group = data.get("group") role = data.get("role") permission = data.get("permission") # 角色 部门 权限 都不嫩为空 如果不存在需要新建 check = self.check_three(group, role, permission) if check is None: return JsonResponse({"status": 3, "msg": "权限设置错误"}) # 创建用户 user = models.User(username=username, password=password, realname=realname, telephone=telephone, email=email) user.groups = check.group user.role = check.role user.permissions = check.permission user.save() return JsonResponse({ "status": 0, "msg": "添加成功" + " 已成功设置默认密码" if default_password else "" })
def register(request): """用户注册功能""" if request.method == 'GET': return render(request, 'register.html') else: # 判断用户选项是否为空 if request.POST.get('uname', '') and request.POST.get( 'password', '') and request.POST.get('company', ''): # 判断两次密码是否一致 if request.POST['password'] == request.POST['password_1']: # 判断用户名是否存在 if not models.User.objects.filter(uname=request.POST['uname']): # 密码加密 password = make_password(request.POST['password'], None, 'pbkdf2_sha1') # 新增用户 newUser = models.User(uname=request.POST['uname'], password=password, company_id=request.POST['company']) try: newUser.save() except DatabaseError as e: logging.warning(e) result = {'response': '注册用户失败'} return HttpResponse(json.dumps(result)) result = {'response': '注册用户成功'} return HttpResponse(json.dumps(result)) else: result = {'response': '用户名已存在'} return HttpResponse(json.dumps(result)) else: result = {'response': '密码不一致,请重新输入'} return HttpResponse(json.dumps(result)) else: result = {'response': '用户名、密码、企业不能为空'} return HttpResponse(json.dumps(result))
def user(request): request_result = __checkUser(request) request_result = HTTP_RESULT_SUCCESS # 要删掉 if request_result == HTTP_RESULT_SUCCESS: # 如果请求成功 if request.method == 'GET': # 如果是Get获取数据 print('Get请求') if {config.KEY_PAGE_NUM, config.KEY_PAGE_COUNT}.intersection(request.GET): # 制定页码 print('请求参数符合条件') user_list = database.User.objects.all() return HttpResponse(user_list) elif request.method == 'POST': print('收到的API的关于用户的POST的请求\n'+str(request.POST)) if {config.KEY_USER_ACTION_TYPE, config.KEY_USERNAME, config.KEY_PASSWORD, config.KEY_IS_STUFF, config.KEY_IS_ACTIVE, config.KEY_NICKNAME, config.KEY_INFO}.intersection(request.POST): print('用户的参数校验正确') user_username = request.POST[config.KEY_USERNAME] user_password = request.POST[config.KEY_PASSWORD] user_is_stuff = int(request.POST[config.KEY_IS_STUFF]) == VALUE_BOOL_TRUE user_is_active = int(request.POST[config.KEY_IS_ACTIVE]) == VALUE_BOOL_TRUE user_action_type = int(request.POST[config.KEY_USER_ACTION_TYPE]) user_info = request.POST[config.KEY_INFO] user_nickname = request.POST[config.KEY_NICKNAME] if user_nickname == '': user_nickname = user_username if user_info == '': user_info = '暂无简介' user_operation_result = VALUE_OPERATION_RESULT_FAIL if user_action_type == ACTION_TYPE_USER_CREATE: # 如果是创建用户 print('创建用户 是否工作人员 '+str(user_is_stuff)+' 是否活动 '+str(user_is_active)) if database.User.objects.filter(username=user_username): # 如果用户名已被注册 user_operation_result = VALUE_OPERATION_RESULT_USER_EXIST print("同户名 %s 已被注册"%user_username) else: # 如果用户名可用 temp_user = database.User() temp_user.username = user_username temp_user.nickname = user_nickname temp_user.set_password(user_password) temp_user.is_staff = user_is_stuff temp_user.is_active = user_is_active temp_user.info = user_info temp_user.save() print("同户名 %s 创建成功"%user_username) elif user_action_type == ACTION_TYPE_USER_EDIT: # 如果是编辑用户,不会改变密码 print('编辑用户') if database.User.objects.filter(username=user_username): # 如果用户的确存在 temp_user = database.User.objects.get(username=user_username) temp_user.username = user_username temp_user.nickname = user_nickname temp_user.is_staff = user_is_stuff temp_user.is_active = user_is_active temp_user.info = user_info temp_user.save() print("同户 %s 编辑成功"%user_username) else: # 如果用户不存在 user_operation_result = VALUE_OPERATION_RESULT_USER_EXIST print("同户 %s 不存在,不能编辑"%user_username) elif user_action_type == ACTION_TYPE_USER_DEL: # 如果是删除账户 print('删除用户') if database.User.objects.filter(username=user_username): # 如果用户的确存在 temp_user = database.User.objects.get(username=user_username) print("同户 %s 删除成功"%user_username) temp_user.delete() else: # 如果用户不存在 user_operation_result = VALUE_OPERATION_RESULT_USER_EXIST print("同户 %s 不存在,不能删除"%user_username) else: print('传递的用户操作类型不正确') user_action_type = ACTION_TYPE_NONE json_obj = { KEY_RESULT: HTTP_RESULT_SUCCESS, KEY_TYPE: TYPE_USER, KEY_OPERATION_RESULT: user_operation_result, config.KEY_USERNAME: user_username, config.KEY_NICKNAME: user_nickname, config.KEY_IS_STUFF: user_is_stuff, config.KEY_IS_ACTIVE: user_is_active, config.KEY_INFO: user_info, config.KEY_USER_ACTION_TYPE: user_action_type } return HttpResponse(json.dumps(json_obj)) return HttpResponse(JSON_PARAMS_INCORRENCT) else: return HttpResponse(DICT_RESULT_CODE.get(request_result, JSON_UNKNOWN_ERROR))
def save(self): new_user = models.User(login=self.data["email"], password=self.data["password"]) new_user.save()
def userlist(request): userlist = models.User().get_all() return render(request, 'userlist.html', {'users': userlist})
def test_form_test(self): user = models.User(login=self.test_user_data["email"], password=self.test_user_data["password"]) with self.assertRaises(Exception) as exc: user.save() self.assertNotEqual(exc, Exception)
def register(request): if request.session.get('is_login', None): # cant register when logged in return redirect('/user/index/') if request.method == 'POST': register_form = RegisterForm(request.POST) # Get the form # check_box_list = request.POST.getlist('check_box_list') # for i in check_box_list: # print(check_box_list) # if i == '1': # print("the form returns integer") # print("the term function") # i.e. add the term choice to db message = '' check_term = request.POST.get( 'term_check' ) # another method to get check box, or can use form.cleaned_data if check_term == 'on': stored_form = register_form if register_form.is_valid(): # dont wanna fill form again # username = register_form.cleaned_data['username'] register_form.clean() username = request.POST.get('username') password1 = request.POST.get('password1') password2 = request.POST.get('password2') email = request.POST.get('email') # check passwords are the same if password1 != password2: message = 'Not the same password' return render(request, 'user/register.html', { 'message': message, 'register_form': stored_form }) else: same_name_user = models.User.objects.filter( username=username) # check user name if same_name_user: message = 'The user name was already existed' return render(request, 'user/register.html', { 'message': message, 'register_form': stored_form }) same_email_user = models.User.objects.filter(email=email) if same_email_user: message = 'The email was registered, please use another one' return render(request, 'user/register.html', { 'message': message, 'register_form': stored_form }) artist = request.POST.get('artist') if artist == 'on': ref_email = request.POST.get('refEmail') if models.User.objects.filter(email=ref_email): message = 'Sorry, cant find your referee\'s email' return render(request, 'user/register.html', { 'message': message, 'register_form': stored_form }) # create the user new_user = models.User() new_user.instagram_username = request.POST.get( 'instagram_username') new_user.username = username # use encrypted password new_user.password = hash_code(password1) new_user.email = email new_user.is_active = False # record additional info additional_info = request.POST.get('additionalInfo') street1 = request.POST.get('street1') additionalInfo = models.AdditionalInfo() additionalInfo.gender = request.POST.get('gender') if additional_info == 'on' or street1 != '': # they may fill the form and close the tab additionalInfo.age = int(request.POST.get('age')) additionalInfo.street1 = street1 additionalInfo.street2 = request.POST.get('street2') additionalInfo.suburb = request.POST.get('suburb') additionalInfo.state = request.POST.get('state') additionalInfo.postalCode = request.POST.get( 'postalCode') additionalInfo.country = request.POST.get('country') additionalInfo.phone = request.POST.get('phone') # record interest interest = models.Interest() if request.POST.get('painting') == 'on': interest.painting = True if request.POST.get('sculpture') == 'on': interest.sculpture = True if request.POST.get('photography') == 'on': interest.photography = True if request.POST.get('calligraphy') == 'on': interest.calligraphy = True if request.POST.get('printmaking') == 'on': interest.printmaking = True if request.POST.get('artsAndCrafts') == 'on': interest.artsAndCrafts = True if request.POST.get('sealCutting') == 'on': interest.sealCutting = True if request.POST.get('artDesign') == 'on': interest.artDesign = True if artist == 'on': new_user.artist = True ref_email = request.POST.get('refEmail') new_user.refEmail = ref_email real_name = request.POST.get('realName') success = send_code_email(email, referee_email=ref_email, send_type="register", real_name=real_name, is_artist=True) else: success = send_code_email(email, send_type="register") if success: try: additionalInfo.save() interest.save() new_user.interest = interest new_user.additionalInfo = additionalInfo new_user.save() except Exception as e: print(e) return render(request, "user/success_send.html") else: message = 'failed to send email that cannot register you now' return render(request, 'user/register.html', { 'message': message, 'register_form': stored_form }) message = 'Please check the provided information such as Captcha' return render(request, 'user/register.html', { 'message': message, 'register_form': stored_form }) # if request is not valid, return a RegisterForm register_form = RegisterForm() message = '' # render a form with error message return render(request, 'user/register.html', locals())
# 文件夹 包 # 非py文件 包:py文件 # 一个包中可以存放多个模块 # 项目 > 包 > 模块 > 类 函数 变量 # 使用包中模块中的User类 from user import models u = models.User('admin', '123456') u.show() from user.models import User u = User('admin', '123456') u.show() from article.models import Article a = Article('个人总结', '雨行') a.show() ''' article ---models.py ---__init__.py ---... user ---models.py ---__init__.py ---...
def create(self, validated_data): user = models.User(**validated_data) user.set_password(validated_data['password']) user.save() return user