' WSGIRequest'对象没有属性' post'使用自定义注册表单

时间:2015-03-05 18:59:00

标签: python django forms django-1.7

我看过很多有类似问题的帖子,答案对我的代码没有任何作用。 我正在使用自定义注册表单来处理我需要的电子邮件。它中的大多数代码都是基于django内置的代码。我试图基于django.contrib.auth.forms.UserCreationForm创建一个新的表单类,但仍然会遇到相同的错误。

基于django中的表单

class UserCreateFrom(UserCreationForm):
    """
    A form that creates a user, with no privileges, from the given username and
    password.
    """
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'duplicate_email': _("That email is already in use"),
        'password_mismatch': _("The two password fields didn't match."),
    }
    email = forms.EmailField(label=_("Email Address"),
                             required=True,
                             help_text="Required. Your Email Address for password resets, and other emails from us")

    def clean_email(self):
        email = self.cleaned_data["email"]
        try:
            User._default_manager.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError(
            self.error_messages['duplicate_email'],
            code='duplicate_email',
        )

目前正在使用的表格

class UserCreateFrom(forms.ModelForm):
    """
    A form that creates a user, with no privileges, from the given username and
    password.
    """
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'duplicate_email': _("That email is already in use"),
        'password_mismatch': _("The two password fields didn't match."),
    }
    username = forms.RegexField(label=_("Username"), max_length=30,
                                regex=r'^[\w.@+-]+$',
                                help_text=_("Required. 30 characters or fewer. Letters, digits and "
                                            "@/./+/-/_ only."),
                                error_messages={
                                    'invalid': _("This value may contain only letters, numbers and "
                                                 "@/./+/-/_ characters.")
                                    }
                                )
    email = forms.EmailField(label=_("Email Address"),
                             required=True,
                             help_text="Required. Your Email Address for password resets, and other emails from us")
    password1 = forms.CharField(label=_("Password"),
                                widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"),
                                widget=forms.PasswordInput,
                                help_text=_("Enter the same password as above, for verification."))

    class Meta:
        model = User
        fields = ("username",)

    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            User._default_manager.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(
            self.error_messages['duplicate_username'],
            code='duplicate_username',
        )

    def clean_email(self):
        email = self.cleaned_data["email"]
        try:
            User._default_manager.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError(
            self.error_messages['duplicate_email'],
            code='duplicate_email',
        )

    def clean_password2(self):
        password1 = self.cleaned_data["password1"]
        password2 = self.cleaned_data["password2"]
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return password2

    def save(self, commit=True):
        user = super(UserCreateFrom, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

视图,我无法处理表单是否有效,因为我无法使用它而没有数据UserCreateFrom是我在同一个应用程序中从froms.py导入的自定义注册表单。< / p>

@sensitive_post_parameters()
@csrf_protect
@never_cache
def register(request):
    """
    Allow registration of new users
    :param request:
    :return:
    """
    context = {}
    form = UserCreateFrom(data=request.post)
    context.update({'form': form})
    if request.method == 'POST' and form.is_valid():
        return render(request, 'test.html', context)
    else:
        return render(request, 'register.html', context)

如果我将form = UserCreateFrom(data=request.post)切换为form = UserCreateFrom(request),我会收到WSGIRequest&#39;对象没有属性&#39; get&#39;错误,但这种方式至少是模板中的错误,通过`{{form}}调用表单,而不是视图。

1 个答案:

答案 0 :(得分:0)

数据属性称为request.POST

但是你应该把它移到检查方法的块中。