The goal is to test creating a new custom user using APITestCase.
In models.py got two new classes inheriting from AbstractBaseUser and BaseUserManager, respectively
class MyUser(AbstractBaseUser):
objects = MyUserManager()
class Meta:
db_table = 'user_entity'
user_id = models.AutoField(primary_key=True)
#username = models.CharField(max_length=USERNAME_MAX_LENGTH, unique=True, validators=[validators.validate_username])
username = models.CharField(max_length=20, unique=True)
password = models.CharField(max_length=256)
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
email = models.EmailField(verbose_name='email', max_length=100, unique=True)
last_access = models.DateField(default=datetime.date.today)
creation_date = models.DateTimeField(default=timezone.now)
last_update = models.DateField(default=datetime.date.today)
user_type = models.IntegerField()
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'user_type']
def __str__(self):
return str(self.user_id) + " (%s)" % str(self.email)
def has_perm(self, perm, obj=None):
return self.user_type == 0
def has_module_perms(self, app_label):
return True
and
class MyUserManager(BaseUserManager):
def _create_generic_user(self, email, username, password, first_name, last_name, user_type):
if not username:
raise ValueError("Username cannot be empty")
if not email:
raise ValueError("Email cannot be empty")
if not first_name:
raise ValueError("First name cannot be empty")
if not last_name:
raise ValueError("Last name cannot be empty")
if not password:
raise ValueError("Password cannot be empty")
user = self.model(
username=username,
first_name=first_name,
last_name=last_name,
email=self.normalize_email(email),
user_type=user_type,
is_staff=user_type == 0,
is_active=False
)
user.set_password(password)
user.save(user=self._db)
return user
def create_user(self, email, username, password, first_name, last_name):
return self._create_generic_user(email, username, password, first_name, last_name, 2)
def create_admin(self, email, username, password, first_name, last_name):
return self._create_generic_user(email, username, password, first_name, last_name, 0)
Then, in serializers.py created a MyUserSerializer for DRF inheriting from a ModelSerializer
class MyUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
required=True, # make sure email is provided
validators=[UniqueValidator(queryset=MyUser.objects.all())] # make sure email is unique
)
username = serializers.CharField(
required=True,
validators=[UniqueValidator(queryset=MyUser.objects.all())],
min_length=5,
max_length=20
)
password = serializers.CharField(
write_only=True,
required=True,
max_length=256
)
first_name = serializers.CharField(
required=True,
max_length=25
)
last_name = serializers.CharField(
required=True,
max_length=25
)
def create(self, validated_data):
user = MyUser.objects.create_user(validated_data['email'], validated_data['username'], validated_data['password'],
validated_data['first_name'], validated_data['last_name'])
return user
class Meta:
model = MyUser
fields = ('user_id', 'email', 'username', 'password', 'first_name', 'last_name')
a view with APIView
class MyUserCreate(APIView):
"""
Creates the user.
"""
def post(self, request, format='json'):
serializer = MyUserSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
if user:
return Response(serializer.data, status=status.HTTP_201_CREATED)
and urls
urlpatterns = [
url(r'api/users^$', views.MyUserCreate.as_view(), name='user-create'),
]
From this, then went on to create a simple test of creating users
class MyUserTest(APITestCase):
def setUp(self):
# Create a user
self.test_user = MyUser.objects.create_user('tiagomartinsperes#gmail.com', 'tiagoperes', 'EWFdfew45te!sadf32', 'Tiago', 'Peres')
# URL for creating user
self.create_url = reverse('user-create')
def test_create_user(self):
"""
Ensure we can create a new user and a valid token is created with it.
"""
data = {
'email': 'cnf32344#zzrgg.com',
'username': 'andresantos',
'password': 'test',
'first_name': 'André',
'last_name': 'Santos'
}
response = self.client.post(self.create_url , data, format='json')
# Make sure we have two users in the database
self.assertEqual(MyUser.objects.count(), 2)
# Return 201
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
# Return the username and email upon successful creation
self.assertEqual(response.data['email'], data['email'])
self.assertEqual(response.data['username'], data['username'])
self.assertFalse('password' in response.data)
self.assertEqual(response.data['first_name'], data['first_name'])
self.assertEqual(response.data['last_name'], data['last_name'])
Thing is, running
python manage.py test
gets the following error:
Creating test database for alias 'default'... System check identified
no issues (0 silenced). E
====================================================================== ERROR: test_create_user (user.tests.MyUserTest) Ensure we can create a
new user and a valid token is created with it.
---------------------------------------------------------------------- Traceback (most recent call last): File
"C:\Users\tiago\Desktop\letsgo\COVID19-be\django_server\user\tests.py",
line 10, in setUp
self.test_user = MyUser.objects.create_user('tiagomartinsperes#gmail.com',
'tiagoperes', 'EWFdfew45te!sadf32', 'Tiago', 'Peres') File
"C:\Users\tiago\Desktop\letsgo\COVID19-be\django_server\user\models.py",
line 38, in create_user
return self._create_generic_user(email, username, password, first_name, last_name, 2) File
"C:\Users\tiago\Desktop\letsgo\COVID19-be\django_server\user\models.py",
line 34, in _create_generic_user
user.save(user=self._db) File "C:\Users\tiago\Desktop\letsgo\unstable\lib\site-packages\django\contrib\auth\base_user.py",
line 66, in save
super().save(*args, **kwargs) TypeError: save() got an unexpected keyword argument 'user'
---------------------------------------------------------------------- Ran 1 test in 0.172s
FAILED (errors=1) Destroying test database for alias 'default'...
and no users are being created. What can I do to solve it?
The issue is at here
user.save(user=self._db)
The django Model save has the following signature.
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
Since you are passing a database as value(self._db), I think you are expected to write
user.save(using=self._db)
Related
I am creating a cross-platform application in which the users are - Admin, Instructor, and Student. And for registering a new user privilege is only for admin users, so an admin user can add another admin, instructor, and student. I am trying to make nested serializers by which a UserProfile (AdminProfile, InstructorProfile, or StudentProfile) when created also creates User. I am new to Django and DRF. How can this be done?
serializers.py
from rest_framework import serializers
from .models import User, ProfileAdmin
# # This will have GET method for seeing the users according to the userType.
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username', 'password', 'user_type']
extra_kwargs = {'password': {'write_only': True}}
class UserProfileSerializer(serializers.ModelSerializer):
user_account = UserSerializer(many=False)
class Meta:
model = ProfileAdmin
fields = ['email', 'first_name', 'last_name', 'address', 'telNum', 'aliasMailID', 'MSteamsID', 'user_account']
def create(self, validated_data):
account_data = validated_data.pop('user_account')
user = ProfileAdmin.objects.create(**validated_data)
User.objects.create(**account_data)
return user
def update(self, instance, validated_data):
account_data = validated_data.pop('user_account')
user_account = instance.user_account
instance.email = validated_data.get('email', instance.email)
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.address = validated_data.get('address', instance.address)
instance.telNum = validated_data.get('telNum', instance.telNum)
instance.aliasMailID = validated_data.get('aliasMailID', instance.aliasMailID)
instance.MSteamsID = validated_data.get('MSteamsID', instance.MSteamsID)
instance.save()
user_account.username = account_data.get('username', user_account.username)
user_account.user_type = account_data.get('user_type', user_account.user_type)
return instance
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser, PermissionsMixin, UserManager, AbstractBaseUser
from django.conf import settings
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.utils.translation import gettext_lazy as _
class CustomAccountManager(UserManager):
def _create_user(self, username, password, user_type, **extra_fields):
if not username:
raise ValueError(_('The Username must be set'))
if not password:
raise ValueError('The password must be set')
if not user_type:
raise ValueError('The user type must be set')
username = self.model.normalize_username(username)
user = self.model(username=username, user_type=user_type, **extra_fields)
user.set_password(password)
user.save()
return user
def create_user(self, username, password, user_type, **extra_fields):
if user_type == 'STUDENT' or user_type == 'INSTRUCTOR':
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(username, password, user_type, **extra_fields)
def create_superuser(self, username, password, user_type, **extra_fields):
# if is_userType == 'Admin'
if user_type == 'ADMIN':
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(username, password, user_type, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
USER_TYPE_CHOICES = (
('ADMIN', 'admin'),
('INSTRUCTOR', 'instructor'),
('STUDENT', 'student'),
)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this admin site.'),
)
user_type = models.CharField(max_length=40, choices=USER_TYPE_CHOICES)
username = models.CharField(max_length=30, unique=True)
password = models.CharField(_('password'), max_length=128)
objects = CustomAccountManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['password', 'user_type']
class ProfileAdmin(User, models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField(verbose_name="email", max_length=85, unique=True)
aliasMailID = models.EmailField(verbose_name="aliasMailID", max_length=85, unique=True, blank=False)
address = models.TextField()
MSteamsID = models.EmailField(verbose_name="MSteamsID", max_length=85, unique=True, blank=False)
telNum = PhoneNumberField(null=False, blank=False, unique=True
views.py
class RegisterUserAPI(generics.GenericAPIView):
serializer_class = UserProfileSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
return Response({
"user": UserProfileSerializer(user, context=self.get_serializer_context()).data,
})
urls.py
from django.conf.urls import url, include
from django.urls import path
from .views import RegisterUserAPI
urlpatterns = [
path('users/', RegisterUserAPI.as_view(), name="userRegister"),
]
When I run it, I have access to http://localhost:8000/api/users and can see the form to fill the required field, but as soon as I hit POST I get a TypeError:
TypeError at /api/users/
User() got an unexpected keyword argument 'user'
Request Method: POST
Request URL: http://127.0.0.1:8000/api/users/
Django Version: 3.0
Exception Type: TypeError
Exception Value:
User() got an unexpected keyword argument 'user'
Exception Location: C:\PyCharm\MobileLearningApplication\venv\lib\site-packages\django\db\models\base.py in __init__, line 500
Python Executable: C:\PyCharm\MobileLearningApplication\venv\Scripts\python.exe
Python Version: 3.8.9
Python Path:
['C:\\PyCharm\\MobileLearningApplication\\MobileLearningApplication',
'C:\\Python\\python38.zip',
'C:\\Python\\DLLs',
'C:\\Python\\lib',
'C:\\Python',
'C:\\PyCharm\\MobileLearningApplication\\venv',
'C:\\PyCharm\\MobileLearningApplication\\venv\\lib\\site-packages']
Server time: Sat, 9 Oct 2021 09:37:44 +0000
i have a custom user model that looks like this
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.base_user import BaseUserManager
# user manager code
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""
Creates and saves a User with the given email, first name,
last name and password.
"""
if not email:
raise ValueError("Users must have an email address")
user = self.model(
email=self.normalize_email(email),
**extra_fields,
)
user.set_password(password)
user.save(using=self._db)
return user
# Create your models here.
class CustomUser(AbstractUser):
email = models.EmailField(unique=True)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def __str__(self):
return self.email
my serializer.py
class RegisteSerializer(serializers.Serializer):
password = serializers.CharField(style={"input_type": "password"},
write_only=True)
password2 = serializers.CharField(style={"input_type": "password"},
write_only=True)
email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
first_name = serializers.CharField(min_length=2, max_length=50)
last_name = serializers.CharField(min_length=2, max_length=50)
USERNAME_FIELD = 'email'
class Meta:
model = User
fields = [
'id',
'first_name',
'last_name',
"email",
"password",
"password2",
]
extra_kwargs = {'password': {'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_password(self, password):
return get_adapter().clean_password(password)
def validate(self, data):
if data['password'] != data['password2']:
raise serializers.ValidationError(
("The two password fields didn't match."))
return data
def get_cleaned_data(self):
return {
'first_name': self.validated_data.get('first_name', ''),
'last_name': self.validated_data.get('last_name', ''),
'password': self.validated_data.get('password', ''),
'password2': self.validated_data.get('password', ''),
'email': self.validated_data.get('email', ''),
}
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, [])
user.save()
return user
when i register using endpoint http://127.0.0.1:8000/api/dj-rest-auth/registration/
i am greeted with all fields the way i want it
but when i try to login http://127.0.0.1:8000/api/dj-rest-auth/login/
i still see username
even after configuring my django allauth
# django-allauth configuarations
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = True
i am new to django rest framework i dont want to rewrite everything i dont even know how
I have a wishlist app with a custom user model. I added the user as the foreign key to each wishlist item. However, I am only able to add the foreign key by specifying a default user, even after deleting the existing db files and running makemigrations and migrate. The default user is associated with the wishlist item regardless of which user is logged in, and if I don't include a default user I get the "NOT NULL constraint failed: wishlist_wish.user_id" error.
How can I update the code so that the wishlist item is associated with the logged-in user creating the item?
A related question is whether I need to include a user id in my custom user model? I tried doing this as well and ran into the same problem. Thanks in advance.
Wish Model:
class Wish(models.Model):
name = models.TextField()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
def __str__(self):
return self.name
Wish View:
def add_wish(request):
user = request.user
wishes = Wish.objects.filter(user=request.user)
if request.method == 'POST':
form = WishForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = WishForm()
context = {'form' : form, 'wishes' : wishes}
return render(request, 'wishlist/add_wish.html', context)
Wish Form:
class WishForm(ModelForm):
class Meta:
model = Wish
fields = ('name', )
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class' : 'textarea', 'placeholder' : 'Enter wishlist item'})
Custom User (Account) Model:
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, first_name, last_name, password=None):
if not email:
raise ValueError("Users must provide an email to create an account.")
if not first_name:
raise ValueError("Users must provide full name to create an account.")
if not last_name:
raise ValueError("Users must provide full name to create an account.")
user = self.model(
email = self.normalize_email(email),
username = username,
first_name = first_name,
last_name = last_name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, first_name, last_name, password):
user = self.create_user(
email = self.normalize_email(email),
username = username,
first_name = first_name,
last_name = last_name,
password = password
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
email = models.EmailField(max_length=100, unique=True)
username = models.CharField(max_length=100, unique=False, blank=True, null=True)
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
objects = MyAccountManager()
def __str__(self):
return self.first_name + " " + self.last_name
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
You simply need to provide a value for the .user for the Wish you are creating:
from django.contrib.auth.decorators import login_required
#login_required
def add_wish(request):
wishes = Wish.objects.filter(user=request.user)
if request.method == 'POST':
form = WishForm(request.POST)
if form.is_valid():
form.instance.user = requst.user
form.save()
return redirect('home')
else:
form = WishForm()
context = {'form' : form, 'wishes' : wishes}
return render(request, 'wishlist/add_wish.html', context)
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
I have this problem for a month.
I'm using abstractbasemodel and basemanagerto to create a login and signup API using rest framework.
However, when I create a user password, it is saved as raw data since I use set_password() method and custom model manager confuses me...
This is my code :
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('id' ,'email' ,'name' ,'password')
extra_kwargs = {
'password':{
'write_only':'True',
'style': {'input_type': 'password'}
}
}
def create(self, validated_data):
user = UserProfile.people.create_user(
email = validated_data['email'],
name = validated_data['name'],
password = validated_data['password']
)
class UserProfileViewSet(viewsets.ModelViewSet):
serializer_class = serializers.UserProfileSerializer
queryset = models.UserProfile.people.all()
authentication_classes = (TokenAuthentication, )
permission_classes = (UpdateOwnProfile, )
filter_backends = (SearchFilter, )
search_fields = ('name', 'email')
class UserLoginApiView(ObtainAuthToken):
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
class UserProfileManager(BaseUserManager):
def create_user(self, email, name, password=None):
print("user model manager")
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)
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
user = self.create_user(email, name, password)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
class UserProfile(AbstractBaseUser,PermissionsMixin):
email = models.EmailField(max_length=255,unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
people = UserProfileManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def get_full_name(self):
return self.name
def get_short_name(self):
return self.name
def __str__(self):
return self.email
class Profile(models.Model):
user = models.OneToOneField(UserProfile,on_delete=models.CASCADE,relat ed_name="Profile")
location = models.CharField(max_length=100,blank=True,null=True)
bio = models.CharField(max_length=100,blank=True,null=True)
creationDate = models.DateTimeField(auto_now_add=True)
follower = models.ManyToManyField(UserProfile,related_name="Following",blank=True)
class Meta:
verbose_name='Profile'
verbose_name_plural='Profiles'
I also defined auth user model in settings :
AUTH_USER_MODEL='profiles.UserProfile'
to make sure Django uses my custom user model.
I don't know whats wrong as there is no error and only superusers that are created in terminal using manage.py are saved with hashed password.
Users which are created with my viewsets are saved with raw password.
First, I named the model manager "objects" and now, its people but the create user method wont run at all.
You can use django's built in hasher to create hashed password. It can be applied in .create method. First import from django.contrib.auth.hashers import make_password and then modify .create() method,
def create(self, validated_data):
user = UserProfile.people.create_user(
email = validated_data['email'],
name = validated_data['name'],
password = make_password(validated_data['password']) # here
)
return user
Or
if you don't override the .create() method then add the following validate_password method in serializer,
The validate_password is ran, everytime a new object has to be created
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('id' ,'email' ,'name' ,'password')
extra_kwargs = {
'password':{
'write_only':'True',
'style': {'input_type': 'password'}
}
}
def validate_password(self, value: str) -> str:
return make_password(value)
I want to register a new user with a associated list of categories.
I have a table called categories with list of unique categories (category id, category name).
I have a table called accounts with a list of users (username, email, password and list of associated categories).
I have a table called account_categories which is a mapping between users and categories.
Unfortunately when I am trying to create new user I receive an error that provided categories already exists. I don't want to update categories table. I want to update accounts and account_categories.
What am I doing wrong?
model.py
class Category(models.Model):
categoryname = models.CharField(unique=True, max_length=50)
def __str__(self):
return "{0}".format(self.categoryname)
class AccountManager(BaseUserManager):
def create_user(self, email, age, categories, password=None, **kwargs):
if not email:
raise ValueError('Users must have a valid email address.')
if not kwargs.get('username'):
raise ValueError('Users must have a valid username.')
if not age:
raise ValueError('Users must have a valid age.')
if not categories:
raise ValueError('Users must choose at least one intrest.')
account = self.model(
email=self.normalize_email(email), age=age, categories=categories, username=kwargs.get('username')
)
account.set_password(password)
account.save()
return account
def create_superuser(self, email, age, categories, password, **kwargs):
account = self.create_user(email=email, age=age, categories=categories, password=password, **kwargs)
account.is_admin = True
account.save()
return account
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
username = models.CharField(unique=True, max_length=25)
age = models.SmallIntegerField()
categories = models.ManyToManyField(Category)
objects = AccountManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['age', 'email']
def __unicode__(self):
return self.email
serializers.py
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'categoryname')
class AccountSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True, required=False)
confirm_password = serializers.CharField(write_only=True, required=False)
categories = CategorySerializer(many=True)
class Meta:
model = Account
fields = ('id', 'email', 'username', 'age', 'categories', 'password', 'confirm_password',)
def create(self, validated_data):
return Account.objects.create(**validated_data)
views.py
class AccountViewSet(viewsets.ModelViewSet):
lookup_field = 'username'
queryset = Account.objects.all()
serializer_class = AccountSerializer
def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS:
return (permissions.AllowAny(),)
if self.request.method == 'POST':
return (permissions.AllowAny(),)
return (permissions.IsAuthenticated(), IsAccountOwner(),)
def create(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
Account.objects.create_user(**serializer.validated_data)
return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
return Response({
'status': 'Bad request',
'message': 'Account could not be created with received data. Probably this email / username has already been used.' + str(serializer.errors) + str(request.data) #+ str(serializer.is_valid())
}, status=status.HTTP_400_BAD_REQUEST)
database scheme
http://postimg.org/image/o15ybcf9f/
error
http://postimg.org/image/4i5muo8fz/