У меня проблема в Django регистрации в просмотрах - PullRequest
1 голос
/ 22 февраля 2020

Я новичок в Django. Я пытался зарегистрироваться с пользовательским пользователем, и я борюсь с ошибками.

views.py

from django.shortcuts import render
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth import authenticate,login,logout
from django.views.generic import FormView,TemplateView,ListView
from .forms import RegisterForm
from .models import User
# Create your views here.




#user-login view
def register(request):
    registred=False
    if request.method=="POST":

        user_register=RegisterForm(data=request.POST)
        if user_register.is_valid():
            user=User.save()
            user.set_password(user.password)
            user.save()
            registred=True
            return HttpResponseRedirect(reverse('index'))
        else:
            return HttpResponse('there is a problem')
    else:
        return render(request,'register.html',{'registred':registred,'user_register':RegisterForm})


def user_login(request):
    if request.method=='POST':
        email=request.POST.get('email')
        password=request.POST.get('password')

        user=authenticate(email=email,password=password)

        if user is not None:
            return HttpResponseRedirect(reverse('index'))
        else:
            return HttpResponse("Account not found")
    else:
        return render(request,'login.html')

#user-logout view
@login_required
def user_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('index'))

#registration view

models.py

# accounts.models.py

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

# accounts.models.py

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

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        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, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.staff = True
        user.admin = True
        user.save(using=self._db)
        return user

# hook in the New Manager to our Model



class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    username=models.CharField(default='',unique=True,max_length=50)
    full_name=models.CharField(default='',max_length=50)
    short_name=models.CharField(default='',max_length=50)
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False) # a admin user; non super-user
    admin = models.BooleanField(default=False) # a superuser
    # notice the absence of a "Password field", that is built in.

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

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

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

    def __str__(self):              # __unicode__ on Python 2
        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
    objects = UserManager()

ошибка :

TypeError at /register/
save() missing 1 required positional argument: 'self'

1 Ответ

1 голос
/ 22 февраля 2020

С views.py, удалите user=User.save(), что недопустимо, если у вас нет экземпляра (того самого, который отсутствует)

    user_register=RegisterForm(data=request.POST)
    if user_register.is_valid():
        user = User()
        user.set_password(user.password)
        user.save()
        registred=True
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...