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
Related
I am using python 3.8 and django 4.0.6 + drf 3.13.1
There are models
class Profile(models.Model):
user='US'
manufacturer = 'MA'
admin='AD'
choice=[
(user, 'User'),
(manufacturer, 'Manufacturer'),
(admin, 'Admin')
]
user_company = models.CharField(max_length=2, choices=choice)
user = models.OneToOneField(User, on_delete=models.CASCADE)
last_request = models.JSONField(null=True)
class ProfileCompany(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
company = models.OneToOneField('Company', on_delete=models.CASCADE)
classCompany(models.Model):
id_company = models.IntegerField(null=True, unique=True)
Company = models.CharField(max_length=128)
Direction = models.CharField(max_length=512, blank=True)
Description = models.TextField(null=True, blank=True)
Categories = ArrayField(base_field=models.CharField(max_length=128), null=True, blank=True)
Products = ArrayField(base_field=models.CharField(max_length=128), null=True, blank=True)
Serializer
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model=Company
fields = '__all__'
The task is to make the pre-moderation of the creation and updating of companies by the admin.
Manufacturer creates a new company or updates data in it, this data is not visible to all users, but only to the admin. The admin accepts or rejects this data with a comment (in this case, the Manufacturer receives a message with this comment, corrects the data and sends the data again for moderation)
I could not connect django-moderation, because it is not suitable for REST.
Are there ready-made libraries or solutions?
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()
I have the following custom user model arrangement.
```
class User(AbstractUser):
is_student = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
class StudentProfile(models.Model):
student = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
location = models.CharField(max_length=8, blank=False, default='')
class TeacherProfile(models.Model):
teacher = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
location = models.CharField(max_length=8, blank=False, default='')
gender = models.CharField(max_length=8, choices=GENDER_CHOICES, default='')
```
I am able to a query the students based on the location of their teacher (current user).
Student.objects.filter(location=request.user.teacher.location)
I can also query the user model & find all teachers/students
User.objects.filter(is_teacher=True)
QUESTION:
Without relying on the profile models (Student & Teacher) How can I extend the query on abstractuser using profile attributes.
[X]-This is wrong but the idea is something like;
User.objects.filter(is_teacher=True).filter(is_teacher.location=newyork)
You can follow the OneToOneField in reverse:
User.objects.filter(teacherprofile__location='newyork')
You thus do not need to store is_teacher and is_student explicitly. You can simply filter Students with:
# Users with a related StudentProfile record
User.objects.filter(studentprofile__isnull=False)
I have created a app using the following Model
models.py
class Vendor(models.Model):
name = models.CharField(max_length=100, unique=True, blank=False)
def __str__(self):
return self.name
class Model(models.Model):
name = models.CharField(max_length=100, unique=True, blank=False)
def __str__(self):
return self.name
class Request(models.Model):
job_reference = models.CharField(max_length=100, unique=True, blank=False)
def __str__(self):
return self.job_reference
class Device(models.Model):
Vendor = models.ForeignKey('Vendor')
Model = models.ForeignKey('Model')
device_id = models.CharField(max_length=255, unique=True, blank=True)
is_encrypted = models.BooleanField()
is_medical = models.BooleanField()
request_job_reference = models.ForeignKey('Request')
submitted = models.DateTimeField(default=timezone.now)
When i go to the admin page I can add new devices which displayed each of the fields and the "Vendor" and "Model" allows me to either select an existing entry or has a plus icon to add a new entry (which is great)
Django_Admin_form
When i create a form for my app
forms.py
from django import forms
from . models import Device
class AddDevice(forms.ModelForm):
class Meta:
model = Device
fields = ('Vendor', 'Model', 'device_id', 'is_encrypted', 'is_medical', 'submitted')
The form on my webpage display ok however there is no option to insert a new entry to "Vendor" or "Model".
Webpage Form
I have looked on other posts on here as users have had the same issue and it's been suggested to use "ModelChoiceField" but unfortunately it still doesn't make any sense to me. Either i'm completely missing something or I have setup my models in a way which is making things harder for myself.
Can anyone explain how I can go about doing this?
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.