Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to test a view with login_required?
I have a view on my Django app with the tag @login_required: @login_required @require_http_methods(['GET', 'POST']) def edit_result(request: WSGIRequest, result_id: str): try: result_type, result_number = EditResultService.split_result_id(result_id.lower()) except Error as e: messages.error(request, str(e)) return render(request, PAGE404_TEMPLATE) if request.POST: EditResultService.post_request(request, result_type, result_number) context = EditResultService.get_request(result_type, result_number) if context: return render(request, 'edit_result.html', context) else: return render(request, PAGE404_TEMPLATE) I am trying to write some tests to cover 100% of this view, but no matter what I do, there is no way to obtain the actual response (not the redirection). Here is the code of my test: class TestViews(TestCase): def set_up(self): self.client = Client() self.user = User.objects.create_user('aaa', 'aaa@aaa.com', 'aaa') ..... def test_edit_result_get_ok(self): self.client.login(username='aaa', password='aaa') response = self.client.get(reverse('edit_result', kwargs={'result_id': 'i1'})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, EDIT_RESULT_TEMPLATE) self.assertTrue('form' in response.context) messages = list(get_messages(response.wsgi_request)) self.assertTrue(len(messages) == 0) Is there a way to get my view covered and check the template used, messages...? -
select filter every time I add in the db it removes it from the select
Hi I would like to know how I can make a dynamic select. Let me explain, I have a select with option fields taken from the db (for example groups). I have a function that makes me choose one of these fields and adds it to me in the db (tab table containing several groups). how can I cycle the select so that when a data from the groups table is inserted in the exercises table he no longer shows it to me in the select so in a nutshell I can't have two groups in the same tab. can someone help me? -
How to pass table value into another model instances in django?
I want pass database value into another model using instance method. and then save it into db. But when i clicked submit the value doesn't save into db. this is my model.py code import datetime from django.db import models from django.contrib.auth.models import User class Customer(models.Model): id_number = models.CharField(max_length=15, null=False) name = models.CharField(max_length=100, null=False) customer_order = models.CharField(max_length=100, null=False) order_date = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True, auto_created=False) phone_number = models.CharField(max_length=20, null=True) def __str__(self): return self.name class SpecialOffer(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) order_date = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True, auto_created=False) phone_number = models.CharField(max_length=20, null=True) customer_prizes = models.CharField(max_length=100, null=True) def __str__(self): return self.customer there are two models here, for form.py here the codes : from django import forms from .models import * class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ['id_number', 'name', 'customer_order', 'order_date', 'phone_number'] widgets = { 'id_number':forms.TextInput(attrs={'class':'form-control', 'type':'text'}), 'name': forms.TextInput(attrs={'class': 'form-control', 'type': 'text'}), 'customer_order': forms.TextInput(attrs={'class':'form-control', 'type':'text'}), 'order_date': forms.DateTimeInput(attrs={'class': 'form-control datetime-local', 'type': 'text', 'data-target': '#datetimepicker', 'id':'datetimepicker'}), 'phone_number' : forms.TextInput(attrs={'class':'form-control', 'type':'text'}), } class SpecialOfferForm(forms.ModelForm): class Meta: model = SpecialOffer fields = ['order_date', 'phone_number', 'customer_prizes'] widgets = { 'order_date':forms.DateTimeInput(attrs={'class':'form-control', 'type':'text'}), 'phone_number': forms.TextInput(attrs={'class': 'form-control', 'type': 'text'}, 'customer_prizes': forms.TextInput(attrs={'class':'form-control', 'type':'text'}), } ok after get the form and model, i create input form for Customer in my views.py … -
How to Make Upload filed in Django
I am making a social media website using django I but I am not able to create a profile picture section. I want to ask that how I will Able to Make a filed Where a User can Select And upload their own profile picture. Please Help me -
How to run prometheus on docker-compose and scrape django server running locally?
I am trying to setup prometheus to monitor my Django application using django-prometheus and Docker compose. I've been following some guides online but different from all the guides I've seen, I want to run Django locally for now so simply python manage.py runserver and run prometheus with docker-compose (and later add grafana). I want to do this to test it locally and later I will deploy it to Kubernetes but this is for another episode. My issue is to make the local running django server communicate in the same network as the prometheus running container because I get this error in the /targets on prometheus dashboard: Get "http://127.0.0.1:5000/metrics": dial tcp 127.0.0.1:5000: connect: connection refused These are my docker-compose file and prometheus configuration: docker-compose.yml version: '3.6' services: prometheus: image: prom/prometheus volumes: - ./prometheus/:/etc/prometheus/ command: - '--config.file=/etc/prometheus/prometheus.yml' ports: - 9090:9090 prometheus.yaml global: scrape_interval: 15s evaluation_interval: 15s scrape_configs: - job_name: prometheus static_configs: - targets: - localhost:9090 - job_name: django-app static_configs: - targets: - localhost:8000 - 127.0.0.1:8000 -
django.db.utils.DataError: length for type varchar cannot exceed 10485760
I was trying to push my code to the heroku and when I migrate my manage.py, it causes this error: django.db.utils.DataError: length for type varchar cannot exceed 10485760 . First, my length has been set to 100000000 and I change it back to 1000 and make migrations. But even after that I still got this Error. I try to search my whole files and everything is set to 1000. Help me to solve the problem! -
Create django query satisfying two conditions involving related models
I have two models, let's say: class Order(models.Model): # ... fields class Product(models.Model): quantity = models.PositiveIntegerField(null=False, blank=False, default=1) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='products') I want to make a query that includes all the Orders which have more than one Product related to it, or if at least one Product has a quantity greater than 1. For the first part I have this: queryset = Order.objects.annotate(products_count=Count('products')).filter(products_count__gt=1) I am stuck on adding the OR condition to also include the other condition. Thank you so much in advance. -
Dockerize a React-Django project where the frontend is served from Django
I am serving a react app from within Django, and I trying to deploy it using docker-compose up -d --build. My project directory is as follows: root ├──project (django) | ├──frontend/ # react project is here | ├──project/ | ├──static/ | ├──Dockerfile //Dockerfile for backend image | ├──entrypoint.sh | ├──manage.py | ├──requirements.txt └──docker-compose.yaml Here is my current deploy script: # pull the official base image FROM python:3.8.12-bullseye # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN apt-get update COPY /requirements.txt /usr/src/app RUN pip install -r requirements.txt # set work directory WORKDIR ~/usr/src/app COPY package.json ./ COPY package-lock.json ./ RUN npm install --silent RUN npm install react-scripts@3.4.1 -g --silent RUN npm run dev # set work directory WORKDIR /usr/src/app # copy project COPY . /usr/src/app/ # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] The error I get > => ERROR [12/18] COPY package.json ./ > 0.0s => ERROR [13/18] COPY package-lock.json ./ 0.0s ------ > > [12/18] COPY package.json ./: > ------ > ------ > > [13/18] COPY package-lock.json ./: > ------ failed to compute cache key: "/package-lock.json" not found: not found lipsumlipsumlipsumlipsumlipsumlipsumlipsumlipsum -
How to edit django default headers
I have the endpoint that return string as response within Response object from rest_framework. Response(response, status=200, headers={'age': 20}, content_type="text/plain; version=0.0.4") Above you can see my response object, as you can see only header I set up is 'age'. However when I check response.items() I can see that more headers are being added: dict_values([('Content-Type', 'text/plain; version=0.0.4'), ('age', '20'), ('Vary', 'Accept, Cookie'), ('Allow', 'GET, OPTIONS'), ('X-Frame-Options', 'DENY'), ('Content-Length', '213'), ('X-Content-Type-Options', 'nosniff')]) Is it possible to somehow delete/edit some of those headers that are being added automatically by django/rest_framework? Thanks! -
Why 404 error occurs even though I have set STATIC_ROOT and urls.py
I don't know why, but I get 404 errors when trying to use static file like this: {% static 'js/some.js' %}. Here's my urls.py urlpatterns = [ path('admin/', admin.site.urls), path("account/", include("account.urls")), path("", include("post.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And this is my settings.py STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static/' # media config MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / 'media/' Thanks!! -
How To Show Foreign Key Field Name instead of ID when UPDATING records in a modal Form using AJAX, Django REST API & jQuery
I have two models class Properties(models.Model): property_name = models.CharField(max_length=100) property_type = models.CharField(choices=TYPE, max_length=50) property_location = models.CharField(max_length=100) county = models.CharField(choices=COUNTY, max_length=50) number_of_units = models.IntegerField() date_created = models.DateField(auto_now_add=True) last_modified = models.DateField(auto_now=True) def __str__(self): return self.property_name class Meta: verbose_name_plural = "Properties" class RentalUnits(models.Model): unit_number = models.CharField(max_length=10) property = models.ForeignKey(Properties, on_delete=models.CASCADE) no_of_bedrooms = models.IntegerField(default=0) no_of_bathrooms = models.IntegerField(default=0) rent_per_month = models.IntegerField(default=0) status = models.CharField(max_length=20, choices=STATUS) date_created = models.DateField(auto_now_add=True) last_modified = models.DateField(auto_now=True) def __str__(self): return self.unit_number class Meta: verbose_name_plural = 'Units' And their corresponding serializers class PropertiesSerializers(serializers.ModelSerializer): class Meta: model = Properties fields = '__all__' class RentalUnitsSerializers(serializers.ModelSerializer): property = serializers.SerializerMethodField() class Meta: model = RentalUnits fields = ('id', 'unit_number', 'property', 'no_of_bedrooms', 'no_of_bathrooms', 'rent_per_month', 'status',) I wanted to show their foreign key names instead of IDs in a datatable and I found a good solution here so i ended up using def to_representation(self, instance): rep = super(RentalUnitsSerializers, self).to_representation(instance) rep['property'] = instance.property.property_name return rep and it gave me this { "id": 12, "unit_number": "1A", "property": 1, "no_of_bedrooms": 3, "no_of_bathrooms": 2, "rent_per_month": 60000, "status": "Occupied" }, { "id": 12, "unit_number": "1A", "property": "New Apartments", "no_of_bedrooms": 3, "no_of_bathrooms": 2, "rent_per_month": 60000, "status": "Occupied" }, Adding units & deleting units still works fine. My problem now comes up when I want … -
How to handle race conditions in ModelForms
I have a ModelForm that uses the model instance to perform a clean validation: class MyForm(forms.ModelForm): text_field = forms.CharField() def clean_text_field(self): print(self.instance.text_field) This works fine with the expected output when one user is using the form. However, if I open the form in 2 browser tabs, complete the form on the second tab and then try to complete the form on the first, self.instance.text_field returns None. What could be causing this? -
How to display the name of the wilaya and the name of the municipality on the map instead of displaying their id?
How to display the name of the wilaya and the name of the municipality on the map instead of displaying their id? The code below displays the wilaya id and the commune id instead of displaying the wilaya name and the commune name. How to solve this problem #models.py wilaya class Wilaya(models.Model): id = models.BigIntegerField() name = models.CharField(max_length=75)`` geom = models.MultiPolygonField(srid=4326) matricule=models.BigIntegerField(primary_key=True,null=False) def __str__(self): return self.name #models.py commune class Commune(models.Model): id = models.BigIntegerField() name = models.CharField(max_length=75) geom = models.MultiPolygonField(srid=4326) wilaya=models.ForeignKey(Wilaya,on_delete=models.DO_NOTHING,null=True) def __str__(self): return self.name #models.py even class Even(models.Model): name = models.CharField(max_length=20, default='Even') date = models.DateField(null=True, blank=True) wilaya=models.ForeignKey(Wilaya,on_delete=models.DO_NOTHING,null=True,blank=True commune=models.ForeignKey(Wilaya,on_delete=models.DO_NOTHING,null=True,blank=True geom = models.PointField(srid=4326, null=True, blank=True,) def __str__(self): return self.name #map.html var even = new L.GeoJSON.AJAX("{% url 'even' %}", { pointToLayer: function (feature, latlng) { return L.marker(latlng, { icon: L.icon({ iconUrl: "/static/img/icons/red.png", iconSize: [28, 32], iconAnchor: [12, 28], popupAnchor: [0, -25] }), title: feature.properties.name, riseOnHover: true }); }, onEachFeature: function (feature, layer) { var content = "<table class='table table-striped table-bordered table- condensed'>" + "<tr><th>Name</th><td>" + feature.properties.name + "</td> </tr>" + "<tr><th>Date</th><td>" + feature.properties.date + "</td></tr> </th></table>" + "<details><summary>" + "See more details"+"</summary> <table class='table table-striped table-bordered table-condensed'>" + " </td></tr>" + "<tr><th>Commune</th><td>" + feature.properties.commune + " </td></tr>" + "<tr><th>Wilaya</th><td>" + feature.properties.wilaya + " … -
Saving current user as assigned agent to model when updating model
I have a list of jobs that are created by the admin. When one of the agents starts the job by updating the notes. I would like to save that agent to the job model. Models.py class Job(models.Model): name = models.CharField(max_length=20, blank=True, null=True) agent = models.ForeignKey("Agent", on_delete=models.SET_NULL, null=True) start_date = models.DateField(null=True, blank=True) notes = models.TextField(default=0, null=True, blank=True) Views.py class JobUpdateView(LoginRequiredMixin, generic.UpdateView): template_name = "jobs/job_update.html" queryset = Job.objects.all() form_class = JobModelForm def get_success_url(self): return reverse("leads:lead-list") def job_update(request, pk): job = Job.objects.get(id=pk) form = JobModelForm(instance=job) if request.method == "POST": form = JobModelForm(request.POST, instance=job) if form.is_valid(): form.save() return redirect("/jobs) context = { "form": form, "job': job } return render(request, "jobs/job_update.html", context) -
Django REST Framework: I want to resolve n+1 in SerializerMethodField
I am trying to create a queryset that returns Boolean from a queryset prefetched with a reverse reference by SerializerMethodField, as shown in the code below. I'm creating one that determines if there is an object for the current user and returns Boolean. However, when I use the prefetched queryset to filter by the current user as shown below, a new queryset is issued instead of the prefetched queryset, and the n+1 problem occurs. In the following code, how can we save the queryset and return Booelan? class VideoSerializer(serializers.ModelSerializer): is_viewed = serializers.SerializerMethodField() is_favorited = serializers.SerializerMethodField() is_wl = serializers.SerializerMethodField() class Meta: model = Video fields = ( "pk", "is_viewed", "is_favorited", "is_wl", ) @staticmethod def setup_eager_loading(queryset): queryset.prefetch_related('history_set', 'favorite_set') def get_is_viewed(self, obj): user = self.context["request"].user if user.is_authenticated: try: obj.history_set.get(user=user) # <- here return True except History.DoesNotExist: pass return False def get_is_favorited(self, obj): user = self.context["request"].user if user.is_authenticated: try: obj.favorite_set.get(user=user) # <- here return True except Favorite.DoesNotExist: pass return False def get_is_wl(self, obj): user = self.context["request"].user if user.is_authenticated: try: Track.objects.get(playlist__user=user, playlist__is_wl=True, video=obj) return True except Track.DoesNotExist: pass return False A large number of query sets were issued. -
User group and permission based on tenants
This is a broad question and I'm here only to get my logic correct. I have an application where different companies registers. Now each company will have its own users. So I have extended the user model and made the user available only to their specific companies. The problem to me is with the user group and permission. Now each company will have its own group and permission (how to manage this?) also when a new company registers I create the user from the data available, now how to create the new group belonging to this new company and add roles and permission to this particular group or even give permission to this user at the time of registration. The permission is required because this will be the first user and based on permission it can do other things. Till now I created a superuser at the time of company registration but that's not right? (the dev work is still on that's why.) I have also extended the user registration model so for eg., if 2nd user is created for this company I am able to add it to a particular group. 2nd user is created at /api/registeruser/ and the … -
How to keep dropdown value in form after submit with Bootstrap and Django?
I've got a Bootstrap search form and I want to keep the values populated after submitting the form. Using Django and Jinja2 I can accomplish this using the value attribute for a regular input: <div class="form-group required"> <label class="control-label" for="carrier">Carrier</label> <input type="text" class="form-control form-control-sm" id="carrier" name="carrier" placeholder="Enter carrier" maxlength="25" value="{{request_data.carrier}}" required> </div> I'm trying to do the same thing with a Bootstrap dropdown/select field but after submitting the form the value resets back to the default value: <label for="environment">Select Environment for Data Search</label> <select class="form-control form-control-sm" name="environment" id="environment"> {% for env in environments %} <option>{{env.name}}</option> {% endfor %} </select> I tried adding the value attribute to the select tag but it didn't work and also messed up some formatting. Also, I don't have experience with PHP so ideally the solution wouldn't use PHP. Thanks -
django button with link to prefiltered data
Hej! I have multiple views, some with result tables and some detail views. From the detail views there should be links to other detail views (which works) and to some of the result tables with prefilled forms/prefiltered results. For example after the name given in the detail view. If clicked on the button I want to get redirected to the result table already filtered for the name of (e.g.) the parent institution given in the detail view. But I want to use the same template for all detail views (every institution gets a detail view) so it should be universal and not hard coded. Does anyone knows I could achieve that? I'm totally blank and can't find a good solution. # forms.py class SearchInstitutionsForm(forms.Form): name = forms.CharField( label="Name", required=False, ) # views.py def search_institution(request): if request.method == "POST": # create a form instance and populate it with data from the request: form = SearchInstitutionsForm(request.POST) if form.is_valid(): query = institution_filter_query(form) context = { "result_data": serialize(query), "form": form, "show_form": False, } return render(request, "stakeholders/search_form.html", context) else: form = SearchInstitutionsForm() class InstitutionDetail(DetailView): model = Institution def get(self, request, *args, **kwargs): institution = get_object_or_404(Institution, pk=kwargs['pk']) context = {'institution': institution} return render(request, 'stakeholders/institution_detail.html', context) # … -
Customize a response from a mutation using django-graphql-auth with graphene
I'm using django-graphql-auth and graphene on my django project. The django-graphql-auth library is nice but it lacks a bit on documentation and examples of customization. I already sent this question there but repo does not seem to get much activity lately (time to replace and use another package in the project perhaps), so I'll try my luck here: most of the questions related to customization are regarding inputs. In my case I'd like to change the output of the Register mutation, as I need the id of the user created on the response. So far what I manage to accomplish was to create a new custom mutation that inherits register, so I can add the logic to grab the created user: class RegisterCustom(mutations.Register): response = graphene.Field(RegisterResponseType) @classmethod def mutate(cls, *args, **kwargs): try: res = super().mutate(*args, **kwargs) if res.success: user = get_user_model().objects.order_by('-date_joined')[:1] return RegisterCustom(success=True, error="", user_id=user[0]['id']) except Exception: raise Exception(res.errors) However the return is not what I expect { "errors": [ { "message": "None", "locations": [ { "line": 472, "column": 5 } ], "path": [ "registerCustom" ] } ], "data": { "registerCustom": null } } if I add a print right before return let's say print(user[0]['id']) I can see the user … -
Preventing/Reducing deadlocks within a django application
I've been having a few issues recently working with a large MySQL database within django, MySQL seems to be having issues with deadlocks. I keep getting the error: (1213, 'Deadlock found when trying to get lock; try restarting transaction') Usually this seems to happen when calling the save or create functions for a new model instance (e.g). payment = Payment.objects.create( to_member=to_member, to_name="%s" % to_member.username, from_member=from_member, from_name="%s" % from_member.username, description="Resubscription", type='resubscription', amount=5.00, currency=from_member, processor='e-wallet' ) The particular table I'm trying to insert into has about 3.1 million rows and a size of 2.2 GB. In production the application has quite a number of active users (Member). The Payment model has two particular foreign keys (to_creator and from_member). So I wondered if that might be the cause of the be the cause of the issue rather than just on the Payment model? I've tried tweaking various aspect of the mysql configuration to manage this, but I seem to either get more deadlocks or the whole system locks up! Below are my current settings for the locks: Database locks Any help would be greatly appreciated. I've been pulling my hair out over the last few days about this. Dan -
Remove Decimal like " [Decimal('1220'), Decimal('160')] "from Django Queryset results
I have a queryset result which I would like to put into a list of Data and a list of Labels for Chart.js without showing Decimal. In my view.py the following funtion based view is written: labels = [] data = [] total_transactions_by_user = filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum('trade_price' ) * Sum('number_of_coins') ) ).order_by('-total') for each in total_transactions_by_user: labels.append(each["coin__name"]) data.append(each["total"]) The results of the lists are: ['Bitcoin', 'Dogecoin'] [Decimal('1220'), Decimal('160')] How do I remove Decimal() ,so I have 1220, and 160 in my List[] Thank you in advance. -
how can i create mini photo while creating photo?
i have a photo upload service on django. when i add a photo I want it to add one more photo with 50% split. If I put it in the pre_save on my photo save service, it can't find the photo (because it's not actually on the server) If I add it to the post_save, it goes into loop and adds unlimited when I add a photo (postman or etc.) How can get to save a small photo at a time?. here is my model class UserPhoto(General, Status): user = models.ForeignKey(UserBase, on_delete=models.CASCADE, verbose_name="User Id", related_name='UserPhoto_user', null=True, blank=True) link = models.ImageField(blank=True, null=True) order = models.IntegerField(null=True, blank=True) mini_link = models.ImageField(upload_to='mini_photos', blank=True, null=True) class Meta: db_table = 'user_photos' my view class UserPhoto(APIView): def get_object(self, pk): try: return Photo.objects.get(user__user__pk=pk) except Exception as e: return e def get(self, request): try: photo = self.get_object(request.user.pk) serializer = UserPhotoSerializer(photo) return Response(serializer.data) except Exception as e: print(e) def post(self, request): serializer = UserPhotoSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request): photo = self.get_object(request.user.pk) serializer = UserPhotoSerializer(photo, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my serializer class UserPhotoSerializer(serializers.ModelSerializer): class Meta: model = UserPhoto fields = '__all__' def create(self, validated_data): validated_data["user"] = … -
Can I just only use MySQL command instead of pure Model in Django? [closed]
I'm newbie in Django and in my first project, I realise that it isn't neccessary to use the pure module Model of Django, and I prefer to use MySQL command to handle data. So when should I use the pure Model instead of MySQL to handle data? Are there any advantages of the Model over MySQL? -
individual Response message on perform_destroy()
I've written a custom perform_destroy()-method to do some additional checks. def perform_destroy(self,instance): force = self.request.data.get('force',None) resp = {} if Processingstepstatus.objects.filter(orderfile__order=instance).exists() and not force: raise serializers.ValidationError({"message": "Order already in production and can't be canceled cost-free. Perform Delete Request with parameter \"force:True\" to cancel and assume the costs of "+ str(instance.currentcosts)+"€" }) else: if Processingstepstatus.objects.filter(orderfile__order=instance).exists() and force: resp['invoice'] = "Placeholdervalue" instance.canceled = True instance.save() resp['message'] = "Successfully canceled your order." return Response(resp,status=status.HTTP_200_OK) This should give back a json-response with the message and the invoice information but it doesn't give any response except 204 - no content. I think it is being overwritten by the higher-level method destroy() here, right? How to handle that? best regards -
What is the recommended Django project strcuture for a SaaS product?
I would try to explain our desired product idea as clear as possible but feel free to ask further questions. So, basically what we want to build is a SaaS product that will be used by multiple clients. For now, we're not interested in custom domains like (cust1.myproduct.com, cust2.myproduct.com) and we will simply be using one database to manage all customers' data. So far so good. Our SaaS product will be sold to enterprise organizations which will then be used by their employees. So for any one customer organization, there are three types of roles that we would like to provide their users, as follows: Admin: An organization's admin that should be able to do all the settings for that particular organization Manager: An organization's manager that can manage the users that are under his/her team Employee: A normal user with bare minimal permissions that can only manage his own data Now, to provision customers for this SaaS product and to set their global settings (e.g. maximum allowed users, license type etc), we also plan to create an admin portal and APIs that will be used by our internal employees only. For this portal, we also want to define roles …