예제 #1
0
    def __init__(self, *args, **kwargs):
        super(TenantModelForm, self).__init__(*args, **kwargs)

        tenant = get_current_tenant()
        if tenant:
            for field in self.fields.values():
                if isinstance(field, (forms.ModelChoiceField, forms.ModelMultipleChoiceField)):
                    # Check if the model being used for the ModelChoiceField has a tenant model field
                    if hasattr(field.queryset.model, "tenant"):
                        # Add filter restricting queryset to values to this tenant only.
                        field.queryset = field.queryset.filter(tenant=tenant)
def tenant_filter(queryset):
    """
    To filter a queryset so that all instances belong to the currently logged in tenant.
    example:
        bugs = BugReport.objects.all()
        bugs = tenant_filter(bugs)
    """
    if hasattr(queryset.model, 'tenant'):
        t = get_current_tenant()
        return queryset.filter(tenant=t)   
    return queryset 
def current_tenant_owns_object(obj):
    """
    To verify that the current logged in tenant owns a particular instance.
    example:
        if current_tenant_owns_object(obj):
            do_something()
    """
    if hasattr(obj, 'tenant'):
        t = get_current_tenant()
        if t != obj.tenant:
            return False
    return True
예제 #4
0
def clone_model(model_class, source_tenant=BASE_TENANT_ID, dest_tenant='current_tenant'):
    """
    This is a general-purpose tool to clone (copy) all instances of a model from one tenant to another.
    By default, it clones from the base tenant to the current tenant (logged in user).
    Warning: it will NOT work with m2m fields.
    """
    if dest_tenant == 'current_tenant':
        dest_tenant = get_current_tenant()

    if issubclass(model_class, TenantModel):
        qs = model_class.objects.filter(tenant=source_tenant).order_by('id')
        for i in qs:
            clone_model_instance(i, { 'tenant': dest_tenant })
def tenant_get_object_or_404(klass, *args, **kwargs):
    """
    A tenant-aware version of django's get_object_or_404 shortcut.
    example:
        tenant_get_object_or_404(BugReport, id=1)
    """
    obj = get_object_or_404(klass, *args, **kwargs)
    
    if obj and hasattr(obj, 'tenant'):
        t = get_current_tenant()
        if t != obj.tenant:
            raise Http404
    
    return obj
예제 #6
0
    def __init__(self, *args, **kwargs):
        super(TenantModelForm, self).__init__(*args, **kwargs)

        tenant = get_current_tenant()
        if tenant:
            for field in self.fields.values():
                if isinstance(field, (
                        forms.ModelChoiceField,
                        forms.ModelMultipleChoiceField,
                )):
                    # Check if the model being used for the ModelChoiceField has a tenant model field
                    if hasattr(field.queryset.model, 'tenant'):
                        # Add filter restricting queryset to values to this tenant only.
                        field.queryset = field.queryset.filter(tenant=tenant)
예제 #7
0
def clone_model(model_class,
                source_tenant=BASE_TENANT_ID,
                dest_tenant='current_tenant'):
    """
    This is a general-purpose tool to clone (copy) all instances of a model from one tenant to another.
    By default, it clones from the base tenant to the current tenant (logged in user).
    Warning: it will NOT work with m2m fields.
    """
    if dest_tenant == 'current_tenant':
        dest_tenant = get_current_tenant()

    if issubclass(model_class, TenantModel):
        qs = model_class.objects.filter(tenant=source_tenant).order_by('id')
        for i in qs:
            clone_model_instance(i, {'tenant': dest_tenant})
예제 #8
0
    def clean(self):
        """
        Here we take care of setting the tenant for any model instance that has a foreign key to the Tenant model.

        The exception is UserProfile - the UserProfile's tenant gets set when first saved, and from then on
        it can be changed by the current user to something else than the current user's tenant.
        This is useful for the Superuser, who can change his own UserProfile tenant.  That lets him slip into any
        tenant's account.

        It's better to set the tenant here in clean() instead of save().  clean() gets called automatically when you
        save a form, but not when you create instances programatically - in that case you must call clean() yourself.
        That gives a lot of flexibility: in some cases, you might want to set or change the tenant from the code; all
        you need to do is avoid calling clean() after setting the value and it won't be overwritten.
        """

        user_profile_class = get_profile_class()
        if hasattr(self, 'tenant_id') and not ( isinstance(self, user_profile_class) and self.id ):
            self.tenant = get_current_tenant()

        super(TenantModel, self).clean()
예제 #9
0
    def clean(self):
        """
        Here we take care of setting the tenant for any model instance that has a foreign key to the Tenant model.
        
        The exception is UserProfile - the UserProfile's tenant gets set when first saved, and from then on
        it can be changed by the current user to something else than the current user's tenant.        
        This is useful for the Superuser, who can change his own UserProfile tenant.  That lets him slip into any 
        tenant's account.
        
        It's better to set the tenant here in clean() instead of save().  clean() gets called automatically when you
        save a form, but not when you create instances programatically - in that case you must call clean() yourself.
        That gives a lot of flexibility: in some cases, you might want to set or change the tenant from the code; all 
        you need to do is avoid calling clean() after setting the value and it won't be overwritten.
        """

        user_profile_class = get_profile_class()
        if hasattr(self, 'tenant_id') and not (isinstance(
                self, user_profile_class) and self.id):
            self.tenant = get_current_tenant()

        super(TenantModel, self).clean()
예제 #10
0
    def clean(self):
        cleaned_data = super(TenantModelForm, self).clean()

        if hasattr(self.instance, "tenant_id"):
            self.instance.tenant = get_current_tenant()
        return cleaned_data
예제 #11
0
 def queryset(self, request):
     qs = super(TenantAdmin, self).queryset(request)
     return qs.filter(tenant = get_current_tenant() )
예제 #12
0
 def queryset(self, request):
     qs = super(TenantAdmin, self).queryset(request)
     return qs.filter(tenant=get_current_tenant())
예제 #13
0
 def get_query_set(self):
     tenant = get_current_tenant()
     if tenant:
         return super(TenantMgr, self).get_query_set().filter(tenant=tenant)
     else:
         return super(TenantMgr, self).get_query_set()
예제 #14
0
 def get_query_set(self):
     tenant = get_current_tenant()
     if tenant:
         return super(TenantMgr, self).get_query_set().filter(tenant=tenant)
     else:
         return super(TenantMgr, self).get_query_set()
예제 #15
0
    def clean(self):
        cleaned_data = super(TenantModelForm, self).clean()

        if hasattr(self.instance, 'tenant_id'):
            self.instance.tenant = get_current_tenant()
        return cleaned_data