Django: UNIQUE constraint failed: user.username

ぐ巨炮叔叔 提交于 2020-05-16 07:45:06

问题


I have a problem using Djangos Default user from django.contrib.auth.models but trying to use it with my custom User model, using from django.contrib.auth.models import AbstractUser.

So here is my User model:

from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager as AbstractUserManager
# from django.conf import settings
from django_countries.fields import CountryField
# https://github.com/SmileyChris/django-countries
from django.db.models.signals import post_save 
from django.dispatch import receiver


class UserManager(AbstractUserManager):
  pass

class User(AbstractUser):
    """auth/login-related fields"""
    is_a = models.BooleanField('a status', default=False)
    is_o = models.BooleanField('o status', default=False)

    def __str__(self):
        return "{} {}".format(self.first_name, self.last_name)

@receiver(post_save, sender=User) 
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        User.objects.set_password(instance.password)

and here is my Profile model:

from django.db import models
from django_countries.fields import CountryField # https://github.com/SmileyChris/django-countries
from django.contrib.auth import get_user_model
User = get_user_model()
# https://medium.com/swlh/best-practices-for-starting-a-django-project-with-the-right-user-model-290a09452b88

from django.db.models.signals import post_save 
from django.dispatch import receiver



class Profile(models.Model):
    """non-auth-related/cosmetic fields"""
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='Profile')
    birth_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True)
    nationality = CountryField(null=True)

    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)

    def __str__(self):
        return f'{self.user.username} Profile'

"""receivers to add a Profile for newly created users"""
@receiver(post_save, sender=User) 
def create_user_profile(sender, instance, created, **kwargs):
     if created:
         Profile.objects.create(user=instance)
@receiver(post_save, sender=User) 
def save_user_profile(sender, instance, **kwargs):
     instance.profile.save()

But before adding User.objects.set_password(instance.password) to my User model, I did it in py shell, which worked perfectly.

But now I added this line in my User model, and when I'm using Postman to post a User:

{
    "username":"1564",
    "password":"12345678",
    "first_name":"Al",
    "last_name":"Pongvf",
    "email":"ahgj@live.fr"
}

It gives me this error message:

IntegrityError at /user/create/
UNIQUE constraint failed: ep_user.username

Which I don't get it because I'm creating a new user with a total new username.

I've searched for a solution, but I didn't get lucky:

  • StackOverflow 1
  • StackOverflow 2
  • StackOverflow 3
  • StackOverflow 4

Does anyone know what am I missing? or doing wrong?

Thanks!

UPDATE:

Here is my User Serializer:

from rest_framework import serializers
from django.contrib.auth import get_user_model
from ..models.model_user import *
# from .serializers_profile import *


class UserIndexSerializer(serializers.ModelSerializer):
    # profile = ProfileIndexSerializer()

    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'password',
            'first_name',
            'last_name',
            'email',
            'is_a',
            'is_o'
            # 'profile'
        ]

class UserCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = [
            'username',
            'password',
            'first_name',
            'last_name',
            'email',
            'is_a',
            'is_o'
        ]

class UserDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

And here is my User View:

from rest_framework import generics
from django.contrib.auth import get_user_model
from ..models.model_user import *
from ..serializers.serializers_user import *


class UserIndex(generics.ListAPIView):
    """List all users, or create a new user."""

    queryset = User.objects.all().order_by('id')
    serializer_class = UserIndexSerializer

class UserCreate(generics.CreateAPIView):
    """List all art pieces, or create a new art piece."""

    queryset = User.objects.all()
    serializer_class = UserCreateSerializer

class UserDetails(generics.RetrieveUpdateDestroyAPIView):
    """Retrieve, update or delete a user instance."""

    queryset = User.objects.all()
    serializer_class = UserDetailsSerializer

And my admin.py:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

# Register your models here.
from .models.model_user import *
from .models.model_profile import *

admin.site.register(User, UserAdmin)
admin.site.register(Profile)

来源:https://stackoverflow.com/questions/60940700/django-unique-constraint-failed-user-username

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!