You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django自定义用户模型注册逻辑构建及前端动态表单需求

Django用户注册:动态显示字段+关联Patient/Doctor模型修复

一、修复模型关联逻辑

Doctor模型使用ForeignKey会允许一个用户对应多个医生,不符合业务逻辑,改为OneToOneField:

class Doctor(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='doctor')
    deg = models.TextField(null=True, blank=True)
    
    def __str__(self):
       return self.user.name

二、优化表单配置

移除Patient/Doctor表单中的user字段,避免用户手动输入,由后台自动绑定:

class DoctorCreation(ModelForm):
    class Meta:
        model = Doctor
        fields = ['deg']  # 仅保留医生专属字段

class PatientCreation(ModelForm):
    class Meta:
        model = Patient
        fields = ['dob', 'contact']  # 仅保留患者专属字段

三、修复注册视图逻辑

修正原视图中is_valid调用缺失括号、保存用户后直接跳转、未关联用户到对应模型的问题:

def registerUser(request):
    user_form = MyUserCreation()
    patient_form = PatientCreation()
    doctor_form = DoctorCreation()

    if request.method == 'POST':
        user_form = MyUserCreation(request.POST)
        if user_form.is_valid():
            user = user_form.save()
            # 根据用户类型创建对应实例并绑定用户
            if user.usertype == 'p':
                patient_form = PatientCreation(request.POST)
                if patient_form.is_valid():
                    patient = patient_form.save(commit=False)
                    patient.user = user
                    patient.save()
            elif user.usertype == 'd':
                doctor_form = DoctorCreation(request.POST)
                if doctor_form.is_valid():
                    doctor = doctor_form.save(commit=False)
                    doctor.user = user
                    doctor.save()
            login(request, user)
            return redirect('home')
        else:
            messages.error(request, '注册出错,请检查输入内容')

    context = {
        'user_form': user_form,
        'patient_form': patient_form,
        'doctor_form': doctor_form
    }
    return render(request, 'rec/register_user.html', context )

四、前端实现动态字段切换

通过JavaScript监听用户类型选择,动态显示对应模型的额外字段:

<form method="POST">
    {% csrf_token %}
    <!-- 用户基础信息字段 -->
    {{ user_form.as_p }}

    <!-- 患者专属字段(默认隐藏) -->
    <div id="patient-section" style="display: none;">
        <h4>患者补充信息</h4>
        {{ patient_form.as_p }}
    </div>

    <!-- 医生专属字段(默认隐藏) -->
    <div id="doctor-section" style="display: none;">
        <h4>医生补充信息</h4>
        {{ doctor_form.as_p }}
    </div>

    <button type="submit">完成注册</button>
</form>

<script>
const usertypeSelect = document.querySelector('select[name="usertype"]');
const patientSection = document.getElementById('patient-section');
const doctorSection = document.getElementById('doctor-section');

// 监听用户类型选择变化
usertypeSelect.addEventListener('change', () => {
    patientSection.style.display = 'none';
    doctorSection.style.display = 'none';
    if (usertypeSelect.value === 'p') {
        patientSection.style.display = 'block';
    } else if (usertypeSelect.value === 'd') {
        doctorSection.style.display = 'block';
    }
});

// 页面加载时初始化显示状态
window.addEventListener('load', () => {
    if (usertypeSelect.value === 'p') {
        patientSection.style.display = 'block';
    } else if (usertypeSelect.value === 'd') {
        doctorSection.style.display = 'block';
    }
});
</script>

额外注意事项

  • 确保settings.py中已配置自定义用户模型:AUTH_USER_MODEL = '你的应用名.User'
  • 修改模型后执行python manage.py makemigrations和python manage.py migrate更新数据库
  • 可自定义表单渲染样式(替换as_p)提升页面美观度

内容的提问来源于stack exchange,提问作者LEO_007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 04:05:12