RegisterForm()缺少1个必需的位置参数:“ request”

穆罕默德·马希尔(Mohammed Mahir)

因此,我正在创建一个自定义用户模型。这就是我在这里关注的内容我一直在关注本教程,但仍然无法完成。

错误:RegisterForm()缺少1个必需的位置参数:“ request”。

这是我的代码。

表格

from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from .models import User

class UserAdminCreationForm(forms.ModelForm):
    """
    A form for creating new users. Includes all the required
    fields, plus a repeated password.
    """
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email',)

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserAdminCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UserAdminChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = User
        fields = ('email', 'password', 'active', 'admin')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]

class LoginForm(forms.ModelForm):
    email   = forms.EmailField(label='Email')
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email', 'password',)

        widgets = {

                'email' : forms.EmailInput(
                    attrs={'class':'form-control', 'place_holder': '', }),

                'password' : forms.PasswordInput(
                    attrs={'class':'form-control' }),

                    }



class RegisterForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email',)

    def clean_email(self):
        email = self.cleaned_data.get('email')
        qs = User.objects.filter(email=email)
        if qs.exists():
            raise forms.ValidationError("email is taken")
        return email

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2


models.py

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

class UserManager(BaseUserManager):
    def create_user(self, email, full_name, password=None, is_staff=False, is_active=True, is_admin=False):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('Users must have an email address')
        if not full_name:
            raise ValueError('Users must have an full name')
        if not password:
            raise ValueError('Users must have a password')

        user = self.model(
            email=self.normalize_email(email),
        )
        user.full_name = full_name
        user.set_password(password)
        user.staff = is_staff
        user.admin = is_admin
        user.active = is_active
        user.save(using=self._db)
        return user

    def create_staffuser(self, email, password):
        """
        Creates and saves a staff user with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.staff = True
        user.save(using=self._db)
        return user

    def create_superuser(self, email, full_name, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.model(
            email=self.normalize_email(email)
        )
        user.full_name = full_name
        user.set_password(password)
        user.full_name = full_name
        user.staff = True
        user.admin = True
        user.save(using=self._db)
        return user


# Create your models here.

class User(AbstractBaseUser):
    email                   = models.EmailField(max_length=255, unique=True)
    full_name               = models.CharField(max_length=255, null=True, blank=True)
    active                  = models.BooleanField(default=True) # to login
    staff                   = models.BooleanField(default=False) # a admin user; non super-user
    admin                   = models.BooleanField(default=False) # a superuser
    created_date            = models.DateTimeField(auto_now_add=True)


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['full_name'] # Email & Password are required by default.

    objects = UserManager()

    def __str__(self):         
        return self.email

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True


    @property
    def is_staff(self):
        "Is the user a member of staff?"
        return self.staff

    @property
    def is_admin(self):
        "Is the user a admin member?"
        return self.admin

    @property
    def is_active(self):
        "Is the user active?"
        return self.active

class Account_type(models.Model):
    name                    = models.CharField(max_length=50, null=True, blank=True) 

class Profile(models.Model):
    user                    = models.OneToOneField(User, on_delete=models.CASCADE)
    account_type            = models.ForeignKey(Account_type, on_delete=models.CASCADE) 


register.html

from django.shortcuts import render, redirect
from . forms import RegisterForm, LoginForm

# Create your views here.

def RegisterForm(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            form.save()        
    else:
        form = RegisterForm()

    context = {
        'form' : form
    }
    return render(request, 'account/register.html', context)

如您所见,视图逻辑很简单。只需将请求保存到数据库中即可。本教程本身并没有说明有关登录和注册视图的任何信息。

所以,我在这里做错了什么。谢谢

威廉·范昂塞姆

问题在于您的视图RegisterForm与表单具有相同的名称,因此,如果您RegisterForm在视图中调用,它将解析为视图函数,并进行递归调用。

通常,(顶级)函数是用编写的snake_case,因此您可以将其重写为register_form,甚至更好register(因为它根本不是一种形式):

from django.shortcuts import render, redirect
from . forms import RegisterForm, LoginForm

# Create your views here.

def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('some-view-name')
    else:
        form = RegisterForm()

    context = {
        'form' : form
    }
    return render(request, 'account/register.html', context)

通常,成功的POST请求会导致重定向以实现Post / Redirect / Get模式[wiki]因此,我强烈建议您使用redirect(..)[Django-doc]并替换some-view-name为您要重定向到的视图的名称。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TypeError:detail()缺少1个必需的位置参数:“ request”

缺少1个必需的位置参数:“ request” django restframework

Django-缺少1个必需的位置参数:“ request”

错误“ TypeError:FirstForm()缺少1个必需的位置参数:'request'”

Django get_total_topup()缺少1个必需的位置参数:“ request”

Django-get_queryset()缺少1个必需的位置参数:“ request”

Django抛出TypeError:_wrapped_view()缺少1个必需的位置参数:'request'

类型错误:request() 缺少 1 个必需的位置参数:urllib3 中的“url”

Django 2.2 TypeError at /cart/checkout __init__() 缺少 1 个必需的位置参数:'request'

Django - PUT 端点身份验证器错误“wrapped_view() 缺少 1 个必需的位置参数:'request'”

文件上载AngularJS和Django:/ uploaded_file uploadFile()处的TypeError缺少1个必需的位置参数:'request'

_wrapped()缺少1个必需的位置参数:'request':方法装饰器出现问题。(Django,Ratelimit库)

如何在此处传递 Id(错误 put() 缺少 1 个必需的位置参数:'request')在表单模板 Django 中

ArrayField缺少1个必需的位置参数

__init __()缺少1个必需的位置参数

缺少1个必需的位置参数:“ pk”

缺少1个必需的位置参数:“键”

python缺少1个必需的位置参数

channel()缺少1个必需的位置参数

AssertTrue 缺少 1 个必需的位置参数

缺少1个必需的位置参数:“循环”

缺少 1 个必需的位置参数:“数字”

缺少1个必需的位置参数:'self'

缺少1个必需的位置参数:“ msg”

缺少1个必需的位置参数

缺少 1 个必需的位置参数 dt

函数缺少 1 个必需的位置参数

缺少 1 个必需的位置参数 [Telebot]

缺少 [Route: admin.request.update] [URI: admin/request/{request}] [缺少参数: request] 的必需参数