在ModelForm中映射不同的字段OneToOneField

时间:2013-05-20 21:04:55

标签: django django-models django-forms

我有两个与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')

这里省略了一些细节。如果您认为它们是相关的,请告诉我。

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

我该怎么做?

提前致谢

1 个答案:

答案 0 :(得分: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