以Django形式获取请求数据

时间:2023-02-04 20:09:10

Is it possible to get request.user data in a form class? I want to clean an email address to make sure that it's unique, but if it's the current users email address then it should pass.

有可能收到请求吗?表单类中的用户数据?我想清理一个电子邮件地址以确保它是唯一的,但是如果它是当前用户的电子邮件地址,那么它应该会通过。

This is what I currently have which works great for creating new users, but if I want to edit a user I run into the problem of their email not validating, because it comes up as being taken already. If I could check that it's their email using request.user.email then I would be able to solve my problem, but I'm not sure how to do that.

这就是我目前所拥有的对创建新用户非常有用的东西,但是如果我想要编辑一个用户,我遇到了他们的电子邮件的问题,而不是验证,因为它已经被采用了。如果我可以用request.user检查他们的邮件。这样我就能解决我的问题了,但我不知道该怎么做。

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

4 个解决方案

#1


58  

As ars and Diarmuid have pointed out, you can pass request.user into your form, and use it in validating the email. Diarmuid's code, however, is wrong. The code should actually read:

正如ars和Diarmuid所指出的,您可以传递请求。用户进入你的表单,并使用它验证电子邮件。然而,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

Then, in your view, you can use it like so:

那么,在您看来,您可以这样使用它:

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

Note that you should pass request.POST as a keyword argument, since your constructor expects 'user' as the first positional argument.

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

Doing it this way, you need to pass user as a keyword argument. You can either pass request.POST as a positional argument, or a keyword argument (via data=request.POST).

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

#2


24  

Here's the way to get the user in your form when using generic views:

以下是在使用通用视图时让用户使用表单的方法:

In the view, pass the request.user to the form using get_form_kwargs:

在视图中,传递请求。使用get_form_kwargs的表单用户:

class SampleView(View):
    def get_form_kwargs(self):
        kwargs = super(SampleView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

In the form you will receive the user with the __init__ function:

在表单中,您将收到具有__init__功能的用户:

class SampleForm(Form):
    def __init__(self, user, *args, **kwargs):
        super(SampleForm, self).__init__(*args, **kwargs)
        self.user = user

#3


3  

Just so you know, with Django 1.4 and generic class based CreateView and UpdateView, a self.instance is populated on each model form, which allows you to compare the POSTed email vs the current user email.

正如您所知道的,使用Django 1.4和基于通用类的CreateView和UpdateView,一个self。每个模型表单上都填充了实例,这允许您比较已发布的电子邮件和当前的用户电子邮件。

Here is a code sample, using mixin

这是一个使用mixin的代码示例

class EmailUniqueMixin(object):
    """
    Ensure each User's email is unique
    on the form level
    """
    def clean_email(self):
        email = self.cleaned_data['email']
        existing_email = User.objects.filter(email=email).exclude(pk=self.instance.id)
        if existing_email:
            raise forms.ValidationError('That email address already exists')
        else:
            return email

#4


0  

Not that I'm aware of. One way to handle this is have your Form class's __init__ take an optional email parameter, which it can store as an attribute. If supplied at form creation time, it can use that during validation for the comparison you're interested in.

我不知道。处理此问题的一种方法是让您的表单类的__init__接受一个可选的电子邮件参数,它可以将其作为属性存储。如果在表单创建时提供,它可以在您感兴趣的比较的验证过程中使用它。

#1


58  

As ars and Diarmuid have pointed out, you can pass request.user into your form, and use it in validating the email. Diarmuid's code, however, is wrong. The code should actually read:

正如ars和Diarmuid所指出的,您可以传递请求。用户进入你的表单,并使用它验证电子邮件。然而,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

Then, in your view, you can use it like so:

那么,在您看来,您可以这样使用它:

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

Note that you should pass request.POST as a keyword argument, since your constructor expects 'user' as the first positional argument.

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

Doing it this way, you need to pass user as a keyword argument. You can either pass request.POST as a positional argument, or a keyword argument (via data=request.POST).

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

#2


24  

Here's the way to get the user in your form when using generic views:

以下是在使用通用视图时让用户使用表单的方法:

In the view, pass the request.user to the form using get_form_kwargs:

在视图中,传递请求。使用get_form_kwargs的表单用户:

class SampleView(View):
    def get_form_kwargs(self):
        kwargs = super(SampleView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

In the form you will receive the user with the __init__ function:

在表单中,您将收到具有__init__功能的用户:

class SampleForm(Form):
    def __init__(self, user, *args, **kwargs):
        super(SampleForm, self).__init__(*args, **kwargs)
        self.user = user

#3


3  

Just so you know, with Django 1.4 and generic class based CreateView and UpdateView, a self.instance is populated on each model form, which allows you to compare the POSTed email vs the current user email.

正如您所知道的,使用Django 1.4和基于通用类的CreateView和UpdateView,一个self。每个模型表单上都填充了实例,这允许您比较已发布的电子邮件和当前的用户电子邮件。

Here is a code sample, using mixin

这是一个使用mixin的代码示例

class EmailUniqueMixin(object):
    """
    Ensure each User's email is unique
    on the form level
    """
    def clean_email(self):
        email = self.cleaned_data['email']
        existing_email = User.objects.filter(email=email).exclude(pk=self.instance.id)
        if existing_email:
            raise forms.ValidationError('That email address already exists')
        else:
            return email

#4


0  

Not that I'm aware of. One way to handle this is have your Form class's __init__ take an optional email parameter, which it can store as an attribute. If supplied at form creation time, it can use that during validation for the comparison you're interested in.

我不知道。处理此问题的一种方法是让您的表单类的__init__接受一个可选的电子邮件参数,它可以将其作为属性存储。如果在表单创建时提供,它可以在您感兴趣的比较的验证过程中使用它。