[英]Generating and storing unique ID using uuid in Django
I am trying to generate a unique user ID using python's uuid
and then store it in my mysql database.我正在尝试使用 python 的uuid
生成唯一的用户 ID,然后将其存储在我的 mysql 数据库中。 I am confused as to when I should generate the ID.我对何时应该生成 ID 感到困惑。
This is my forms.py
:这是我的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这是我的 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.我建议使用所有必要的附加字段(例如您的 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).用于描述models.py 中的一个字段(不是在表单中)。 If you put it here you don't have to think about generating id, you have already set a callable uuid4 for it.放在这里就不用考虑生成id了,已经为它设置了一个可调用的uuid4。 Read more at docs .在docs阅读更多内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.