python - Django自定义注册: how to set a default password and use first name + last name as username

标签 python mysql django

有人要我制作一份没有电子邮件的注册表,只有名字、姓氏和出生日期。所以我决定这样做:

用户名 = 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/

相关文章:

python - 在 GeoPandas 中将 Legend 添加到 Choropleth map

python - PyQt 窗口打开后立即关闭

mysql - 只从查询返回表,不返回 View

MySQL/PhpMyAdmin 复制具有不同列的表

python - 如何查看rabbitmq队列中推送的所有celery任务

django - 如何检查外键是否存在?

python - 我可以在单个项目中同时使用 Django 和 Rest Framework View 吗?

python - Plotly:改变填充颜色的透明度

mysql - 仅当两个或多个记录具有相同值时才连接两个表并分组

django - 如何在 direct_to_template 上免除 CSRF 保护