Пример #1
0
    def post(self, request):

        # if a user is already logged in, redirect to home
        if request.user.is_authenticated():
            return redirect('main:root')

        # create a filled user creation form from POST data
        filled_user_creation_form = UserCreationForm(request.POST)

        # if the filled form is valid:
        if filled_user_creation_form.is_valid():

            # create a new user object with the form information
            user = filled_user_creation_form.save()

            # authenticate the new user against the database (a formality)
            user = authenticate(username=request.POST['username'],
                                password=request.POST['password1'])

            # log the new user into the site and redirect to home
            auth_login(request, user)
            return redirect('main:root')

        # if the filled form was invalid
        else:

            # save error message and invalid form to be passed back for editing
            context = {}
            context['error_on_create'] = True
            context['form'] = filled_user_creation_form
            return render(request, 'project/register.html', context)
Пример #2
0
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            # Create an inactive user with no password:
            user = form.save(commit=False)
            user.is_active = False
            user.save()

            # Send an email to the user with the token:
            current_site = get_current_site(request)
            uid = urlsafe_base64_encode(force_bytes(user.pk))
            token = account_activation_token.make_token(user)
            send_mail(
                subject='Activate your account',
                message="""
                We are happy to see you aboard!
                Click on the link down, so we can start doing our job.
                And you will find yours!
                """,
                link=
                f"http://{current_site}/signup/activate_mail/{uid}/{token}",
                to_email=[form.cleaned_data['email']],
            )

            return render(
                request, 'alerts/render_base.html', {
                    'response_error_text':
                    'Please confirm your email address to complete the registration',
                    'response_error_title': 'Email confirmation'
                })
    else:
        form = RegisterForm()

    return render(request, 'registration/register.html', {'form': form})
Пример #3
0
 def test_user_creation_form(self):
     form = UserCreationForm({'email': '*****@*****.**', 'password1': 'somepassword', 'password2': 'somepassword'})
     self.assertTrue(form.is_valid())
     with self.assertLogs('main.forms', level='INFO') as cm:
         form.send_welcome_email()
     self.assertGreaterEqual(len(cm.output), 1)
     self.assertEqual(len(mail.outbox), 1)
Пример #4
0
def register(request):
	form = UserCreationForm()
	if request.method == 'POST':
		form = UserCreationForm(request.POST)
		if form.is_valid():
			form.save()
			return redirect('home')
	return render_to_response('register.html',{
		'form': form,
	}, RequestContext(request))
Пример #5
0
    def test_valid_signup_form_sends_email(self):
        form = UserCreationForm({
            'email': '*****@*****.**',
            'password1': 'abcabcabc',
            'password2': 'abcabcabc',
        })

        self.assertTrue(form.is_valid())

        with self.assertLogs("main.forms", level='INFO') as cm:
            form.send_mail()

        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].subject, 'Welcome to BookStore')
        self.assertGreaterEqual(len(cm.output), 1)
Пример #6
0
    def test_valid_signup_form_sends_email(self):
        form = UserCreationForm({
            'email': '*****@*****.**',
            'password1': 'asdf1234.*',
            'password2': 'asdf1234.*'
        })
        self.assertTrue(form.is_valid())

        with self.assertLogs(logging.getLogger('main.forms'),
                             level='INFO') as cm:
            form.send_mail()

        self.assertEquals(len(mail.outbox), 1)
        self.assertEquals(mail.outbox[0].subject, "Welcome to BookTime")

        self.assertGreaterEqual(len(cm.output), 1)
Пример #7
0
    def form_valid(self, form: forms.UserCreationForm):
        response = super().form_valid(form)
        form.save()

        email = form.cleaned_data.get('email')
        raw_password = form.cleaned_data.get('password1')
        logger.info(f'New signup for email={email}')

        user = authenticate(email=email, password=raw_password)
        login(self.request, user)

        form.send_email()

        messages.info(self.request, 'You signed up successfully/.')

        return response
Пример #8
0
def user_signup(request):
    context = {

    }
    if request.is_ajax():
        response_data = {}

        data = json.loads(request.body.decode('utf-8'))
        postEmail = data.get('email')
        postUsername = data.get('username')
        postPassword = data.get('password')

        user = User(email=postEmail, username=postUsername)
        user.set_password(postPassword)
        try:
            user.save()

        except IntegrityError as e:
            response_data['status'] = False
            response_data['msg'] = 'Sorry! This email is already signed up.'
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json"
                                )
        response_data['status'] = True
        response_data['msg'] = 'Success!'

        return HttpResponse(
                    json.dumps(response_data),
                    content_type="application/json"
                )


    else:
        if request.method == 'POST':
            form = UserCreationForm(request.POST)
            if form.is_valid():
                form.save()

        else:
            form = UserCreationForm()

        context.update({'form': form})
        return render(request, 'main/pages/signup.html', context)
