1

我有两个与 OneToOneField 相关的 django 模型。我将显示相关字段:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, db_index=True)

class PasswordRecovery(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    token = models.CharField(default=utils.make_token)
    password = models.CharField(max_length=128)

然后我有一个 PasswordRecovery 模型的表格

class PasswordRecoveryForm(forms.ModelForm):
    password_check = forms.CharField(max_length=128)
    class Meta:
        model = PasswordRecovery
        fields = ('user', 'password', 'password_check')

这里省略了一些细节。告诉我你是否认为它们相关。

问题是用户字段显示为“选择”元素,我希望它是一个电子邮件字段。而不是能够从列表中选择一个用户,我想要它而不是要求输入电子邮件。

我怎样才能做到这一点?

提前致谢

4

1 回答 1

1

您应该重写 clean_user 方法以传递 User 对象

class PasswordRecoveryForm(forms.ModelForm):

    user = forms.EmailField(required=True)
    password_check = forms.CharField(max_length=128)

    class Meta:
        model = PasswordRecovery
        fields = ('user', 'password', 'password_check')

    def clean_user(self):
        user_email = self.cleaned_data['user']
        if User.objects.get(email__iexact=user_email):
            return User.objects.get(email__iexact=user_email)
        return None

    #If you wanna to fill in the email add this
    def __init__(self, *args, **kwargs):
        super(PasswordRecoveryForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['user'].initial = self.instance.user.email
于 2013-05-20T21:23:19.060 回答