Miguel Toledano Miguel Toledano - 2 months ago 6
Python Question

How I can make my db add codes for users to register with one of the codes ? (Python-Django)

I want to put a number of codes in my database so that when a user wants to register my application need to enter a code of those who are in the database, so that the system registry access.

All this in django, but honestly I have no idea how to do it, if you can help me, I would appreciate it very much.

Thanks for your time.


There are a couple of steps that you will need to do, but essentially you are just seeding the DB with valid registration codes. To generate a number of registration codes you can use the following, I limit the number to 1000 but this can be changed

import uuid

codes = set()
num_codes = 1000

while (num_codes > 0):
    code = str(uuid.uuid4())
    # make sure the randomly gen code isn't a duplicated
    while code in codes:
        code = str(uuid.uuid4())
    # add the newly generated code to the set and dec the counter
    num_codes -= 1

Next what you will want to do is add the codes to a new table. It would probably make sense to have a table structure like:

   table_name: registration code,
   columns: {
        id: int,
        code: string,
        valid: bool,

where valid limits the code to a one time registration.

Then when a user tries to register select where the key used = code column and valid = true, if it returns something it is valid otherwise the key is invalid or already used.