Django RegisterForm()缺少1个必需的位置参数:';请求';

Django RegisterForm()缺少1个必需的位置参数:';请求';,django,django-custom-user,Django,Django Custom User,因此,我正在制作一个自定义用户模型。这就是我所关注的。我一直在学习教程,但仍然做不到 错误:RegisterForm()缺少1个必需的位置参数:“请求”。 这是我的密码 forms.py from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User class UserAdminCreationForm(forms.ModelF

因此,我正在制作一个自定义用户模型。这就是我所关注的。我一直在学习教程,但仍然做不到

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

这是我的密码

forms.py

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)
正如您所看到的,视图逻辑很简单。只是将请求保存到数据库中。教程本身没有告诉任何关于登录和注册视图的内容

那么,我做错了什么。
谢谢

问题在于您的视图
注册表执行
与表单同名,因此如果您在视图中调用
注册表执行
,它将解析为视图函数,并进行递归调用

通常(顶级)函数是在
snake\u case
中编写的,因此您可以将其重写为
register\u form
,或者更好的
register
(因为它根本不是一个表单):

从django.shortcuts导入渲染,重定向
从…起表单导入注册表,LoginForm
#在这里创建您的视图。
def寄存器(请求):
如果request.method==“POST”:
form=RegisterForm(request.POST)
如果form.is_有效():
form.save()
返回重定向('some-view-name')
其他:
form=RegisterForm()
上下文={
“形式”:形式
}
返回呈现(请求'account/register.html',上下文)

通常,成功的POST请求会导致重定向以实现。因此,我强烈建议您使用要重定向到的视图的名称来替换
某些视图名称。

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

通常(顶级)函数是在
snake\u case
中编写的,因此您可以将其重写为
register\u form
,或者更好的
register
(因为它根本不是一个表单):

从django.shortcuts导入渲染,重定向
从…起表单导入注册表,LoginForm
#在这里创建您的视图。
def寄存器(请求):
如果request.method==“POST”:
form=RegisterForm(request.POST)
如果form.is_有效():
form.save()
返回重定向('some-view-name')
其他:
form=RegisterForm()
上下文={
“形式”:形式
}
返回呈现(请求'account/register.html',上下文)

通常,成功的POST请求会导致重定向以实现。因此,我强烈建议您使用并替换
某些视图名称
,使用您要重定向到的视图名称。

视图与表单名称相同,因此您可以“覆盖”表单引用。视图与表单名称相同,因此您可以“覆盖”表单引用。太棒了,从未注意到这一点。谢谢你给我额外的提示。我也很喜欢,如果你能看一看,我还有一个问题。谢谢你太棒了,我从没注意到。谢谢你给我额外的提示。我也很喜欢,如果你能看一看,我还有一个问题。非常感谢。
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)