0๐
Twilio developer evangelist here.
There have been some great answers to help you generate a random 6 digit string, however I just wanted to add one more suggestion.
Authy is part of Twilio and provides Two Factor Authentication as a service. It supports sending codes by SMS (which goes via Twilio), generating codes in the Authy application and even two factor authentication without copying a code from an app/sms to your login screen with Authy OneTouch. You can implement your entire 2FA flow with just 3 API calls.
There is a tutorial on how to use Authy with Flask, which Iโm sure you could translate to Django.
Let me know if this helps at all.
12๐
In addition to Matthiasโ answer (I upvoted his answer);
Django provides a shortcut function for this purpose:
from django.utils.crypto import get_random_string
get_random_string(length=6, allowed_chars='1234567890')
Which is more readable and memorable.
And also if you are really concerned about randomness of this string, you may want to use random module from pycrypto because standard library implementations of random function in programming languages are not โrandomโ enough for cryptographic and security related issues.
- [Django]-Why is django.test.client.Client not keeping me logged in
- [Django]-How to set PYTHONPATH on web server
- [Django]-Django ignoring translated strings from third party module
5๐
You can use random.choice
to determine each digit. choice
will give you one element from the given sequence.
The code could look like this:
import random
pin = ''.join(random.choice('0123456789') for _ in range(6))
- [Django]-Dynamic SEO-friendly URLs
- [Django]-Ignore_user_abort php simil in Django/python?
- [Django]-Django Mongodb Engine : Authentication, Sessions ans User Model
- [Django]-Django queryset "contains" for lists, not strings
0๐
rand(1000, 9999); == 4 digit
rand(100000, 999999); == 6 digit
$client = $this->_initTwilioClient();
$fromNo = $this->_helperPot->getTwilioPhone();
$code = rand(1000, 9999);
try {
$result = $client->messages->create(
$toNo,
[
'from' => $this->_helperPot->getTwilioPhone(),
'body' => "Verification code: $code"
]
);
$output = [];
$output['status'] = "success";
$output['code'] = $code;
return $output;
} catch (\Exception $e) {
$output = [];
$output['status'] = "failure";
$output['message'] = $e->getMessage();
return $output;
}
- [Django]-Getting Illegal instruction: illegal hardware instruction python manage.py runserver on Apple M1 chip
- [Django]-Django migration OperationalError: index [name] already exists
- [Django]-Django โ queryset with extra method returns empty, count() says otherwise
- [Django]-Stop django from automatically unicodifing POST stuff
- [Django]-Django model.save() not writing to database