有人要我制作一份没有电子邮件的注册表,只有名字、姓氏和出生日期。所以我决定这样做:
用户名 = request.POST['first_name'] + '__' + request.POST['last_name']
我知道我们需要在 Django 中有一个唯一的字段,因此同名的人会导致问题。但这就是他想要的方式(没有多少用户会使用它)。
那么如何使用上面的用户名和默认密码填充 Django 的 AbstractBaseUser?
我们的想法是让已登录的医生
仅使用名字、姓氏和出生日期来注册新的患者
。
models.py
:
class MyUser(AbstractBaseUser):
USER_TYPE = (('doc', 'Doctor'), ('pat', 'Patient'))
id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
username = models.CharField(max_length=200, unique=True, )
joined = models.DateTimeField(auto_now_add=True)
usertype = models.CharField(max_length=254, choices=USER_TYPE)
first_time = models.NullBooleanField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
USERNAME_FIELD = 'username'
def __unicode__(self):
return self.username
forms.py:
class patientForm(forms.ModelForm):
class Meta:
model = MyUser
fields = ('username', 'first_name', 'last_name')
class patientProfileForm(forms.ModelForm):
class Meta:
model = Patients
fields = ('dob', 'condition')
views.py:
@login_required
def new_patient(request):
context = RequestContext(request)
registered = False
if request.method == 'POST':
patient_form = patientForm(data=request.POST)
patient_profile = patientProfileForm(data=request.POST)
if patient_form.is_valid() and patient_profile.is_valid():
username = request.POST['first_name'] + '__' + request.POST['last_name']
user = patient_form.save() #Error here: (1062, “Duplicate entry '' for key 'username'”)
user.set_password(user.password)
user.save()
profile = patient_profile.save(commit=False)
profile.user = user
profile.doctor = request.user
profile.save()
registered = True
else:
print patient_form.errors, patient_profile.errors
else:
patient_form = patientForm()
patient_profile = patientProfileForm()
return render_to_response(
'new-patient.html',
{'patient_form': patient_form, 'patient_profile': patient_profile, 'registered': registered},
context)
如何在保存表单时按照前面提到的格式添加用户名?我收到错误:
(1062, “重复条目 '' for key 'username'”)
(参见上文发生这种情况的位置)
最佳答案
实现此目的的一种方法是覆盖 clean
method设置用户名字段直到找到。这可能不是您需要的确切代码,但您明白了。
class patientForm(forms.ModelForm):
class Meta:
model = MyUser
fields = ('username', 'first_name', 'last_name')
def clean(self):
cd = self.cleaned_data
fullname = "%s-%s" % (cd.get('first_name'), cd.get('last_name'))
username = slugify(fullname)
while True:
try:
user = User.objects.get(username=username)
except:
username = username + '-copy' #Or changes this to a counter.
else:
break
cd['username'] = fullname
return cd
关于python - Django自定义注册: how to set a default password and use first name + last name as username,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25254708/