django user_groups table missing - python

I ahve a user model called TbUser and I have integrated a mysql legacy database with django. After doing migrations I have the follwing tables. django_seesion, django_migrations, django_content_type, django_admin_log, auth_permission, auth_group_permissions, auth_group
When I log in to django admin page, and click on the TbUser then select a random user I am getting the following error.
Exception Value:
(1146, "Table 'db.tb_user_groups' doesn't exist")
Should this table be created when migrations are run?
Could it be that this table is the auth_group, and django is looking for this one using the wrong table name?
users.models
class TbUser(AbstractBaseUser, PermissionsMixin):
id = models.CharField(primary_key=True, max_length=32, default=uuid.uuid4)
username = models.CharField(
max_length=40, blank=True, null=True, unique=True, db_column='usname')
password = models.CharField(
max_length=255, blank=True, null=True, db_column='psword')
email = models.CharField(max_length=255, blank=True, null=True)
role = models.ForeignKey(TbRole, on_delete=models.CASCADE)
department = models.ForeignKey(
'app.TbDepartment', on_delete=models.CASCADE, null=True, blank=True)
is_superuser = models.BooleanField(
default=False, blank=True, null=True, db_column='default_super')
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = TbUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
managed = False
db_table = 'tb_user'
admin.py
from app.models import TbDepartment
from django.contrib import admin
from .models import TbCustomer, TbRole, TbUser, TbUserRole
admin.site.register(TbUser)
admin.site.register(TbRole)
admin.site.register(TbUserRole)
admin.site.register(TbDepartment)
admin.site.register(TbCustomer)
UPDATE:
I have created in mysql a table called tb_user_groups and when doing the same action the next error appears
Exception Value:
(1146, "Table 'db.tb_user_user_permissions' doesn't exist")
How do I generate these tables?

Why don't you just use AbstractUser. It has everything configured, and you can customize it if you want. In this case you shouldn't get tb_user_groups doesn't exist error.
class TbUser(AbstractUser):
REQUIRED_FIELDS = []
objects = TbUserManager()

Related

Getting error when attempting to add items into the database

So, I am actively trying to create categories with subcategories. My current app is listings, and the idea is to create a ManyToManyField inside my Listing models. Here is my code inside models.py.
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
class Category(MPTTModel):
name = models.CharField(max_length=150, unique=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by = ['name']
class Blist(models.Model):
name = models.CharField('Business Name', max_length=250)
address = models.CharField('Address', max_length=300)
city = models.CharField('City', max_length=100)
zip_code = models.CharField('Zip Code', max_length=10)
phone_number = models.CharField('Phone Number', max_length=20)
web = models.URLField('Website')
def __str__(self):
return self.name
But when I go into the shell to add items into the category, I'm getting errors:
django.db.utils.ProgrammingError: column listings_category.name does not exist
LINE 1: SELECT "listings_category"."id", "listings_category"."name",...
Once finished, I ran makemigrations and migrate, but I realize it is not creating the tables in my database. I'm using Postgresql.
What am I doing wrong here?

Show all users related to tenant in one place

I'm working on an application in the saas model (django 2.1). I use the django tenants plugin (https://github.com/tomturner/django-tenants).
My problem is to display all tenants in the "public" schema. In such a way as to see how much each tenant has users, to be able to manage them, etc.
Is it a good architectural solution to put a foreign key into Tenant in the User model and save this column during the registration process?
Is there another way to do it?
Below is example, pseudo code:
class Tenant(TenantMixin):
name = models.CharField(_('Name of company'), max_length=50, unique=True)
on_trial = models.BooleanField(default=True)
paid_until = models.DateTimeField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
auto_create_schema = True
def __str__(self):
return self.name
def get_name(self):
return self.name
class Domain(DomainMixin):
pass
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('Email address'), unique=True)
first_name = models.CharField(_('First name'), max_length=60, blank=True)
last_name = models.CharField(_('Last name'), max_length=60, blank=True)
member_of_company = models.ForeignKey(Tenant, on_delete=models.CASCADE, related_name='users', null=True, blank=True)
You can iterate over your tenants and get the Users for each tenant with the following code:
from django.db import connection
from django.contrib.auth import get_user_model
from tenant_schemas.utils import get_tenant_model
UserModel = get_user_model()
TenantModel = get_tenant_model()
for tenant in TenantModel.objects.all():
connection.set_tenant(tenant)
tenant_users = UserModel.objects.all()
# Do whatever you want with your users

