def new_member(request): context = {'new_member': True} if request.method == 'GET': form = UserAdminCreationForm() context['form'] = form return render(request, 'accounts/register.html', context) else: form = UserAdminCreationForm(request.POST) context['form'] = form if form.is_valid(): user = User() user.username = form.cleaned_data['username'] user.name = form.cleaned_data['name'] user.email = form.cleaned_data['email'] user.telefone = form.cleaned_data['telefone'] user.cpf = form.cleaned_data['cpf'] user.logradouro = form.cleaned_data['logradouro'] user.numero = form.cleaned_data['numero'] user.cep = form.cleaned_data['cep'] user.complemento = form.cleaned_data['complemento'] user.bairro = form.cleaned_data['bairro'] user.estado = form.cleaned_data['estado'] user.is_staff = True user.set_password(form.cleaned_data['password1']) user.save() messages.success(request, 'Novo membro da equipe criado com sucesso!') url = resolve_url('/area_administrativa/index') return HttpResponseRedirect(url) else: return render(request, 'accounts/register.html', context)
def test_miss_data_field(self): print('miss_data_field') miss_data = self.user.copy() miss_data['email'] = '' self.assertFalse(UserAdminCreationForm(miss_data).is_valid()) miss_data = self.user.copy() miss_data['confirm'] = '' self.assertFalse(UserAdminCreationForm(miss_data).is_valid()) miss_data = self.user.copy() miss_data['initial'] = '' self.assertFalse(UserAdminCreationForm(miss_data).is_valid())
def register(request): form = UserAdminCreationForm() if request.method == 'POST': form = UserAdminCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') return render(request, 'accounts/register.html', {'form': form})
def register(req): form = UserAdminCreationForm() if req.method == 'POST': form = UserAdminCreationForm(req.POST) if form.is_valid(): form.save() return redirect('register') return render(req, 'register.html', {'form': form})
def cadastrar(request, token, username): hotp = pyotp.HOTP('base32secret3232') crip = Token.objects.get(username=username) if not hotp.verify(token, crip.token): messages.error( request, 'Token invalido, não foi possível fazer a confirmação de email. Tente novamente!' ) return redirect('index') else: form = UserAdminCreationForm() if request.method == 'POST': form = UserAdminCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = username user.email = username + '@inf.ufsm.br' user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) messages.success(request, 'Usuario criado com sucesso') return redirect('accounts:index') else: messages.error(request, 'Dados invalidos') return render(request, 'accounts/cadastro.html', { 'form': form, 'token': token, 'username': username })
def activate_account(request): if len(request.GET) != 0: id_coach = request.GET.get('c_id') id_ath = request.GET.get('ath_id') token = request.GET.get('token') coach = get_object_or_404(Coach, id = id_coach) user = coach.user ath = get_object_or_404(Athlete, id = id_ath) token_generator = PasswordResetTokenGenerator() is_valid = token_generator.check_token(user, token) if is_valid: is_valid = Token.objects.filter(athlete=ath, token=token).exists() if is_valid: form = UserAdminCreationForm() form.fields['email'].help_text = None form.fields['password1'].help_text = None form.fields['password2'].help_text = None if request.method == "POST": # Añadimos los datos recibidos al formulario form = UserAdminCreationForm(data=request.POST) # Si el formulario es válido... if form.is_valid(): user = form.save() ath.user = user ath.save() token = Token.objects.get(athlete=ath, token=token) token.delete() if user is not None: # Hacemos el login manualmente # do_login(request, user) # Y le redireccionamos a la portada return redirect('../../accounts/login') # Si llegamos al final renderizamos el formulario return render(request, 'boxApp/activate_account.html', {'form': form}) return redirect('../../')
def create_user(request): if request.user.is_authenticated: # Creamos el formulario de autenticación vacío form = UserAdminCreationForm() form.fields['email'].help_text = None form.fields['password1'].help_text = None form.fields['password2'].help_text = None if request.method == "POST": # Añadimos los datos recibidos al formulario form = UserAdminCreationForm(data=request.POST) # Si el formulario es válido... if form.is_valid(): # Obtenemos el entrenador que va a realizar el alta coach = get_object_or_404(Coach, user = request.user) # Obtenemos al box que pertenece box = coach.box # Creamos la nueva cuenta de usuario user = form.save() # Creamos el atleta asociado al usuario ath = Athlete(user = user, box = box, user_name= "prueba", name = "prueba", last_name= "prueba") ath.save() # Si el usuario y el atleta se crean correctamente if user is not None and ath is not None: # Hacemos el login manualmente # do_login(request, user) # Y le redireccionamos a la portada return redirect('../../box') # Si llegamos al final renderizamos el formulario return render(request, "boxApp/create_user.html", {'form': form}) return redirect('../../accounts/login')
def test_form_email_char_field(self): form = UserAdminCreationForm() self.assertTrue(form.fields['email'].label == None or form.fields['email'].label == 'Email address')
def test_with_no_email(self): data = {'email': '', 'password1': 'password1', 'password2': 'password2'} form = UserAdminCreationForm(data) self.assertFalse(form.is_valid())
def test_existing_user__admin_create_form(self): print('existing_user') User.objects.create_user(**self.data['user']) form = UserAdminCreationForm(data=self.data) self.assertFalse(form.is_valid())
def test_UserAdminCreationForm(self): print('UserAdminCreationForm') form = UserAdminCreationForm(data=self.user) self.assertTrue(form.is_valid()) form.save() self.assertTrue(User.objects.filter(slug='admin-kalonji').exists())
def test_with_unmatching_passwords(self): data = {'email': '*****@*****.**', 'password1': 'password1', 'password2': 'password2'} form = UserAdminCreationForm(data) self.assertFalse(form.is_valid())
def test_form_name_char_field(self): form = UserAdminCreationForm() self.assertTrue(form.fields['name'].label == None or form.fields['name'].label == 'Name')
def test_form_password2_char_field(self): form = UserAdminCreationForm() self.assertTrue( form.fields['password2'].label == None or form.fields['password2'].label == 'Confirmação de senha')
def test_form_password1_char_field(self): form = UserAdminCreationForm() self.assertTrue(form.fields['password1'].label == None or form.fields['password1'].label == 'Senha')
def question(request): description = Description.objects.all().last() inputs = {} questoes = Question.objects.all() form = UserAdminCreationForm() context = { 'questoes': questoes, 'form': form, 'description': description, } if request.method == "POST": form = UserAdminCreationForm(request.POST or None) if not Control.objects.filter(identificador=request.POST.get('email')).exists(): if form.is_valid(): user = form.save() dados = Dados() #Capturando valores dos inputs (ID DA RESPOSTA: VALOR DA PERGUNTA) for questao in questoes: inputs[questao.id] = request.POST.get(str(questao.id)) #Funções para calculo das médias de respostas de cada segmento media_financeiro_estrutural = form.media_financeiro_estrutural(inputs) media_marketing = form.media_marketing(inputs) media_pessoas = form.media_pessoas_processos(inputs) #Calculos dos niveis (determinar em que nivel a empresa está em um segmento) if(media_financeiro_estrutural<=3.0): nivelA = 1 elif(media_financeiro_estrutural>3.0 and media_financeiro_estrutural<=7.0): nivelA = 2 else: nivelA = 3 if(media_marketing<=3.0): nivelB = 1 elif(media_marketing>3.0 and media_marketing<=7.0): nivelB = 2 else: nivelB = 3 if(media_pessoas<=3.0): nivelC = 1 elif(media_pessoas>3.0 and media_pessoas<=7.0): nivelC = 2 else: nivelC = 3 #Salvando médias e níveis necessários na tabela de Dados form.atualizar_media_and_niveis(dados,media_financeiro_estrutural,media_marketing,media_pessoas,nivelA,nivelB,nivelC, user.pk, user.email, inputs) dados.save() #Atualizando contadores na tabela de contadores form.atualizar_contadores(nivelA, nivelB, nivelC, dados) cont_usuarios = User.objects.all().count() #Capturar os relatorios a partir do segmento e do nivel (3 relatórios sempre!) rel1 = Relatorio.objects.filter(nivel=nivelA).filter(segmentos='Financeiro/Estrutural') rel2 = Relatorio.objects.filter(nivel=nivelB).filter(segmentos='Marketing') rel3 = Relatorio.objects.filter(nivel=nivelC).filter(segmentos='Pessoas/Processos') for i in rel1: relatorioA = i.save() print(i) for j in rel2: relatorioB = j.save() print(j) for k in rel3: relatorioC = k.save() print(k) usuarios = User.objects.all() num = Contadores.objects.filter(pk=1).first() context = { 'relatorio1': rel1, 'relatorio2': rel2, 'relatorio3': rel3, 'nivelA': nivelA, 'nivelB': nivelB, 'nivelC': nivelC, 'mediaA': media_financeiro_estrutural, 'mediaB': media_marketing, 'mediaC': media_pessoas, 'usuario': usuarios, 'email': user.email, 'mediaAint': int(media_financeiro_estrutural), 'mediaBint': int(media_marketing), 'mediaCint': int(media_pessoas), 'inputs': inputs, 'cont_usuarios': cont_usuarios, 'num': num, } #Ao enviar uma resposta, pegamos o ID do usuário que a enviou #controle = Control() #controle.identificador = user.email #controle.save() #Enviar e-mail com relatório #form.send_email(user.email) #Logando o usuario recém-cadastrado, apenas para manter o template diagnostico privado logger = authenticate(email=user.email) if logger is not None: if logger.is_active: login(request, logger) form = UserAdminCreationForm() return render(request, 'diagnostico/relatorio.html', context) else: messages.error(request, 'Formulário inválido!') form = UserAdminCreationForm() return render(request, 'sitio/error.html', context) else: return render(request, 'sitio/error.html', context) return render(request, 'sitio/base.html', context)
def test_with_valid_data(self): data = {'email': '*****@*****.**', 'password1': 'password1', 'password2': 'password1'} form = UserAdminCreationForm(data) self.assertTrue(form.is_valid())