django,save()缺少1个必需的位置参数'request'

时间:2018-06-08 16:01:11

标签: python django

我尝试将create_user用于电子邮件登录作为自定义用户模型,但它无效。 save()缺少1个必需的位置参数'request'。 我怎么能解决这个问题,请帮帮我。

这是Traceback ..

文件“/Users/maxx/.local/share/virtualenvs/testauth--sM0sqjl/lib/python3.6/site-packages/rest_framework/views.py”,第480行,发送     response = handler(request,* args,** kwargs)   文件“/Users/maxx/Documents/workspace/python3/testauth/users/views.py”,第12行,在帖子中     user = serializer.save() TypeError:save()缺少1个必需的位置参数:'request'

models.py

class UserManger(BaseUserManager):

use_in_migrations = True

def _create_user(self, email, password, **extra_fields):
    if not email:
        raise ValueError('You must give email address')
    email = self.normalize_email(email)
    user = self.model(email=email, **extra_fields)
    user.set_password(password)
    user.save(using=self._db)
    return user

def create_user(self, email, password=None, **extra_fields):
    extra_fields.setdefault('is_staff', False)
    extra_fields.setdefault('is_superuser', False)
    return self._create_user(email, password, **extra_fields)

def create_superuser(self, email, password, **extra_fields):
    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)
    return self._create_user(email, password, **extra_fields)


class User(AbstractBaseUser):

email = models.EmailField(unique=True)
nick_name = models.CharField(max_length=50)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

objects = UserManger()


def __str__(self):
    return self.email

def get_full_name(self):
    return self.email

def get_short_name(self):
    return self.email

def has_perm(self, perm, obj=None):
    return True

def has_module_perms(self, app_label):
    return True

serializers.py

class RegisterSerializer(serializers.Serializer):

email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
password1 = serializers.CharField(write_only=True)
password2 = serializers.CharField(write_only=True)

def validate_email(self, email):
    email = get_adapter().clean_email(email)
    if allauth_settings.UNIQUE_EMAIL:
        if email and email_address_exists(email):
            raise serializers.ValidationError(
                _("A user is already registered with this e-mail address."))
    return email

def validate_password1(self, password):
    return get_adapter().clean_password(password)

def validate(self, data):
    if data['password1'] != data['password2']:
        raise serializers.ValidationError(_("password fields didn't match."))
    return data

def get_cleaned_data(self):
    return {
        'email': self.validated_data.get('email', ''),
        'password1': self.validated_data.get('password1', ''),
    }

def save(self, request):
    adapter = get_adapter()
    user = adapter.new_user(request)
    self.cleaned_data = self.get_cleaned_data()
    adapter.save_user(request, user, self)
    setup_user_email(request, user, [])
    return user

views.py

class UserCreateView(APIView):

def post(self, request):
    serializer = RegisterSerializer(data=request.data)
    if serializer.is_valid():
        user = serializer.save()
        if user:
            token = Token.objects.create(user=user)
            json = serializer.data
            json['token'] = token.key
            return Response(json, status=status.HTTP_201_CREATED)

    return Response(data=serializer.errors ,status=status.HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:0)

在您的RegisterSerializer中,您实施了一个save()方法,该方法需要名为request的位置参数,在UserCreateView中,您需要在该方法调用中包含该请求。< / p>

class UserCreateView(APIView):

def post(self, request):
    serializer = RegisterSerializer(data=request.data)
    if serializer.is_valid():
        user = serializer.save(request) # <---- INCLUDE REQUEST
        if user:
            token = Token.objects.create(user=user)
            json = serializer.data
            json['token'] = token.key
            return Response(json, status=status.HTTP_201_CREATED)

    return Response(data=serializer.errors ,status=status.HTTP_400_BAD_REQUEST)