i have follwing structure:
class FullTreeAdminUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
class AdminFullTreeListView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = FullTreeAdminUserSerializer
When i query users/all i have following error:
Cannot resolve keyword 'created' into field
The user model looks like
class User(AbstractBaseUser, PermissionsMixin):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
username = models.CharField(max_length=255, unique=True, db_index=True)
first_name = models.CharField(max_length=255, blank=True)
last_name = models.CharField(max_length=255, blank=True)
email = models.EmailField(max_length=255, unique=True, db_index=True)
is_verified = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
date_joined = models.DateTimeField(auto_now=True)
balance = models.FloatField(default=0.0)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
I cannot figure out where the problem is. I simply wanna get list of all user and i didn't expect such problems. I don't have created filed in my user model
Related
I get such an error while migrating to a database:
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: foreign key mismatch - "user_auth_customer"
referencing "user_auth_profile"
I have checked Foreign_Keys of my models and they look good.
I have no idea why I receive that error :(
Please, help me out here.
class Customer(AbstractUser):
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
profile = models.OneToOneField("Profile", related_name="user_profile",
on_delete=models.CASCADE, null=True)
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, null=True, blank=True)
username = models.CharField(max_length=30, null=True, blank=True)
phone = models.CharField(max_length=10, default='', null=True, blank=True)
email = models.EmailField(validators=[validators.EmailValidator()],
unique=True)
password = models.CharField(max_length=100, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
#staticmethod
def get_customer_by_email(email):
try:
return Customer.objects.get(email=email)
except:
return False
def isExists(self):
if Customer.objects.filter(email=self.email):
return True
return False
class Meta:
verbose_name = 'Customer'
verbose_name_plural = 'Customers'
class Profile(models.Model):
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=10, default='', null=True, blank=True)
email = models.EmailField(primary_key=True, unique=True, validators=[validators.EmailValidator()])
password = models.CharField(max_length=100, null=True, blank=True)
# Add a photo field
owner = models.OneToOneField(Customer, related_name='profile_owner',
on_delete=models.SET_NULL, null=True)
username = models.CharField(max_length=30, null=True, blank=True,
validators=[UnicodeUsernameValidator()])
date_created = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'
if you need any else details, I can provide you with those in the comments.
You can't have both ways OneToOneField. Choose one way.
If you delete Customer's profile field, then still you will have possibility to call relation with:
customer = Customer.objects.get(id=1)
customer.profile # that will call Customer's related Profile object
Assuming, that you will change related_name='profile_owner' to simpler related_name='profile'.
Read more about OneToOneRelationships.
I used the django debug toolbar to analyse why the calls to my usermodel were so painfully slow within the django admin. There I saw that I had hundreds of duplicate calls to the content_type model:
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id"
= 1 LIMIT 21
362 similar queries. Duplicated 4 times.
To be honest, I do not understand where these calls come from in the first place but I wanted to pre_fetch the model. However, this seems not to be possible in the normal way because there is actually no ForeignKey or any other kind of direct relationship between the models. How could I reduce those 362 content_type calls?
This is the usermodel in question:
class User(AbstractBaseUser, PermissionsMixin):
"""
Base model for the user application
"""
USERNAME_FIELD = "email"
objects = UserManager()
username_validator = None
username = None
email = models.EmailField(_("email address"), unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
first_name = models.CharField(max_length=150, blank=True)
last_name = models.CharField(max_length=150, blank=True)
title_of_person = models.ForeignKey(
TitleOfPerson, on_delete=models.CASCADE, blank=True, null=True
)
is_verified = models.BooleanField(default=False)
language = models.ForeignKey(
Language, blank=True, null=True, on_delete=models.SET_NULL
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("User")
verbose_name_plural = _("Users")
def __str__(self) -> str:
return self.email
Thanks
I want to assign Tasks to only the staffs. Therefore, I want my dorpdown list should only show the users that have a role of is_staff = True.
But my drop down list now shows all the users (Superuser, Authority, General_user) that are available in the database.
How to modify this to only show staffs in the drop down list which should only show two users since I've assigned two users with staff role...?
My Model Classes:
Custom-User Model:
class User(AbstractBaseUser, PermissionsMixin):
"""
Responsible for handleing App user's data
"""
email = models.EmailField(max_length=255, unique=True)
nid = models.CharField(max_length=30, unique=True)
username = models.CharField(max_length=20, blank=True, null=True)
date_of_birth = models.DateTimeField(blank=True, null=True)
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
image = models.FileField(
upload_to=FileManager.photo_path, null=True, blank=True)
is_active = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_authority = models.BooleanField(default=False)
is_specialist = models.BooleanField(default=False)
is_general_user = models.BooleanField(default=False)
timestamps = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
objects = user_manager.UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['nid']
Tasks Model
class Task(BaseAbstractModel):
'''
Responsible for Storing and Providing Tasks data
'''
assignment = models.ForeignKey(Assignment,
on_delete=models.DO_NOTHING,
related_name='+')
assigne_to = models.ForeignKey(User,
on_delete=models.DO_NOTHING,
related_name='+')
task_name = models.CharField(max_length=300)
is_done = models.BooleanField(default=False)
created_by = models.ForeignKey(User,
on_delete=models.DO_NOTHING,
related_name='created_by')
Serializer:
class TaskListSerializer(serializers.ModelSerializer):
'''
Will be serializing Task's data
'''
created_by = UserListSerializer(read_only=True)
class Meta:
model = Task
fields = ('assignment',
'assigne_to',
'task_name',
'is_done',
'created_by',)
Generic Create View
class CreateTaskView(generics.CreateAPIView):
queryset = Task.objects.all()
serializer_class = TaskListSerializer
Try to use PrimaryKeyRelatedField with queryset argument:
class TaskListSerializer(serializers.ModelSerializer):
'''
Will be serializing Task's data
'''
created_by = UserListSerializer(read_only=True)
assigne_to = serializers.PrimaryKeyRelatedField(queryset=User.objects.filter(is_staff=True))
class Meta:
model = Task
fields = ('assignment',
'assigne_to',
'task_name',
'is_done',
'created_by',)
I have two models named user, skill, and profile.
I am trying to implement a search filter on the user's skills. which means when someone searches for something that is contained in the skills of a user, that user would appear in the search result.
Note: when the user signs up, a signal is used to auto-create a profile for that user. The user simply updates their profile to add skills and other things.
user model
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
name = models.CharField(max_length=250)
picture = models.TextField(null=True, blank=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(max_length=255, unique=True, blank=True)
profile model
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profiles')
date_of_birth = models.DateField(blank=True, verbose_name="DOB", null=True)
bio = models.TextField(max_length=500, blank=True, null=True)
skills = models.ManyToManyField(Skill, related_name='skills')
sex = models.CharField(max_length=6, choices=SEX, blank=True, null=True)
type_of_body = models.CharField(max_length=8, choices=BODYTYPE, blank=True, null=True)
feet = models.PositiveIntegerField(blank=True, null=True)
inches = models.PositiveIntegerField(blank=True, null=True)
lives_in = models.CharField(max_length=50, blank=True, null=True)
updated_on = models.DateTimeField(auto_now=True)
skill model
class Skill(models.Model):
name = models.CharField(max_length=60)
subcategory = models.CharField(max_length=60, blank=True, null=True)
description = models.TextField(null=True, blank=True)
created_on = models.DateTimeField(auto_now=True)
updated_on = models.DateTimeField(auto_now_add=True)
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.DO_NOTHING)
the user view, where the search is done from
class ListUsersView(generics.ListAPIView):
'''
Gets all the users in the database
'''
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [AllowAny]
filter_backends = [filtr.SearchFilter]
search_fields = ['email', 'name']
currently, the solution above works, but when I add to the search_fields other fields like profiles__skills in order to include results where there is a skill like that created by ay user, the code doesn't work.
Please, how can I get the skills in the profile of a user to show in the search?
The SearchFilter class supports simple single query parameter based searching. The search_fields attribute should be a list of names of text type fields on the model.
profiles__skills is not a field. You should use a text field eg. profiles__skills__name
class ListUsersView(generics.ListAPIView):
'''
Gets all the users in the database
'''
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [AllowAny]
filter_backends = [filtr.SearchFilter]
search_fields = ['email', 'name', 'profiles__skills__name']
This is my User class:
class User(TimeStampedModel, AbstractBaseUser):
name = models.CharField(null=False, max_length=255)
username = models.CharField(null=False, unique=True, max_length=255)
email = models.EmailField(null=True)
mobile_number = models.CharField(null=True, max_length=255)
bio = models.CharField(null=True, max_length=255)
title = models.CharField(null=True, max_length=255)
posts = models.IntegerField(default=0)
views = models.IntegerField(default=0)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
last_active_on = models.DateTimeField(auto_now=True)
objects = CustomUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['name']
When I try to update the user from admin dashboard I get 'field cannot be empty error' for the following fields: mobile_number, email, bio, title
Any idea on how to resolve this?
Specify blank=True in your model for those fields.
class User(TimeStampedModel, AbstractBaseUser):
name = models.CharField(null=False, max_length=255)
username = models.CharField(null=False, unique=True, max_length=255)
email = models.EmailField(null=True, blank=True) # add 'blank' argument
mobile_number = models.CharField(null=True, max_length=255, blank=True) # add 'blank' argument
bio = models.CharField(null=True, max_length=255, blank=True) # add 'blank' argument
title = models.CharField(null=True, max_length=255, blank=True) # add 'blank' argument
posts = models.IntegerField(default=0)
views = models.IntegerField(default=0)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
last_active_on = models.DateTimeField(auto_now=True)
objects = CustomUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['name']
If a field has blank=True, form validation will allow entry of an empty value. Default value for blank argument is False.
Note: null is purely database-related, whereas blank is validation-related.
If a field has blank=True, form validation will allow entry of an empty value.
If a field has null=True, Django will store empty values as NULL in the database.