def register(request): if request.method == "GET": initial_values = {} if request.user is not None and not request.user.is_anonymous: initial_values['username'] = request.user.username initial_values['email'] = request.user.email return render(request, "user/register.html", {"form": CustomUserCreationForm(initial=initial_values)}) elif request.method == "POST": form = CustomUserCreationForm(request.POST) form.fields['username'].widget.render_value = True if form.is_valid(): user = form.save() else: messages.add_message( request, messages.ERROR, "Les données sont invalides." " Veuillez saisir à nouveau les " "identifiants.") return render(request, 'user/register.html', {'form': form}) auth_login(request, user) url_reverse = reverse("dashboard") return redirect(url_reverse)
def test_regForm_wrong_email(self): """ Pb email incorrect :return: false """ data = self.user_register_wrong_email form = CustomUserCreationForm(data) is_valid = form.is_valid() self.assertFalse(is_valid)
def test_regForm_is_valid(self): """ data correct :return: true """ data = self.user_register form = CustomUserCreationForm(data) is_valid = form.is_valid() self.assertTrue(is_valid)
def test_if_form_is_not_valid_with_no_email_input(self): """Test if form is not valid with no email input.""" form = CustomUserCreationForm( data={ "email": "", "username": "******", "password1": "pwdCOMPLEX@123", "password2": "pwdCOMPLEX@123", }) self.assertFalse(form.is_valid())
def test_if_form_is_valid_with_corrects_inputs(self): """Test if form is valid with corrects inputs.""" form = CustomUserCreationForm( data={ "email": "*****@*****.**", "username": "******", "password1": "pwdCOMPLEX@123", "password2": "pwdCOMPLEX@123", }) self.assertTrue(form.is_valid())
def test_logForm_is_valid(self): data = self.user_register form1 = CustomUserCreationForm(data) is_valid1 = form1.is_valid() self.assertTrue(is_valid1) # User enregistré avec bon login form1.save() data = self.user_login form2 = CustomAuthenticationForm(None, data=data) is_valid2 = form2 is not None and form2.is_valid() self.assertTrue(is_valid2)
def generate_data(request): msg_users = "Created users: " msg_auctions = "Created auctions: " for i in range(100): i_str = str(i) # CREATE USERS user_info = { "username": "******" + i_str, "password": "******", "email": "testUser" + i_str + "@mail.com" } form = CustomUserCreationForm(user_info) if form.is_valid(): new_user = form.save() msg_users = msg_users + new_user.username + ', ' # CREATE USER LANGUAGES # Set language try: language = request.session[translation.LANGUAGE_SESSION_KEY] except KeyError: language = 'en' user_language = UserLanguageModel(user=new_user, language=language) user_language.save() # CREATE AUCTIONS deadline_date = timezone.now() + timezone.timedelta(days=5) token = str(uuid.uuid4()) # Unique token for editing without login while len(AuctionModel.objects.filter(token=token)) != 0: token = str(uuid.uuid4()) new_auction = AuctionModel(title='Title ' + i_str, description='Description ' + i_str, minimum_price=Decimal( random.randint(1, 100)), deadline_date=deadline_date, token=token, seller=new_user, version=1) new_auction.save() msg_auctions = msg_auctions + 'Title ' + i_str + ', ' messages.add_message(request, messages.INFO, msg_users) messages.add_message(request, messages.INFO, msg_auctions) messages.add_message( request, messages.INFO, 'Admin users are created using the admin interface (manage.py or django-admin)' ) return redirect(reverse('index'))
def user_registration(request): user_create_form = CustomUserCreationForm() if request.method == 'POST': user_create_form: CustomUserCreationForm = CustomUserCreationForm( request.POST, files=request.FILES) if user_create_form.is_valid(): customer: User = user_create_form.save(commit=False) customer.save() return redirect('user:user_login') return render(request, template_name='user/registration.html', context={'form': user_create_form})
def registration(request): if request.method == "POST": if request.POST.get("im_bot") == "on": return HttpResponseForbidden("Seems that you are a bot.") form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("user_login")) else: form = CustomUserCreationForm() return render_to_response( "registration.html", { "page_title": ugettext("Registration"), "form": form, }, context_instance=RequestContext(request) )
def get(self, request): safe_destination = safeRedirectDestination(request) if safe_destination: form = CustomUserCreationForm() return render(request, "signup.html", {"form": form}) else: messages.add_message( request, messages.INFO, "Back to safety! Malicious attempt to redirect.") return redirect("index")
def post(self, request): safe_destination = safeRedirectDestination(request) if safe_destination: form = CustomUserCreationForm(request.POST) if form.is_valid(): # Save the user with the save() function in CustomUserCreationForm new_user = form.save() # Set language try: language = request.session[ translation.LANGUAGE_SESSION_KEY] except KeyError: language = 'en' user_language = UserLanguageModel(user=new_user, language=language) user_language.save() # Messages messages.add_message(request, messages.INFO, "User created") user_info = "username " + new_user.username + ", email " + new_user.email + ", language " + user_language.language messages.add_message(request, messages.INFO, user_info) # Sign in the user for ease of use auth.login(request, new_user) print('Signup SIGNED IN: ' + str(new_user.is_authenticated)) return redirect('index') # Issue 001 else: messages.add_message( request, messages.INFO, "This username has been taken, or This email has been taken" ) # Required by UC1 return render(request, "signup.html", {"form": form}) else: messages.add_message( request, messages.INFO, "Back to safety! Malicious attempt to redirect.") return redirect("index")
def signup(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your account.' message = render_to_string( 'registration/signup_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') send_mail(mail_subject, message, '*****@*****.**', [to_email]) return redirect('signup_confirm') else: form = CustomUserCreationForm() return render(request, 'registration/signup.html', { 'form': form, })
def post(self, request): form = CustomUserCreationForm(request.data) if form.is_valid(): form.save() #print(form.errors) response = {"result": form.is_valid(), "errors": form.errors} return Response(response) '''
def register(request): if request.user.is_authenticated: return redirect('ecommerce:home') user_create_form = CustomUserCreationForm() if request.method == 'POST': user_create_form = CustomUserCreationForm(request.POST) if user_create_form.is_valid(): user_create_form.save() return redirect('ecommerce:home') return render(request, template_name='user/register.html', context={'form': user_create_form})
def test_signup_form(self): """test custom user signup form""" credential = { 'email': "*****@*****.**", 'password1': "ASZX1234!", 'password2': "ASZX1234!", } form = CustomUserCreationForm(data=credential) is_valid = form.is_valid() self.assertTrue(is_valid) self.assertEqual(form.cleaned_data['email'], credential['email']) self.assertEqual(form.cleaned_data['password1'], credential['password1']) self.assertEqual(form.cleaned_data['password2'], credential['password2']) user_form = form.save() user_auth = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password2']) # self.assertIsNotNone(user_form) self.assertIsNotNone(user_auth) from django.contrib.auth import get_user_model user_model = get_user_model() self.assertIsInstance(user_form, user_model) self.assertIsInstance(user_auth, user_model) self.assertEqual(user_form.id, user_auth.id, )
def home(request): if request.user.is_authenticated(): activ_user = get_object_or_404(User, username=request.user) user_film_vote = FilmRating.objects.filter(user=activ_user) user_serial_vote = SerialRating.objects.filter(user=activ_user) articles_queryset = Article.objects.get_queryset() articles = articles_queryset.order_by('-created_date') latest_article = articles.first() page = request.GET.get('page') paginator = Paginator(articles, per_page=4) try: articles = paginator.page(page) except PageNotAnInteger: articles = paginator.page(1) except EmptyPage: articles = paginator(paginator.num_pages) context = { 'user_film_vote': user_film_vote, 'user_serial_vote': user_serial_vote, 'articles': articles, 'latest_article': latest_article, } return render(request, "main/home.1.html", context) else: if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] full_message = f'{message}\nFrom: {from_email}' my_email = settings.EMAIL_HOST_USER to_email = my_email try: send_mail(subject, full_message, my_email, [to_email], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') messages.success(request, 'Thanks for your reply') return redirect('website_home') if request.method == 'POST': signup_form = CustomUserCreationForm(request.POST) if signup_form.is_valid(): signup_form.save() messages.success(request, 'Account created successfully, login.') return redirect('website_login') else: signup_form = CustomUserCreationForm() return render(request, "main/home.html", { 'signup_form': signup_form, 'form': form })
def setUp(cls): """Create a unique form for all tests.""" cls.form = CustomUserCreationForm()