RC-
RC-

Reputation: 163

Replacing random part of a generated key in Django

I am generating a key in my Django project once a user clicks a button, here is the code in the view:

key_value = get_random_string(length=14, allowed_chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
 if request.method == "POST":
        form = PostProposal(request.POST)
        if form.is_valid():
[...]
p = Contract.objects.create(
               key= key_value,

[...]

The end result is a string of 14 characters, like this example: I8IH2GPH8RNK6A

I am trying to create another key: "key1" tha will replace randomly 4 characters by an underscore, so basically I will have:

key: I8IH2GPH8RNK6A

key1: I8I_2GP_8_NK_A

the replacement should be randomly created when the user clicks the button, and it always concern 4 characters. Any help would be appreciated. Thx

Upvotes: 0

Views: 41

Answers (1)

Afsal Salim
Afsal Salim

Reputation: 486

import random
key = "I8IH2GPH8RNK6A"
key1 = list(key)
while 1:
    key1[random.randrange(0, len(key))] = "_"
    if key1.count("_") == 4:
        break
key1 = ''.join(key1)
print key1

Upvotes: 1

Related Questions