[Fixed]-Generate alphanumeric string in python

1👍

What is happening with the 0x0 part changing is that when codegenerate (I don’t know what that is exactly or how it is actually called in the context of your code) gets called each time, a new/fresh instance of the lettercounter generator is returned. You can specifically create a fresh instance of the generator by doing this in the module that defined it:

lettercounter_inst = lettercounter()

Then you need to actually get the next string value from your generator function rather than letting your code (inside codegenerate) casting that object into a string (this is what causes the raw repr expression of the generator to appear in your text field). Like so:

addcodegenerate = codegenerate(initial={'id_gen': next(lettercounter_inst)})

However, in the context of django I assume you want to persist the results submitted by the users and it’s best to rely on the database or construct a model associated with it, and then have a function that cast the associated auto-increment value to the alphanumeric string you desire.

0👍

You’re creating a new generator each time the view is called. You need to create the generator once, then refer to it in the view. For example:

# Outside the view
incrementing_letters = letter_counter

# Inside the view
addcodegenerate = codegenerate(initial={'id_gen': incrementing_letters})

Leave a comment