小编典典

以Django形式获取请求数据

django

是否可以在表单类中获取request.user数据?我想清理一个电子邮件地址以确保它是唯一的,但是如果它是当前用户的电子邮件地址,则它应该通过。

这是我目前拥有的东西,非常适合创建新用户,但是如果我要编辑用户,则会遇到他们的电子邮件无法验证的问题,因为它已经被采用。如果我可以使用request.user.email检查这是他们的电子邮件,则可以解决我的问题,但是我不确定该怎么做。

class editUserForm(forms.Form):
    email_address = forms.EmailField(widget=forms.TextInput(attrs={'class':'required'}))

    def clean_email_address(self):
        this_email = self.cleaned_data['email_address']
        test = UserProfiles.objects.filter(email = this_email)
        if len(test)>0:
            raise ValidationError("A user with that email already exists.")
        else:
            return this_email

阅读 437

收藏
2020-03-29

共1个答案

小编典典

正如ars和Diarmuid所指出的那样,你可以传递request.user你的表单,并将其用于验证电子邮件。但是,Diarmuid的代码是错误的。该代码应实际读取:

from django import forms

class UserForm(forms.Form):
    email_address = forms.EmailField(widget = forms.TextInput(attrs = {'class':'required'}))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(UserForm, self).__init__(*args, **kwargs)

    def clean_email_address(self):
        email = self.cleaned_data.get('email_address')
        if self.user and self.user.email == email:
            return email
        if UserProfile.objects.filter(email=email).count():
            raise forms.ValidationError(u'That email address already exists.')
        return email

然后,在你看来,可以这样使用它:

def someview(request):
    if request.method == 'POST':
        form = UserForm(request.POST, user=request.user)
        if form.is_valid():
            # Do something with the data
            pass
    else:
        form = UserForm(user=request.user)
    # Rest of your view follows

请注意,你应该将request.POST作为关键字参数传递,因为构造函数希望将“ user”作为第一个位置参数。

这样,你需要将其user作为关键字参数传递。你可以将其request.POST作为位置参数或关键字参数(通过data=request.POST)传递。

2020-03-29