我正在尝试随机生成用户名并保存到用户模型。目前,我可以生成用户名,但是无法将其保存到用户模型中,我也不知道该怎么做。请帮助完成它。我的表单过程没有随机的用户名生成器功能。当我添加这些函数以生成自定义和随机用户名时,我遇到了很多错误,例如attibute错误,unbound错误等等
views.py
# random username generator
def userdate(dt_time):
return str(10000*dt_time.year+100*dt_time.month+dt_time.day)
def usernameGen(names):
names = names.split(" ")
for i in range(1,1000):
first_letter = names[0][0]
three_letter = names[-1][:3]
number = '{:03d}'.format(random.randrange(1,1000))
dateuser = userdate(date.today())
username =(first_letter+three_letter+dateuser+number)
try:
User.objects.get(username = username)
return usernameGen("PMK GAC")
except User.DoesNotExist:
return username
# registration view
def register(request, *args, **kwargs):
if request.method == 'POST':
username = usernameGen("PMK GAC") #calling usernameGen function
form = CustomUserCreationForm(request.POST) #user form
profile = ProfileForm(request.POST, request.FILES) #profile form
if form.is_valid() and profile.is_valid():
form.save()
profile.save()
# messages.success(request, 'new user is create. ')
return render(request,'info.html')
form = CustomUserCreationForm()
profile = ProfileForm()
context = {'form':form, 'profile':profile}
return render(request, 'register.html', context)
models.py
#this models is not User model. it is additional model with One to one relationship of current user
class Profile(models.Model):
# specified choices
DEPARTMENT_CHOICES = (
("Department of Computer Science", "Department of Computer Science" ),
("Department of Electronics", "Department of Electronics" ),
("Department of Bio-Chemistry", "Department of Bio-Chemistry" ),
("Department of Chemistry", "Department of Chemistry" ),
("Department of Tamil", "Department of Tamil" ),
("Department of English", "Department of English" ),
("Department of Mathematics", "Department of Mathematics" ),
("Department of Physics", "Department of Physics" ),
("Department of Commerce", "Department of Commerce" ),
("Department of Business Administration", "Department of Business Administration" ),
("Department of Histroy", "Department of Histroy" ),
("Department of Economics", "Department of Economics" ),
)
GENDER_CHOICES = (
('Male', 'Male'),
('Female', 'Female')
)
user = models.OneToOneField(User, on_delete = models.CASCADE)
Date_Of_Birth = models.DateField(null=True)
Department = models.CharField(null=True, max_length = 50, choices= DEPARTMENT_CHOICES, default=None)
Phone_number = models.CharField(unique=True, null=True,max_length=10)
Age = models.CharField(null=True, max_length = 3)
University_Exam_No = models.CharField(null=True, max_length=10)
Aadhar = models.CharField(null = True, max_length=12)
Gender = models.CharField(null=True, max_length = 50, choices= GENDER_CHOICES, default=None)
Permanent_Address = models.TextField(null=True)
Per_Taluk = models.CharField(null=True, max_length = 30)
Per_Pin_Code = models.CharField(null=True, max_length=6)
Per_State = models.CharField(null=True, max_length=30)
Per_Dist = models.CharField(null=True, max_length = 30)
Address = models.TextField(null = True)
Dist = models.CharField(null=True, max_length = 30)
Taluk = models.CharField(null=True, max_length = 30)
Pin_Code = models.CharField(null=True, max_length=6)
State = models.CharField(null=True, max_length=30)
Image = models.ImageField(upload_to='profiles', null = True)
Sign = models.ImageField(upload_to='Signs', null=True)
def __str__(self):
return self.user.first_name
forms.py
# Here I directly created the form without creating a custom User model
# user registration form
class CustomUserCreationForm(forms.Form):
firstname = forms.CharField(label='First Name', max_length=50, widget=forms.TextInput(attrs={'class':'form-control'}))
lastname = forms.CharField(label='Last Name', max_length=50,widget=forms.TextInput(attrs={'class':'form-control'}))
username = forms.CharField(label = 'Username', min_length=4, max_length=150,widget=forms.TextInput(attrs={'class':'form-control'}))
email = forms.EmailField(label='Email id', widget=forms.EmailInput(attrs={'class':'form-control'}))
password1 = forms.CharField(label = 'Password', widget=forms.PasswordInput(attrs={'class':'form-control'}))
password2 = forms.CharField(label = 'Conform Password', widget=forms.PasswordInput(attrs={'class':'form-control'}))
def clean_firstname(self):
firstname = self.cleaned_data['firstname']
return firstname
def clean_lastname(self):
lastname = self.cleaned_data['lastname']
return lastname
def clean_username(self):
username = self.cleaned_data['username']
r = User.objects.filter(username = username)
if r.count():
raise ValidationError('username is already exists')
return username
def clean_email(self):
email = self.cleaned_data['email']
r = User.objects.filter(email = email)
if r.count():
raise ValidationError('Email id is already exists')
return email
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise ValidationError(' Passwords did not matching')
return password2
def save(self, commit = True):
user = User.objects.create_user(
self.cleaned_data['username'],
first_name=self.cleaned_data['firstname'],
last_name=self.cleaned_data['lastname'],
email=self.cleaned_data['email'],
password=self.cleaned_data['password1']
)
return user
# profile model form.it is model forms of Profile model
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = '__all__'
exclude = ['user']
widgets = {
'Date_Of_Birth':forms.DateInput(attrs={'class':'form-control', 'placeholder':'YYYY-MM-DD'}),
'Department':forms.Select(attrs = {'class':'form-control'}),
'Phone_number':forms.NumberInput(attrs = {'class':'form-control'}),
'Age':forms.TextInput(attrs={'class':'form-control'}),
'University_Exam_No':forms.TextInput(attrs={'class':'form-control'}),
'Aadhar':forms.TextInput(attrs={'class':'form-control'}),
'Gender':forms.Select(attrs = {'class':'form-control'}),
'Permanent_Address':forms.Textarea(attrs = {'class':'form-control rounded', 'rows':3, 'cols':3}),
'Per_Taluk':forms.TextInput(attrs={'class':'form-control'}),
'Per_Pin_Code':forms.NumberInput(attrs = {'class':'form-control'}),
'Per_State':forms.TextInput(attrs={'class':'form-control'}),
'Per_Dist':forms.TextInput(attrs={'class':'form-control'}),
'Address':forms.Textarea(attrs = {'class':'form-control rounded','rows':3, 'cols':3}),
'Taluk':forms.TextInput(attrs={'class':'form-control'}),
'Pin_Code':forms.NumberInput(attrs = {'class':'form-control'}),
'State':forms.TextInput(attrs={'class':'form-control'}),
'Dist':forms.TextInput(attrs={'class':'form-control'}),
'Image':forms.FileInput(attrs={'class':'form-control'}),
'Sign':forms.FileInput(attrs={'class':'form-control'}),
}
如果您有创建新用户的表单,那么他们也将填写用户名字段。但是无论如何,对于任何模型的任何新对象,您都可以覆盖save函数,或者至少在将其保存到数据库之前,向该对象添加一些属性。
例如,在您的admin.py模型的modelAdmin中添加此(根据https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model):
@admin.register(MyCustonUser)
classs MyCustomUserAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.username = Your_Username_Gen_Functio()
super().save_model(request, obj, form, change)
也有可能在views.py中做类似的事情