'NoneType' object has no attribute 'add'

I have the following User object,
class User(AbstractBaseUser, PermissionsMixin, Base):
username = models.CharField(
db_index=True,
null=False,
unique=True,
max_length=255,
)
mobile = PhoneNumberField(
db_index=True,
null=False,
unique=True,
)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
And I've the following class to manage connections,
class Connections(Base):
owner = models.OneToOneField(
User,
on_delete=models.CASCADE,
null=True,
)
friends = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='friend_set',
null=True,
blank=True,
)
followers = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='follower_set',
null=True,
blank=True,
)
followings = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='following_set',
null=True,
blank=True,
)
When I try to add a friend,
sender = User.objects.get(
id=kwargs.get('sender_id')
)
receiver = User.objects.get(
id=kwargs.get('receiver_id')
)
sender_connections, created =(
Connections.objects.get_or_create(owner=sender)
)
sender_connections.friends.add(receiver)
I get the following error,
'NoneType' object has no attribute 'add'
Can someone help me with this?
It looks like you are trying to user the django related manager add function
sender_connections.friends.add(receiver)
However the friends attribute on connections is a ForeignKey relation instead of a ManyToManyField. This means that when you call sender_connections.friends and the connection does not exist, you will get None.
If you change the attribute to a ManyToManyField, then sender_connections.friends will return a ManyRelatedManager and the add should work as expected.
Complementing the wingardtw answer, with Django 3.0 you can use PrimaryKeyRelatedField, and instead of using "add" you will perform an update on the queryset, like under:
Connections.objects.filter(owner=sender).update(friends=receiver)
Important: This requires the objects to already be saved.
See those link for more information:
https://docs.djangoproject.com/en/3.0/ref/models/relations/#django.db.models.fields.related.RelatedManager.add
https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.update

Migrations being applied according to User in models.py instead of being applied according to migrations in the database

I have written a custom django migrations command as shown below
User = get_user_model()
def populate_asset_assignee(apps, schema_editor):
for user in User.objects.all():
user.save()
# Some more code
The user model looks as follows
class User(AbstractUser):
username = None
email = models.EmailField(max_length=50, unique=True)
cohort = models.IntegerField(blank=True, null=True)
slack_handle = models.CharField(max_length=50,
blank=True, null=True)
picture = models.CharField(max_length=255, blank=True, null=True)
phone_number = models.CharField(max_length=50, blank=True, null=True)
last_modified = models.DateTimeField(auto_now=True, editable=False)
password = models.CharField(max_length=128, blank=True, null=True)
location = models.ForeignKey('SomeCentre',
blank=False,
null=True,
on_delete=models.PROTECT)
# Some more fields
I added the location field recently and have the migrations for it which is applied after this custom migration has been applied. The problem I am having is that whenever I try to make the migrations on the test db or a new database, I get the error django.db.utils.ProgrammingError: column core_user.location_id does not exist which is being raised inside the populate_asset_assignee method when I try to do the user in User.objects.all()
Any ideas why location_id is beeing checked yet I haven't applied the migrations for the location field yet.

how to make USERNAME field unique for multiple type of users in User Model

I have followed these [1,2,3] links to create a custom user model by extending AbstractBaseUser class. I am storing login information of three type of users lets say teacher, Admin and students in this table. USERNAME field is emailId.
I want to make emailId unique among one type of users. In other words, in my system student can register as teacher as well with same emailId. But since emailId is USERNAME field and hence unique, I am unable to achieve this.
Please suggest how can I do this in Django application.
UserModel :
class UserModel(AbstractBaseUser):
user_type_choices = (
(constants.USER_TYPE_ADMIN, 'Admin'),
(constants.USER_TYPE_INSTITUTE, 'Institute'),
(constants.USER_TYPE_STUDENT, 'Student')
)
sys_id = models.AutoField(primary_key=True, blank=True)
name = models.CharField(max_length=127, null=False, blank=False)
email = models.EmailField(max_length=127, unique=True, null=False, blank=False)
mobile = models.CharField(max_length=10, unique=True, null=False, blank=False)
user_type = models.PositiveSmallIntegerField(choices=user_type_choices, null=False, blank=True)
is_staff = models.BooleanField()
is_active = models.BooleanField(default=True)
objects = MyUserManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ['name', 'mobile', 'user_type','is_staff']
I am using other models like StudentsDetails, TeacherDetails with foreign key to UserModel to store extra information.

Categories

Resources