What I'm trying to do is whenever the user requests an API key--regardless of whether the user already generated one or not--the system will generate an entirely new key.
I know that whenever calling ApiKey.objects.create()
will generate an API key for the user that doesn't have one generated. However, if a user does have one, then trying to call the .create()
method throws an error.
In this case, I figured that it would be best to write my own key generator. However, I am now hoping that maybe someone here might know of a helper function that will allow me to generate a random API key, and then let me save it to the database manually myself.
Would anyone might know of any such a helper function?
Based on Filip Dupanović's answer the working code for me was something like this:
user = get_user_model().objects.get(email="[email protected]")
api_key = ApiKey.objects.get_or_create(user=user)
api_key[0].key = api_key[0].generate_key()
api_key[0].save()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With