我正在尝试构建注册API。在这里,我坚持这个问题,希望你们能解决我的错误并引导我走正确的道路。无论如何,谢谢。希望您能尽快得到答复。谢谢。
serializers.py
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
""" Create and return a new user"""
user = User.objects.create_user(**validated_data)
return user
models.py
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
from django.contrib.auth import get_user_model
class UserRegisterManager(BaseUserManager):
""" Helps django work with our custom user model """
def createUser(self, email, name, password=None):
""" Creates a new user profile object """
if not email:
raise ValueError("User must have an email address.")
email = self.normalize_email(email)
user = self.model(email=email, name=name)
user.set_password(password) # set_password helps to convert str into hash
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
""" Creates and saves a new superuser with given details. """
user = self.create_user(email, name, password)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
class UserRegister(AbstractBaseUser, PermissionsMixin):
""" Represents a 'user register' inside our system """
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True) # user is currently active or not
is_staff = models.BooleanField(default=False)
objects = UserRegisterManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def get_full_name(self):
""" Used to get user fullname """
return self.name
def get_short_name(self):
""" Used to get user short name """
return self.name
def __str__(self):
""" Django uses this when it need to convert the object to a string """
return self.email
这是我的模特
views.py
from django.contrib.auth.models import User
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from .serializers import UserSerializer
from . import permissions
from django.contrib.auth import get_user_model
User = get_user_model()
class UserViewSet(viewsets.ModelViewSet):
""" API endpoint that allows users to be viewed or edited. """
serializer_class = UserSerializer
queryset = User.objects.all()
# authentication_classes = (TokenAuthentication,)
# permission_classes = (permissions.UpdateProfile,)
setting.py
AUTH_USER_MODEL = 'register.UserRegister'
这有助于切换到服装用户。
admin.py
from django.contrib import admin
from .models import UserRegister
admin.site.register(UserRegister)
这就是我注册模型的方式
错误
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/register/
Django Version: 2.1.5
Python Version: 3.7.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'register',
'corsheaders']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware']
Traceback:
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\core\handlers\base.py" in _get_response
156. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\core\handlers\base.py" in _get_response
154. response = response.render()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\template\response.py" in render
106. self.content = self.rendered_content
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\response.py" in rendered_content
72. ret = renderer.render(self.data, accepted_media_type, context)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\renderers.py" in render
733. context = self.get_context(data, accepted_media_type, renderer_context)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\renderers.py" in get_context
663. raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\renderers.py" in get_raw_data_form
574. data = serializer.data.copy()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in data
563. ret = super(Serializer, self).data
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in data
266. self._data = self.get_initial()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in get_initial
413. for field in self.fields.values()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in fields
363. for key, value in self.get_fields().items():
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in get_fields
1024. info = model_meta.get_field_info(model)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\utils\model_meta.py" in get_field_info
39. forward_relations = _get_forward_relationships(opts)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\utils\model_meta.py" in _get_forward_relationships
96. not field.remote_field.through._meta.auto_created
Exception Type: AttributeError at /api/register/
Exception Value: 'NoneType' object has no attribute '_meta'
答案 0 :(得分:0)
from django.contrib.auth import get_user_model
User = get_user_model()
始终使用它来访问用户模型
from django.contrib.auth.models import User
考虑自定义用户模型。