Пример #9
0
def register(request):
    # A HTTP POST?
    if request.method == 'POST':
        form = UserCreationForm(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new manufacturer to the database.
            form.save(commit=True)


            # The user will be shown the homepage.
            return HttpResponseRedirect('/main/')
        else:
            # The supplied form contained errors - just print them to the terminal.
            print(form.errors)
    else:
        # If the request was not a POST, display the form to enter details.
        form = UserCreationForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render(request, 'register.html', {'form': form})
Пример #10
0
def user_signup(request):
    context = {}
    if request.is_ajax():
        response_data = {}

        data = json.loads(request.body.decode('utf-8'))
        postEmail = data.get('email')
        postUsername = data.get('username')
        postPassword = data.get('password')

        user = User(email=postEmail, username=postUsername)
        user.set_password(postPassword)
        try:
            user.save()

        except IntegrityError as e:
            response_data['status'] = False
            response_data['msg'] = 'Sorry! This email is already signed up.'
            return HttpResponse(json.dumps(response_data),
                                content_type="application/json")
        response_data['status'] = True
        response_data['msg'] = 'Success!'

        return HttpResponse(json.dumps(response_data),
                            content_type="application/json")

    else:
        if request.method == 'POST':
            form = UserCreationForm(request.POST)
            if form.is_valid():
                form.save()

        else:
            form = UserCreationForm()

        context.update({'form': form})
        return render(request, 'main/pages/signup.html', context)
Пример #11
0
def login(request):

    # if a user is already logged in, redirect to the front page
    if request.user.is_authenticated():
            return redirect('front')

    # load a blank registration form to context in case they want to register
    context = {}
    context['user_create_form'] = UserCreationForm()
    context['next'] = request.GET.get('next', '/')

    if request.method == 'POST':

        # if the POST request was a submission of the login form
        if request.POST['type'] == 'login':

            # attempt to authenticate the user
            user = authenticate(username=request.POST['username'],
                                password=request.POST['password'])

            # if the user is found in the database
            if user is not None:

                # and if the user's account is active
                if user.is_active:

                    # then log the user in and redirect to front page
                    auth_login(request, user)
                    if request.user.is_authenticated():
                        return redirect(request.POST.get('next', '/'))

                # if the user's account is not active
                else:

                    # load an error message to context and reload page
                    context['error'] = 'Your account has been disabled.'
                    return render(request, 'login.html', context)

            # if the user is not found in the database
            else:

                # load an error message to context and reload page
                context['error'] = 'Invalid username or password.'
                return render(request, 'login.html', context)

        # if the POST request was a submission of the registration form
        elif request.POST['type'] == 'create_user':

            # save a copy of the filled registration form
            filled_user_creation_form = UserCreationForm(request.POST)

            # if the filled form is valid
            if filled_user_creation_form.is_valid():

                # create a new user with the form information (the email field
                # has to be saved manually because although Django renders an
                # email field by default, it doesn't actually save it by
                # default)
                user = filled_user_creation_form.save()
                # user.email = request.POST['email']
                # user.save()

                # authenticate the new user against the database (a formality)
                user = authenticate(username=request.POST['username'],
                                    password=request.POST['password1'])

                # log the new user into the site
                auth_login(request, user)

                # redirect user to the front page
                return redirect(request.POST.get('next', '/'))

            # if the filled form is invalid
            else:

                # load invalid form to context to be passed back for editing
                context['error_on_create'] = True
                context['user_create_form'] = filled_user_creation_form

    return render(request, 'login.html', context)
Пример #12
0
def login(request):

    # if a user is already logged in, redirect to the front page
    if request.user.is_authenticated():
        return redirect('front')

    # load a blank registration form to context in case they want to register
    context = {}
    context['user_create_form'] = UserCreationForm()
    context['next'] = request.GET.get('next', '/')

    if request.method == 'POST':

        # if the POST request was a submission of the login form
        if request.POST['type'] == 'login':

            # attempt to authenticate the user
            user = authenticate(username=request.POST['username'],
                                password=request.POST['password'])

            # if the user is found in the database
            if user is not None:

                # and if the user's account is active
                if user.is_active:

                    # then log the user in and redirect to front page
                    auth_login(request, user)
                    if request.user.is_authenticated():
                        return redirect(request.POST.get('next', '/'))

                # if the user's account is not active
                else:

                    # load an error message to context and reload page
                    context['error'] = 'Your account has been disabled.'
                    return render(request, 'login.html', context)

            # if the user is not found in the database
            else:

                # load an error message to context and reload page
                context['error'] = 'Invalid username or password.'
                return render(request, 'login.html', context)

        # if the POST request was a submission of the registration form
        elif request.POST['type'] == 'create_user':

            # save a copy of the filled registration form
            filled_user_creation_form = UserCreationForm(request.POST)

            # if the filled form is valid
            if filled_user_creation_form.is_valid():

                # create a new user with the form information (the email field
                # has to be saved manually because although Django renders an
                # email field by default, it doesn't actually save it by
                # default)
                user = filled_user_creation_form.save()
                # user.email = request.POST['email']
                # user.save()

                # authenticate the new user against the database (a formality)
                user = authenticate(username=request.POST['username'],
                                    password=request.POST['password1'])

                # log the new user into the site
                auth_login(request, user)

                # redirect user to the front page
                return redirect(request.POST.get('next', '/'))

            # if the filled form is invalid
            else:

                # load invalid form to context to be passed back for editing
                context['error_on_create'] = True
                context['user_create_form'] = filled_user_creation_form

    return render(request, 'login.html', context)