从ModelForm创建用户前排除字段?Django 4.1

e5nszbig  于 2023-01-03  发布在  Go
关注(0)|答案(1)|浏览(146)

我有一个从自定义用户继承的用户类型patient,我尝试在创建用户对象之前从数据中删除确认密码字段。确认密码字段不在模型中,但在模型表单中创建。我尝试下面的代码,但得到got unexpected keyword arguments: 'confirm'

    • 型号. py:**
class User(AbstractUser):
    username = None

    email = models.EmailField(unique=True)

    is_patient = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'

    REQUIRED_FIELDS = ['password']

    object = UserManager()

class Patient(User):
    address = models.CharField(max_length=200)

    class Meta:
        verbose_name_plural = 'Patients'

    def __str__(self):
        return self.first_name
    • 表格. py:**
class PateintForm(forms.ModelForm):
    
    confirm = forms.CharField(max_length=50, widget=forms.PasswordInput)
    is_patient = forms.BooleanField(widget=forms.HiddenInput)

    class Meta:
        model = Patient
        fields = ['first_name', 'last_name', 'address', 'email', 'password']

        widgets = {
            'first_name': forms.TextInput(attrs={'placeholder': 'First Name'}),
            'last_name': forms.TextInput(attrs={'placeholder': 'Last Name'}),
            'address': forms.TextInput(attrs={'placeholder': 'Address'}),
            'email': forms.EmailInput(attrs={'placeholder': 'Email'}),
            'password': forms.PasswordInput(attrs={'placeholder': 'Password'})
        }

    def clean(self):
        cleaned_data = self.cleaned_data
        password = cleaned_data.get("password")
        confirm = cleaned_data.get("confirm")
        if confirm != password:
            self.add_error("password", "Passwords do not match.")
            self.add_error("confirm", "Passwords do not match.")
        if len(password) < 8:
            self.add_error("password", "Password must be greater than 8 letters.")
        if confirm == password and len(password) > 8:
            del cleaned_data['confirm']
            return cleaned_data
    • 浏览次数. py:**
def Patient(request):
    if request.method == "POST":
        form = PatientForm(request.POST, initial={'is_patient': True})
        if form.is_valid():
            Patient.objects.create(**form.cleaned_data)
            return HttpResponseRedirect('/Login/')

        else:
            for field in form.errors:
                form[field].field.widget.attrs['class'] += ' is-invalid'
            return render(request, 'Home/RegPatient.html', {'form': form})
    
    else:
        form = PatientForm(initial={'is_patient': True})
        return render(request, 'Home/RegPatient.html', {'form': form})
gojuced7

gojuced71#

找到了答案。如果没有删除确认密码字段,则只需执行以下操作:

del form.cleaned_data['confirm_pass')

然后创建模型对象。

相关问题