def test_bad_username(self): # Simple match. form = RegisterForm({'username': '******', 'password': '******', 'password2': 'adssadfsadf', 'email': '*****@*****.**'}) assert not form.is_valid() # Simple obfuscation. form = RegisterForm({'username': '******', 'password': '******', 'password2': 'adssadfsadf', 'email': '*****@*****.**'}) assert not form.is_valid() # Partial match. form = RegisterForm({'username': '******', 'password': '******', 'password2': 'adssadfsadf', 'email': '*****@*****.**'}) assert not form.is_valid() # No match. form = RegisterForm({'username': '******', 'password': '******', 'password2': 'adssadfsadf', 'email': '*****@*****.**'}) assert form.is_valid()
def test_bad_username(self): # Simple match. form = RegisterForm({'username': '******', 'password': '******', 'password2': 'adssadfsadf1', 'email': '*****@*****.**'}) assert not form.is_valid() # Simple obfuscation. form = RegisterForm({'username': '******', 'password': '******', 'password2': 'adssadfsadf1', 'email': '*****@*****.**'}) assert not form.is_valid() # Partial match. form = RegisterForm({'username': '******', 'password': '******', 'password2': 'adssadfsadf1', 'email': '*****@*****.**'}) assert not form.is_valid() # No match. form = RegisterForm({'username': '******', 'password': '******', 'password2': 'adssadfsadf1', 'email': '*****@*****.**'}) assert form.is_valid()
def handle_register(request, email_template=None, email_subject=None, email_data=None): """Handle to help registration.""" if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form = try_send_email_with_form( RegistrationProfile.objects.create_inactive_user, form, 'email', form.cleaned_data['username'], form.cleaned_data['password'], form.cleaned_data['email'], locale=request.locale, email_template=email_template, email_subject=email_subject, email_data=email_data) if not form.is_valid(): # Delete user if form is not valid, i.e. email was not sent. # This is in a POST request and so always pinned to master, # so there is no race condition. User.objects.filter(email=form.instance.email).delete() else: statsd.incr('user.register') return form return RegisterForm()
def test_can_save(self): self.assertEqual(User.objects.count(), 0) test_form = RegisterForm({'username': '******', 'email': '*****@*****.**', 'password1': 'asdf', 'password2': 'asdf'}) test_form.is_valid() test_form.save() self.assertEqual(User.objects.count(), 1)
def test_can_save(self): self.assertEqual(User.objects.count(), 0) test_form = RegisterForm({ 'username': '******', 'email': '*****@*****.**', 'password1': 'asdf', 'password2': 'asdf' }) test_form.is_valid() test_form.save() self.assertEqual(User.objects.count(), 1)
def make_validated_form(**kwargs): valid = dict( first_name="Admin", last_name="Adminson", email="*****@*****.**", username="******", facebook="https://www.facebook.com/adminadminson", phone="99 9999-9999", password1="123456", password2="123456", ) data = dict(valid, **kwargs) form = RegisterForm(data) form.is_valid() return form
def make_validated_form(**kwargs): valid = dict( first_name='Admin', last_name='Adminson', email='*****@*****.**', username='******', facebook='https://www.facebook.com/adminadminson', phone='99 9999-9999', password1='123456', password2='123456', ) data = dict(valid, **kwargs) form = RegisterForm(data) form.is_valid() return form
def test_not_valid_with_non_matching_passwords(self): self.assertEqual(User.objects.count(), 0) test_form = RegisterForm({'username': '******', 'email': '*****@*****.**', 'password1': 'asdf', 'password2': 'asdf2'}) test_form.is_valid() def test_this(): test_form.save() self.assertRaises(ValueError, test_this) self.assertEqual(User.objects.count(), 0)
def post(self, request): register_form = RegisterForm(request.POST) if register_form.is_valid(): # 判断RegisterForm中定义的字段(forms.py文件)是否合法,例如是否不为空 data = register_form.cleaned_data # register_form.cleaned_data包含了RegisterForm中定义的字段, # 跟前端页面表单中的name属性相对应,获取用户输入的值,字典形式返回 if UserProfile.objects.filter(email=data['email']): # 判断数据库中是否有相同的email存在 return render( request, 'register.html', { 'register_form': register_form, 'captcha': captcha(), 'msg': '用户已存在' }) flag = is_contain_chinese(data['username']) # 判断输入的用户名是否包含中文 if not flag: if UserProfile.objects.filter(username=data['username']): # 判断用户名username是否存在 return render( request, 'register.html', { 'register_form': register_form, 'captcha': captcha(), 'msg': '此用户名已被使用' }) captchaHashkey = request.POST.get('hashkey', '') if jarge_captcha(data['captcha'], captchaHashkey): # 判断前端传过来的验证码是否与数据库中的相同 register_form.cleaned_data['password'] = make_password( register_form.cleaned_data['password']) UserProfile.objects.create(**register_form.cleaned_data, is_active=False) send_register_email(data['email'], 'register') return render(request, 'login.html', { 'msg': '发送邮件成功,请前往验证邮箱...', 'captcha': captcha() }) # 如果都满足的话,就渲染到login.html这个文件,反之就是下面的渲染到register.html文件并显示相应的错误 else: return render( request, 'register.html', { 'register_form': register_form, 'msg': '验证码错误', 'captcha': captcha() }) else: return render( request, 'register.html', { 'register_form': register_form, 'captcha': captcha(), 'msg': '用户名不要包含中文' }) else: return render(request, 'register.html', { 'register_form': register_form, 'captcha': captcha() })
def sign_up(request): redirect_to = request.POST.get('next', request.GET.get('next')) if request.method == 'POST': signup_form = RegisterForm(request.POST) if signup_form.is_valid(): signup_info = signup_form.cleaned_data username = signup_info['user_name'] password = signup_info['user_passwd'] user_email = signup_info['user_email'] if signup_info[ 'user_email'] else None # user = UserProfile.objects.create_user( # username=username, # password=password, # email=user_email, # ) # user.save() messages.success(request, '注册成功,正在跳转页面!') if signup_info['auto_login']: user = auth.authenticate( username=username, password=password) auth.login(request, user) if redirect_to: return HttpResponseRedirect(redirect_to) else: return HttpResponseRedirect('/') else: return HttpResponseRedirect('/') else: return render(request, 'users/register.html', {'form': signup_form}) else: form = RegisterForm() return render(request, 'users/register.html', { 'form': form, 'next': redirect_to })
def post(self, request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get('email', '') # 用户已存在 if UserProfile.objects.filter(email=user_name): return render( request, 'register.html', { 'register_form': register_form, 'msg': 'The username is already existed.' }) pass_word = request.POST.get('password', '') print('user_name:', user_name) print('pass_word:', pass_word) # 实例化一个 useProfile 对象 user_profile = UserProfile() user_profile.username = user_name user_profile.email = user_name # 默认添加的用户是激活状态(is_active=1表示True),这里修改默认的状态为 False,只有用户邮箱激活后才改为True user_profile.is_active = False # 密码加密 user_profile.password = make_password(pass_word) user_profile.save() send_register_email(user_name, 'register') return render(request, 'login.html') else: return render(request, 'register.html', {'register_form': register_form})
def post(self, request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get('email', None) # 如果用户存在,则显示错误信息 if UserProfile.objects.filter(email=user_name): return render(request, 'register.html', { 'register_form': register_form, 'message': '用户名已存在' }) pass_word = request.POST.get('password', None) pass_word2 = request.POST.get('pwd', None) if pass_word == pass_word2: # 实例化一个user_profile对象 user_profile = UserProfile() user_profile.username = user_name user_profile.email = user_name user_profile.is_active = False # 对保存到数据库的密码加密 user_profile.password = make_password(pass_word) user_profile.save() send_register_email(user_name, 'register') return render(request, 'login.html') else: return render(request, 'register.html', { 'errmsg': '两次密码输入不一致', 'register_form': register_form }) else: return render(request, 'register.html', {'register_form': register_form})
def user_register(request): all_category = Category.objects.filter(is_tab=True).all() if request.method == 'GET': return render(request, 'user_register.html') else: register_form = RegisterForm(request.POST) if register_form.is_valid(): email = register_form.cleaned_data['email'] pwd = register_form.cleaned_data['password'] nick_name = register_form.cleaned_data['nick_name'] user = UserProfile.objects.filter(username=email) if user: return render(request, 'user_register.html', {'msg': '用户名已存在'}) else: # if pwd == pwd1: new = UserProfile() new.username = email new.email = email new.nick_name = nick_name new.set_password(pwd) new.save() send_email_code(email, '1') return render(request, 'wait_start.html', { 'all_category': all_category, }) # else: # return render(request, 'user_register.html', { # 'msg': '两次密码不一致' # }) else: return render(request, 'user_register.html', {'register_form': register_form})
def post(self, request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get('email', '') users = UserProfile.objects.filter(username=user_name) if not users: password = request.POST.get('password', '') user_profile = UserProfile() user_profile.username = user_name user_profile.email = user_name user_profile.password = make_password(password) # 默认激活状态为false user_profile.is_active = False user_profile.save() # 写入欢迎注册消息 user_message = UserMessage() user_message.user = user_profile.id user_message.message = "欢迎注册Isudynet小站!! --系统自动消息" user_message.save() # 新建一个线程发送注册激活邮件 send_email_thread = SendEmailThread(email=user_name, type='register') send_email_thread.start() # 跳转到登录页面 return render(request, "login.html") else: return render(request, 'register.html', { 'msg': '用户名已经注册', 'register_form': register_form }) else: return render(request, 'register.html', {'register_form': register_form})
def register(request, **kwargs): if request.user.is_authenticated(): messages.error(request, 'Ya estas registrado') logging.error('Ya estas registrado: %s ' % request.user.username) return redirect(reverse('error')) form = RegisterForm() if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() messages.success(request, _("Bienvenido a %s" % current_site.name)) user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1']) auth_login(request, user) return redirect(reverse('home')) context = { 'form': form } c = template.RequestContext(request, context) return render_to_response('page.users.register.html', c)
def create_user(request): #If the user is trying to add info to the server, if request.method == 'POST': #Feed as arguments to RegisterForm the inputs from the user. create_user_form = RegisterForm(request.POST) #If username and password are of the right length and email is of the valid form, #And password and confirm password identical, if create_user_form.is_valid(): #Don't save the user in creation as a new user yet. new_user = create_user_form.save() pw = create_user_form.cleaned_data.get('password') new_user.set_password( pw ) new_user.save() #Then create UserProfile object from User object. new_UserProfile = UserProfile(user=new_user) #new_UserProfile.user = new_user new_UserProfile.save() #Then save. #Render a Welcome to GroupFit page if the input info is valid. #No need to customize welcome page unless we want to just switch the name: Welcome, username! return render(request, 'welcome.html') #Send an email as well. else: #If the user didn't plug in anything, create_user_form will be an empty shell? create_user_form = RegisterForm() return render(request, 'register.html', {'create_user_form': create_user_form})
def post(self, request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get('email', '') if UserProfile.objects.filter(email=user_name): return render(request, 'register.html', { 'register_form': register_form, 'msg': '用户已存在' }) pass_word = request.POST.get('password', '') re_user = UserProfile() re_user.username = user_name re_user.email = user_name re_user.password = make_password(pass_word) re_user.is_active = False re_user.save() usermessage = UserMessage() usermessage.message = "欢迎注册慕学在线网" usermessage.user = re_user usermessage.save() send_email_code.delay(user_name) return render(request, 'login.html') else: return render(request, 'register.html', {'register_form': register_form})
def post(self, request): register_form = RegisterForm() if register_form.is_valid(): user_name = request.POST.get("email", "") if UserProfile.objects.filter(email=user_name): return render(request, "register.html", { 'register_form': register_form, "msg": "User has been exist!" }) pass_word = request.POST.get("password", "") user_profile = UserProfile() user_profile.username = user_name user_profile.email = user_name user_profile.password = make_password(pass_word) user_profile.save() #写入欢迎注册消息 user_message = UserMessage() user_message.user = user_profile user_message.message = "Welcome to join us" user_message.save() send_register_email(user_name, "register") return render(request, "login.html") else: return render(request, "register.html")
def register_wholesale(request): """Регистрация оптового покупателя""" if request.POST: form = RegisterForm(request.POST) company_form = CompanyForm(request.POST) if form.is_valid() and company_form.is_valid(): instance = form.save(commit=False) instance.set_password(form.cleaned_data["password"]) instance.status = User.STATUS_WHOLESALE instance.save() instance = authenticate(email=instance.email, password=form.cleaned_data["password"]) user_login(request, instance) company = company_form.save(commit=False) company.user = request.user company.save() return redirect(reverse("users.auth.register.completed")) else: form = RegisterForm() company_form = CompanyForm() context = {"form": form, "company_form": company_form} return render(request, "users/auth/register_wholesale.html", context)
def post(self, request): register_form = RegisterForm(request.POST) if register_form.is_valid(): email = register_form.cleaned_data.get("email") # 这里需要判断用户是否已经存在 password = register_form.cleaned_data.get("password") if User.objects.filter(email=email).first(): # 表示该用户名已经存在 return render(request, "register.html", { "register_form": register_form, "msg": u"用户名已存在" }) else: # 向用户发送激活邮件 send_status = send_email(email, "register") if send_status: user = User() user.username = email user.email = email user.password = make_password(password) # 加密密码存入数据库 user.is_active = False # 用户注册时默认为未激活,需要通过邮箱连接进行激活 user.save() return render(request, "login.html") else: # 邮件发送失败 return render(request, "register.html", {"msg": u"邮件发送失败,请重试"}) else: # 如果表单校验没通过,将表单信息返回,页面进行信息显示 return render(request, 'register.html', {"register_form": register_form})
def post(self, request): ''' 1 get value 2 check value 3 sava value to mysql/redis 4 give info custom :param request: :return: ''' json_data = request.body if not json_data: return to_json_data(errno=Code.PARAMERR, errmsg=error_map[Code.PARAMERR]) # 将json转化为dict dict_data = json.loads(json_data) #.decode('utf8') 清除解码 form = RegisterForm(data=dict_data) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') mobile = form.cleaned_data.get('mobile') user = User.objects.create_user(username=username, password=password, mobile=mobile) login(request, user) return to_json_data(errmsg="恭喜您,注册成功!") else: # 定义一个错误信息列表 err_msg_list = [] for item in form.errors.get_json_data().values(): err_msg_list.append(item[0].get('message')) err_msg_str = '/'.join(err_msg_list) return to_json_data(errno=Code.PARAMERR, errmsg=err_msg_str)
def post(self, request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get('email', '') if UserProfile.objects.filter(email=user_name): return render(request, 'register.html', { 'register_form': register_form, 'msg': '用户已经存在' }) pass_word = request.POST.get('password', '') user_profile = UserProfile() user_profile.username = user_name user_profile.email = user_name user_profile.is_active = False user_profile.password = make_password(pass_word) user_profile.save() #写入欢迎注册的消息进我的消息 user_message = UserMessage() user_message.user = user_profile.id user_message.message = '欢迎注册慕学网' user_message.save() send_register_email(user_name, 'register') return render(request, 'send_success.html') else: return render(request, 'register.html', {'register_form': register_form})
def post(self, request): title = "注册" if request.user.is_authenticated: messages.add_message(request, messages.INFO, '用户已登录,请登出后再访问') return redirect(reverse('index')) register_form = RegisterForm(request.POST) if register_form.is_valid(): email = request.POST.get('email', None) username = request.POST.get('username', None) # 如果用户已存在,则提示错误信息 if UserProfile.objects.filter(email=email): messages.add_message(request, messages.WARNING, '用户已存在', extra_tags='warning') return render(request, 'sign-up.html', {'register_form': register_form, 'title': title}) password1 = request.POST.get('password1', None) password2 = request.POST.get('password2', None) if password1 != password2: messages.add_message(request, messages.ERROR, '密码不一致!', extra_tags='danger') return render(request, 'sign-up.html', {'register_form': register_form, 'title': title}) # 实例化一个user_profile对象 user_profile = UserProfile() user_profile.username = username user_profile.email = email user_profile.is_active = False # 对保存到数据库的密码加密 user_profile.password = make_password(password2) user_profile.save() send_register_email(email, 'register') messages.add_message(request, messages.SUCCESS, '邮件已发送,请查收') return redirect(reverse('login')) else: messages.add_message(request, messages.ERROR, '注册失败,请重新注册', extra_tags='danger') return render(request, 'sign-up.html', {'register_form': register_form, 'title': title})
def post(self, request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get("email", "") if UserProfile.objects.filter(email=user_name): return render( request, "register.html", { "register_form": register_form, "msg": "The account already existed in the system" }) pass_word = request.POST.get("password", "") user_profile = UserProfile() user_profile.username = user_name user_profile.email = user_name user_profile.is_active = False user_profile.password = make_password(pass_word) user_profile.save() # Send the Welcome Message user_message = UserMessage() user_message.user = user_profile.id user_message.message = "Welcome to the Mooc Online" user_message.save() send_register_email(user_name, "register") return render(request, "login.html") else: return render(request, "register.html", {"register_form": register_form})
def post(self, request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get('email', '') if UserProfile.objects.filter(email=user_name): return render(request, 'register.html', { 'register_form': register_form, 'msg': '账号已存在' }) pass_word = request.POST.get('password', '') user_profile = UserProfile() user_profile.username = user_name user_profile.email = user_name user_profile.password = make_password(pass_word) user_profile.is_active = False user_profile.save() # 想用户发送注册消息 UserMessage(user=user_profile, message='欢迎注册').save() send_register_email(user_name) return render(request, 'login.html') else: return render(request, 'register.html', {'register_form': register_form})
def register(request): url='/register' sub='Register' if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): nm = form.cleaned_data['name'] gender = form.cleaned_data['gender'] reg_no = form.cleaned_data['reg_no'] email = form.cleaned_data['email'] pwd = form.cleaned_data['password'] x = OjUser.objects.filter(username=email) if x: return HttpResponse('Email exists') l = OjUser.objects.create( username = reg_no, first_name = nm, email = email, gender = gender, reg_no = reg_no, ) l.set_password(pwd) l.save() text="Registered Successfully" return render(request,"index.html",{'text':text}) else: return render(request,'register.html',{'form':form,'url':url,'sub':sub}) else: form = RegisterForm() return render(request,'register.html',{'form':form,'url':'/register','sub':'Register'})
def register_view(request): """ Register a new user """ # Check if the user is authenticated if request.user.is_authenticated(): # User is already authenticated return render(request, 'users/register/already_logged_in.html') else: register_form = RegisterForm(request.POST or None) if request.method == 'POST': # Form data was submitted if register_form.is_valid(): # Form data is valid # Create the user with transaction.atomic(): user = User.objects.create_user( register_form.cleaned_data['username'], "N/A", # we don't deal with email addresses register_form.cleaned_data['password']) PastebinUser.create_user(user) # TODO: Show a different message if the registration fails return render(request, 'users/register/register_success.html') # Show the registration page return render(request, "users/register/register.html", {"form": register_form})
def post(self, request): register_form = RegisterForm(request.POST) field_errors = register_form.errors.as_json() success = False email_error = None success_message = None if register_form.is_valid(): user = register_form.save(commit=False) user.is_active = False try: send_mail(request, user) user.save() success = True success_message = 'На указанную вами электронную почту выслано письмо с инструкциями для подтверждения учётной записи' except Exception as e: email_error = 'Ошибка! Перезагрузите страницу и попробуйте заново.' print(e) context = { 'success': success, 'errors': field_errors, 'email_error': email_error, 'success_message': success_message } return JsonResponse(context)
def register(request): form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) # Generate activation key for user account activation_key = generate_activation_key(user.email) user.activation_key = activation_key user.is_active = False user.save() send_email.delay('mail/confirmation', {'link': activation_key}, u'\u2713 ' + _("Welcome to Prestashop-Sync Service"), [user.email]) return HttpResponse( simplejson.dumps({ 'response': _("Email with a confirmation link has been sent"), 'result': 'success' })) else: response = {} for k in form.errors: response[k] = form.errors[k][0] return HttpResponse( simplejson.dumps({ 'response': response, 'result': 'error' }))
def post(self, request): register_form = RegisterForm(request.POST) if register_form.is_valid(): email = request.POST.get("email", "") if UserProfile.objects.filter(email=email): return render(request, "login.html", { "register_form": register_form, "msg": "用户已存在" }) pass_word = request.POST.get("password", "") user_profile = UserProfile() user_profile.email = email user_profile.password = make_password(pass_word) user_profile.is_active = False user_profile.save() # 写入欢迎注册信息 user_message = UserMessage() user_message.user = user_profile.id user_message.message = '欢迎注册' user_message.save() send_register_email(email, "register") return render(request, "login.html") else: return render(request, "register.html", {"register_form": register_form})
def sbregister(request): errors_msg = [] if request.method=="POST": form = RegisterForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] rptpwd = request.POST['rptpwd'] sbid = request.POST['idnum'] name = request.POST['name'] teleph = request.POST['teleph'] address = request.POST['address'] user = User.objects.create_user(username=username, password=password) user.save() profile = SBProfile(user=user, sbid=sbid, name=name, teleph=teleph, address=address, flag=1) profile.save() #login the user in user = authenticate(username=username, password=password) login(request, user) return redirect('users.views.home') else: errors_msg.append('Input invalid!') else: form = RegisterForm() return render_to_response('users/register.html', locals(), context_instance=RequestContext(request) )
def user_register(request): if request.method == "GET": form = RegisterForm() return render(request, 'users/signup.html', {'form': form}) else: form = RegisterForm(request.POST) if form.is_valid(): pdb.set_trace() auth_user = User.objects.create( username=form.cleaned_data['email'], password=form.cleaned_data['password'], email=form.cleaned_data['email'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name']) BMNUser.objects.create( user=auth_user, birth_date=jdate_to_date(form.cleaned_data['birthDate']), birth_country=form.cleaned_data['birth_country'], residence_country=form.cleaned_data['residence_country'], education=form.cleaned_data['education'], university=form.cleaned_data['university'], field=Field.objects.get(title=form.cleaned_data['field']), phone=form.cleaned_data['phone'], mobile=form.cleaned_data['mobile']) return HttpResponseRedirect('/users/?msg=success') return render(request, 'users/signup.html', {'form': form})
def post(self, request): # 获取前段的数据 register_form = RegisterForm(request.POST) # 验证表单是不是合法 if register_form.is_valid(): email = request.POST.get("email", "") if UserInfo.objects.filter(email=email): return render(request, "register.html", { "register_form": register_form, "msg": "用户已经存在!"}) pass_word = request.POST.get("password", "") # 实例化UserInfo字段 user_profile = UserInfo() user_profile.username = email user_profile.email = email user_profile.is_active = False user_profile.password = make_password(pass_word) user_profile.save() # 发送邮箱 send_register_email(email, 'register') return HttpResponseRedirect(reverse("login")) else: return render(request, "register.html", {"register_form": register_form})
def register_view(request): """ Register a new user """ # Check if the user is authenticated if request.user.is_authenticated(): # User is already authenticated return render(request, 'users/register/already_logged_in.html') else: register_form = RegisterForm(request.POST or None) if request.method == 'POST': # Form data was submitted if register_form.is_valid(): # Form data is valid # Create the user with transaction.atomic(): user = User.objects.create_user(register_form.cleaned_data['username'], "N/A", # we don't deal with email addresses register_form.cleaned_data['password']) PastebinUser.create_user(user) # TODO: Show a different message if the registration fails return render(request, 'users/register/register_success.html') # Show the registration page return render(request, "users/register/register.html", { "form": register_form })
def register(request): if request.user.is_authenticated: return HttpResponseRedirect(reverse("users:hello")) if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] raw_password = form.cleaned_data['raw_password'] user = UserProfile.objects.create_user( username=username, email=email, password=raw_password, ) user.save() login(request, user) return HttpResponseRedirect(reverse("users:hello")) else: form = RegisterForm() return render( request, 'utils/form.html', { 'url_form': reverse("users:register"), 'title': "Inscription", 'form': form, })
def post(self, request): # 1. 获取参数 json_data = request.body # byte str if not json_data: return to_json_data(errno=Code.PARAMERR, errmsg=error_map[Code.PARAMERR]) dict_data = json.loads(json_data.decode('utf8')) # 2. 校验参数 form = RegisterForm(data=dict_data) if form.is_valid(): # 3. 存入数据到数据 username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') mobile = form.cleaned_data.get('mobile') user = Users.objects.create_user(username=username, password=password, mobile=mobile) login(request, user) # 4. 返回给前端 return to_json_data(errmsg='恭喜您,注册成功!') else: # 定义一个错误信息列表 err_msg_list = [] for item in form.errors.get_json_data().values(): err_msg_list.append(item[0].get('message')) # print(item[0].get('message')) # for test err_msg_str = '/'.join(err_msg_list) # 拼接错误信息为一个字符串 return to_json_data(errno=Code.PARAMERR, errmsg=err_msg_str)
def post(self, request): register_form = RegisterForm(request.POST) # print(register_form,"*"*100) if register_form.is_valid(): user_name = request.POST.get("email", "") if UserProfile.objects.filter(email=user_name): return render(request, 'register.html', { "register_form": register_form, "msg": "用户已经存在" }) pass_word = request.POST.get("password", "") user_profile = UserProfile() user_profile.username = user_name user_profile.email = user_name user_profile.is_active = False user_profile.password = make_password(pass_word) user_profile.save() user_message = UserMessage() user_message.user = user_profile.id user_message.message = '欢迎注册慕学在线网' user_message.save() send_register_email(user_name, "register") return render(request, 'login.html') else: return render(request, 'register.html', {"register_form": register_form})
def register(request): # 获取跳转地址 redirect_to = request.POST.get('next', request.GET.get('next', '')) # 判断是什么提交方法 form = RegisterForm() if request.method == 'POST': # 首先使用提交的数据生成form form = RegisterForm(request.POST, request.FILES) # 判断数据是否合法 if form.is_valid(): user = form.save() # 返回登录,并提示注册成功,请登录 messages.success(request, '提示注册成功,请登录!') # 判断redirect_to是否存在。 if redirect_to: login(request, user) return redirect(redirect_to) else: # 重定向到login return redirect(reverse('login')) else: return render(request, 'users/register.html', { 'form': form, 'next': redirect_to })
def register(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = RegisterForm(request.POST) print("there is a request") # check whether it's valid: if form.is_valid(): user = form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save() blog_id = Blog.objects.count() + 1 user = User.objects.get(username=request.POST.get('username')) blog = Blog(num=blog_id, writer=user, isDefault=True) blog.save() # form.save() response_data['status'] = 0 return HttpResponse(json.dumps(response_data), content_type="application/json") else: response_data['status'] = -1 response_data['message'] = list( form.errors.keys())[0] + ": " + form.errors[list( form.errors.keys())[0]][0] print( HttpResponse(json.dumps(response_data), content_type="application/json")) return HttpResponse(json.dumps(response_data), content_type="application/json") else: return HttpResponse(json.dumps(response_data), content_type="application/json")
def register(request): c = get_common_context(request) auth_form = AuthenticationForm() register_form = RegisterForm() c['auth_form'] = auth_form c['register_form'] = register_form if request.method == "POST": if request.POST['action'] == 'auth': auth_form = AuthenticationForm(request.POST) if auth_form.is_valid(): pass username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) if 'is_order' in request.session: del request.session['is_order'] return HttpResponseRedirect('/order/2/') return HttpResponseRedirect('/') else: c['auth_error'] = u'Ваш аккаунт не активирован.' else: c['auth_error'] = u'Неверный логин или пароль.' c['auth_form'] = auth_form elif request.POST['action'] == 'register': from django.forms.util import ErrorList register_form = RegisterForm(request.POST) if register_form.is_valid(): p1 = register_form.data.get('password_1') p2 = register_form.data.get('password_2') error = False if p1 != p2: register_form._errors["password_2"] = ErrorList([u'Пароли не совпадают.']) error = True if len(User.objects.filter(username=register_form.data.get('email'))): register_form._errors["email"] = ErrorList([u'Такой емейл уже зарегистрирован.']) error = True if not error: u = User(username=register_form.data.get('email'), email=register_form.data.get('email')) u.set_password(register_form.data.get('password_1')) u.save() p = u.get_profile() p.fio = register_form.data.get('fio') p.save() user = auth.authenticate(username=register_form.data.get('email'), password=register_form.data.get('password_1')) auth.login(request, user) if 'is_order' in request.session: del request.session['is_order'] return HttpResponseRedirect('/order/2/') else: return HttpResponseRedirect('/') c['register_form'] = register_form return render_to_response('register.html', c, context_instance=RequestContext(request))
def post(self, request): form = RegisterForm(request.POST) if form.is_valid(): user = form.save() return render_to_response('register_success.html', RequestContext(request)) #return HttpResponseRedirect('../../coins/') else: return self.registerPage(request, form)
def post(self, request, *args, **kwargs): form = RegisterForm(request.POST, request.FILES) if form.is_valid(): user = form.save() # send_validation_code.apply_async(kwargs={'pk': user.id }) messages.info(request, _('You were successfully registered.' 'Validation link was sent to you'), extra_tags='register') return HttpResponseRedirect(reverse('users:code_sent')) return self.render_to_response({'form': form})
def testEmailAlreadyRegistered(self): form_data = { 'username': self.CREATED_USER_USERNAME, 'email': self.USER_EMAIL, 'password': self.USER_PASSWORD, 'password_confirm': self.USER_PASSWORD, } form = RegisterForm(form_data) self.assertFalse(form.is_valid()) self.assertIn('email', form.errors)
def handle_register(request): """Handle to help registration.""" if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): RegistrationProfile.objects.create_inactive_user( form.cleaned_data['username'], form.cleaned_data['password'], form.cleaned_data['email']) return form return RegisterForm()
def register(request): form = RegisterForm() if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() mail_welcome(user) authenticate(request, user) util.add_success(request, "Welcome to %s" % ConfigData.get_configdata('SITE_NAME')) return redirect(reverse('admin_dashboard')) c = template.RequestContext(request, locals()) return render_to_response('users_register.html', c)
def register(request): if (request.method=='POST'): form = RegisterForm(data=request.POST) if(form.is_valid()): #check captcha first session = UserSession.objects.get(session_key=request.session.session_key) print("session captcha: "+session.captcha) print("form captcha: "+form.cleaned_data["captcha"]) if(session.captcha != form.cleaned_data["captcha"]): messages.add_message(request, messages.ERROR, _('The captcha was entered wrong.')) else: referer = request.META.get('HTTP_REFERER') user = form.save() user.groups.add(Group.objects.get(name='User')) user.is_active = False user.set_password(user.password) user.save() import uuid lv_uuid = str(uuid.uuid1())[0:30] message = """<html> <body> <h3>Registration at """+get_current_site(request).name+"""</h3><br/> <p> Please click the following link to end your registration. </p> <p> <a href='https://"""+get_current_site(request).domain+""""/user/activate/"""+lv_uuid+"""/'>Activation Link</a> </p> </html> """ send_mail('Registration at '+get_current_site(request).name, 'Hello '+user.username+ '\n\nPlease click the following the link to end your registration.\n\n'+ 'Activation Link: https://'+get_current_site(request).domain+'/user/activate/'+lv_uuid+'/', settings.SYSTEMMAIL, [user.email], fail_silently=False,html_message=message) profile = UserProfile() profile.user = user profile.posts = 0 profile.threads = 0 profile.activate = lv_uuid profile.theme = Theme.objects.get(default=True) profile.banned = False profile.save() messages.add_message(request, messages.INFO, _('User successful registrated.')) #return redirect(urlresolvers.reverse('board.views.index')) return redirect(referer) else: form = RegisterForm() f_profile = ProfileForm() return render_to_response('user/register.html',{'form':form},context_instance=RequestContext(request))
def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): # Validate fields if form.cleaned_data['password1'] == form.cleaned_data['password2']: password = form.cleaned_data['password1'] else: return render_to_response('users/register.html', {'form':form, 'invalid':"Passwords mismatched"}, context_instance=RequestContext(request)) # Django User Data username = form.cleaned_data['username'] email = form.cleaned_data['email'] # User Profile Data birthday = form.cleaned_data['birthday'] nickname = form.cleaned_data['nickname'] gender = form.cleaned_data['gender'] interests = form.cleaned_data['interests'] # Save User to database newuser = User(username=username,email=email) newuser.set_password(password) newuser.save() # save user profile to database user = User.objects.get(username=username) newUserProfile = UserProfile.objects.create(user=user, birthday=birthday, nickname=nickname, gender=gender, interests=interests) newUserProfile.save() return HttpResponseRedirect('/login/') else: return render_to_response('users/register.html', {'form':form, 'invalid':"Some required fields have not been filled"}, context_instance=RequestContext(request)) else: form = RegisterForm() return render_to_response('users/register.html', context_instance=RequestContext(request))
def handle_register(request): """Handle to help registration.""" if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] new_user = User.objects.create_user(username, email, password) new_user.save() Profile.objects.create(user=new_user) return form return RegisterForm()
def testPasswordsDoNotMatch(self): form_data = { 'username': self.CREATED_USER_USERNAME, 'email': self.CREATED_USER_EMAIL, 'password': self.USER_PASSWORD, 'password_confirm': "oops123", } form = RegisterForm(form_data) self.assertFalse(form.is_valid()) self.assertIn('__all__', form.errors) self.assertEquals(len(form.errors['__all__']), 1) (error,) = form.errors['__all__'] self.assertIn('Password', error) self.assertIn('not match', error)
class Register(View): template_name = 'users/register.html' def render(self, request): context = { 'form': self.form} return render(request, self.template_name, context) def get(self, request): self.form = RegisterForm() return self.render(request) def get_user(self): email = self.form.cleaned_data.get('email') username = self.form.cleaned_data.get('username') password = self.form.cleaned_data.get('password1') user = User.objects.create_user(username, email, password) user.is_active = False user.save() return user def send_conf_mail(self): template = 'users/email/confirm_email' conf_loc_url = reverse('users:activate', args=(self.confirm.code,)) conf_url = settings.SITE_HOST + conf_loc_url to = [self.user.email] subject = 'JudgeSystem account confirmation' context = Context({ 'username': self.user.username, 'conf_url': conf_url}) send_email(template, context, subject, to) def post(self, request): self.form = RegisterForm(request.POST) if not self.form.is_valid(): return self.render(request) self.user = self.get_user() self.confirm = Confirmation(user = self.user) self.confirm.save() self.send_conf_mail() messageText = messages.success(request, 'You have been successfuly \ registered. Check your e-mail for further instructions.') return redirect(reverse('judge:problem_list'))
def post(self, request): if request.user.is_authenticated(): return redirect('index') postData = request.POST regForm = RegisterForm(postData) if regForm.is_valid(): cleanedData = regForm.cleaned_data username = cleanedData['username'] email = cleanedData['email'] password = cleanedData['password1'] firstName = cleanedData['first_name'] lastName = cleanedData['last_name'] timezone = cleanedData['timezone'] gender = cleanedData['gender'] with transaction.atomic(): newUser = User.objects.create_user( username=username, password=password, email=email, first_name=firstName, last_name=lastName, ) newProfile = UserProfile( user=newUser, timezone=timezone, gender=gender, ) newProfile.save() user = authenticate(username=username, password=password) login(request, user) if 'next' in postData: return redirect(postData['next']) else: return redirect('users_profile', username=username) else: context = { 'regForm' : regForm, } return render(request, self.template_name, context)
def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): try: form.save() messages.add_message(request, messages.SUCCESS, "Your registration succed. We've sent a verification link to your email address.") return redirect(reverse('login')) except: pass else: form = RegisterForm() data = {'form': form} return render(request, 'registration/register.html', data)
def register(request): """Register a new user.""" if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) # TODO: Send registration email for confirmation. user.is_active = True user.set_password(form['password'].data) user.save() return login(request) else: # request.method == 'GET' form = RegisterForm() return jingo.render(request, 'users/register.html', {'form': form})
def register_user(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): form.save() data = form.cleaned_data user = authenticate(username=data['username'], password=data['password']) return HttpResponseRedirect('/registerSucces/') else: form = RegisterForm() return render(request, 'register.html', {'form':form})
def register(request): """ Register page. """ if request.user.is_authenticated(): return redirect('index') form = RegisterForm(request.POST or None) if form.is_valid(): try: user = form.register(request) except ValidationError as err: form._errors['__all__'] = err.messages else: return redirect('index') return {'form': form}
def register(request): d = {} d["url"] = "/register" d["sub"] = "Register" if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): u = form.save(commit = False) password = form.cleaned_data["password"] u.set_password(password) u.save() return HttpResponseRedirect("/") else: d["form"] =form return render(request,"register.html",d) else: d["form"] = RegisterForm() return render(request,"register.html",d)
def register(request): ''' Función que permite el registro de un usuario :param request: Request enviado por el cliente :return: renderizado del template con la inforamción del contexto ''' error_messages = [] if request.method == 'POST': # Si es una petición POST form = RegisterForm(request.POST) # Llenamos el formu if form.is_valid(): email = form.cleaned_data.get('email') username = form.cleaned_data.get('user') password = form.cleaned_data.get('password') user = User(username=username, email=email) user.set_password(password) user.is_active = False user.save() if user is None: error_messages.append("Nombre de Usuario o contraseña incorrectos") else: userNonce = UsersNonce() userNonce.Owner = user userNonce.Code = user.id userNonce.save() message = mail.EmailMessage(sender="*****@*****.**", subject="Cuenta creada") message.to = email message.body = "Cuenta creada accede a https://invoicecloud-1143.appspot.com/ac/" + str( user.id) + " \n \n Para la activación del usuario" + "\n\n\n Gracias \n El equipo de InvoiceCloud" message.send() context = { 'username': username } return render(request, 'users/register.html', context) else: # Si es una petición GET form = RegisterForm() # Creamos el formulario vació, generará los campos y los permitirá añadir de forma dinamica # al template context = { 'errors': error_messages, 'register_form': form } return render(request, 'users/register.html', context)
def register(request): form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) # Generate activation key for user account activation_key = generate_activation_key(user.email) user.activation_key = activation_key user.is_active = False user.save() send_email.delay('mail/confirmation', {'link': activation_key}, u'\u2713 ' + _("Welcome to Prestashop-Sync Service"), [user.email]) return HttpResponse(simplejson.dumps({'response': _("Email with a confirmation link has been sent"), 'result': 'success'})) else: response = {} for k in form.errors: response[k] = form.errors[k][0] return HttpResponse(simplejson.dumps({'response': response, 'result': 'error'}))