I am trying to generate a unique user ID using python's uuid
and then store it in my mysql database. I am confused as to when I should generate the ID.
This is my forms.py
:
from django import forms
from django.contrib.auth.models import models
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
import uuid
class RegistrationForm(UserCreationForm):
email = models.EmailField(required=True)
user_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class meta:
model = User
fields = (
'first_name',
'last_name',
'email',
'password1',
'password2'
)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
user.user_id = uuid.uuid4()
if commit:
user.save()
return user
This is the registration portion of my views.py
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save
return redirect('/account')
else:
form = RegistrationForm()
args = {'form':form}
return render(request, 'accounts/registration.html', args)
First, what you are trying to do is Extending core User model . You must choose one of two ways to do it. I would recommend creating one-to-one model with all necessary additional fields, such as your uuid ID.
Second, the code
user_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
is for describing a field in models.py (not in forms). If you put it here you don't have to think about generating id, you have already set a callable uuid4 for it. Read more at docs .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.