Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Argument of AND must be type boolean, not type character varying
I have a model called Baksgewijs with a models.BooleanField called eindbaksgewijs and I try to on the page of the baksgewijs if eindbaksgewijs is True. Here is my model: class Baksgewijs(models.Model): name = models.CharField(max_length=64) description = models.CharField(max_length=512, blank=True, default="") date = models.DateField() peloton = models.ManyToManyField(Peloton) eindbaksgewijs = models.BooleanField(default=False) def __str__(self): return self.name My view for displaying a baksgewijs looks something like this: def display_baksgewijs(request, baksgewijs_id): baksgewijs = Baksgewijs.objects.get(id=baksgewijs_id) if Baksgewijs.objects.get(id=baksgewijs_id, eindbaksgewijs=True): print("This is true") return render(request, "baksgewijs/baksgewijs_pelotons.html", { "baksgewijs" : baksgewijs }) display_baksgewijs is shown from this url: path("<int:baksgewijs_id>", views.display_baksgewijs, name="baksgewijs") But when I display a baksgewijs, I get the following error: argument of AND must be type boolean, not type character varying Why can I not check whether or not eindbaksgewijs is True in the model? -
USSD menu response with Django not working
AM building a USSD application, in Django with this API https://documenter.getpostman.com/view/7705958/UyrEhaLQ#intro. I get the responses from the API and initialize the data to be processed. But I don't get the menu (MSG) to display on the user phone successfully. The error I get is invalid(empty) response. This is the response to the user’s request. The content provider should provide a response to the request in the same format. USERID = This is the ID provided by NALO to the client MSISDN = The mobile number of the user MSG =This is a mandatory parameter that holds the message to be displayed on the user’s phone MSGTYPE = This indicates whether the session should continue or be terminated (True/false) @csrf_exempt def ussd(request): if request.method == 'GET': html = "<html><body>Nothing here baby!</body></html>" return HttpResponse(html) elif request.method == 'POST': url = "https://99c9-102-176-94-213.ngrok.io/ussd" response_data = json.loads(request.body) code_id = response_data["USERID"] serviceCode = response_data["MSISDN"] type = response_data["MSGTYPE"] session_id = response_data["SESSIONID"] text = response_data["USERDATA"] msg = "" if text == "": msg = "Welcome To TEST Dev" elif text == "1": msg = "This is Test Two" payload ={ "USERID": code_id, "MSISDN": serviceCode, "MSGTYPE": type, "USERDATA": text, "SESSIONID": session_id, "MSG": msg, } headers = { 'Content-Type': 'application/json' … -
invalid literal for int() with base 10: b'31 11:15:47.294407' on Django
I have model like this when I created an item. it gives an error like this: invalid literal for int() with base 10: b'31 11:47:21.619913' from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Book(models.Model): name = models.CharField(max_length=255) writer = models.CharField(max_length=255) explanation = models.TextField(blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) publication_date = models.DateTimeField() def __str__(self): return f'{self.name} - {self.writer}' class Comment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='comments') owner = models.CharField(max_length=255) comment = models.TextField(blank=True, null=True) publication_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) rating = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return self.rating -
Fill Foreign Key Field in Form Field with Related Record in Django
I have 2 models Office & Meeting. class Office(models.Model): name = models.CharField(verbose_name=u"name",max_length=255) class Meeting(models.Model): meeting_office = models.ForeignKey(Registration,verbose_name=u"Office", on_delete=models.DO_NOTHING, related_name='meeting_office') date = models.DateField(verbose_name=u"Date", null=False, blank=False) I have a form that creates the blank meeting successfully class MeetingForm(ModelForm): class Meta: model = Registration fields = ( 'date', 'meeting_office' ) widgets = { 'date' :forms.TextInput(attrs={'class': 'form-control'}), 'meeting_office' :forms.Select(attrs={'class': 'form-control'}), When I want to have a prefilled form, i have a view that is below def office_add_meeting(request, office_id): office = Office.objects.get(pk=office_id) form = MeetingForm(request.POST or None) if form.is_valid(): form.instance.meeting_office = office form.save() messages.success(request, "Insert Successfull") return HttpResponseRedirect('/office_main') return render(request, 'Office/meeting-form.html', {"form": form, "office_id": office_id}) But the form does not prefill the foreign key field. Confirmed the office_id has been passed to the view successfully. Idon't see why the form is not using the defined instance. Any ideas what could be causing this? Or is there a better way? -
Signup Form Fields are not rendering Django
Here is my code In Urls.py from django.contrib.auth import authenticate, login, logout from .forms import CustomUserCreationForm def registeruser(request): form = CustomUserCreationForm() if request.method == "POST": form = CustomUserCreationForm(request, POST) if form.is_valid(): user = form.save(commit=False) user.save() user = authenticate(request, username=user.username, password=request.POST['password']) if user is not None: login(request, user) return redirect('home') context = {'form' : form} return render(request, 'signup.html', context) urlpatterns = [ path('signup/', registeruser, name='signup'), ] In forms.py from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] def __init__(self, *args, **kwargs): super(CustomUserCreationForm, self).__init__(self, *args, **kwargs) self.fields['username'].widget.attrs.update({'class' : 'form-control', 'placeholder' : 'Enter Username'}) self.fields['password1'].widget.attrs.update({'class' : 'form-control', 'placeholder' : 'Enter Password'}) self.fields['password2'].widget.attrs.update({'class' : 'form-control', 'placeholder' : 'Re-Enter Password'}) In Signup.html <form class="text-left clearfix" method="POST"> {% csrf_token %} {% for field in forms %} <div class="form-group"> {{field}} </div> {% endfor %} <div class="text-center"> <button type="submit" class="btn btn-main text-center">Sign UP</button> </div> </form> Result is Signup page image I tried alot of settings but got no input field on signup page. It just render nothing. Please help me what am i doing wrong? -
Django (DRF) fails silently
I have been working on a side project using django and django rest framework. There is even an active version running in the cloud currently without any issue. I wanted to make some minor changes on the code base but while using the django admin page it crashes silently. I haven't changed anything in the code until now. [2022-08-31 13:39:10 +0200] [8801] [INFO] Starting gunicorn 20.1.0 [2022-08-31 13:39:10 +0200] [8801] [INFO] Listening at: http://127.0.0.1:8000 (8801) [2022-08-31 13:39:10 +0200] [8801] [INFO] Using worker: sync [2022-08-31 13:39:10 +0200] [8802] [INFO] Booting worker with pid: 8802 [2022-08-31 13:39:18 +0200] [8801] [WARNING] Worker with pid 8802 was terminated due to signal 11 [2022-08-31 13:39:18 +0200] [8810] [INFO] Booting worker with pid: 8810 [2022-08-31 13:39:23 +0200] [8801] [WARNING] Worker with pid 8810 was terminated due to signal 11 [2022-08-31 13:39:23 +0200] [8814] [INFO] Booting worker with pid: 8814 Same happens with python manage.py runserver command. I'm using a virtual environment with python 3.9 -
Django queryset retrieve many-to-many choosen field values
I have a class A(Aid,Aname,manytomanyfield) with a many to many relationship to a class B(Bid,Bname). I have for example three rows in A : Aid,Aname 1,foo 2,bar 3,baz I have for example three rows in B: Bid,Bname 1,foo 2,bar 3,baz With Django ORM I don't really see the relationship class, C which contains for example: Aid,Bid 1,1 1,2 1,3 2,2 2,3 I want all A rows that match for example class B 3,baz rows, in django "A.objects.filter(manytomanyfield=B.get(Bname=baz))": Aid,Aname,Bname 1,foo,baz Is there a way to retrieve all possible values of A relationship with B after filtering? I want: Aid,Aname,Bname,manytomanyfield 1,foo,baz,"foo,bar,baz" In django admin, django produce this result with a new request for every line of the html table. I wonder if we can do this with only one ORM request. Sorry for my english! -
How to upload file, encrypt and make available to download in Django?
This question might be a bit confusing, but I don't know how else to ask it. I want to make a website that lets the user upload a file and then make the file available to be downloaded by another user. I have finished the frontend to backend upload so the file is available in the Django backend. I plan to manually encrypt the file in the backend before saving it to database. I also plan to save the bytes of the file to the database instead of the actual file, for example: uploadedFile = request.FILES["file"] file_data = [] for chunk in uploadedFile.chunks(): file_data.append(chunk) # Encrypt file_data... # Save file_data to database here... The problem is that after I decrypt the bytes of the file, how do I convert the file bytes to an actual downloadable file? (basically the opposite of file.read() in Django) Does anyone know how to do this, and please edit this question or ask if anything is unclear. Thank you. -
Latest objects of every group with Django filter in mysql backend
I have 2 Models- class WLSDomainName(BaseMixin): domain_name = models.CharField('Domain Name',max_length=255, null=False, blank=False) site_name = models.CharField('Site Name', max_length=10, choices = SITE_NAME, default='dc',blank=False, null=False) delete_status = models.BooleanField(default=False) class DomainOverallHealthStatus(BaseMixin): domain_name = models.ForeignKey(WLSDomainName, on_delete=models.CASCADE, null=True, blank=False, related_name="overall_health_status_domain_name") configuredServerCount = models.IntegerField(blank=True, null=True) activeServerCount = models.IntegerField(blank=True, null=True) overallServiceHealth = models.CharField(max_length=255, null=True, blank=True) activeThreadCount = models.IntegerField(blank=True, null=True) activeHttpSessionCount = models.IntegerField(blank=True, null=True) classification_time = models.CharField(max_length=20, null=True, blank=True) I need to find the latest object from DomainOverallHealthStatus model for every object of WLSDomainName. I have tried- o_health = DomainOverallHealthStatus.objects.all().values('domain_name').annotate(Max('created')).order_by() This query returning me only id and created. <QuerySet [{'domain_name': 1, 'created__max': datetime.datetime(2022, 8, 31, 9, 14, 49, 217073, tzinfo=datetime.timezone.utc)}, {'domain_name': 2, 'created__max': datetime.datetime(2022, 8, 31, 9, 14, 50, 338368, tzinfo=datetime.timezone.utc)}]> But I need to fetch every column of DomainOverallHealthStatus. Thanks in advance. -
Host blocking SMTP connection [closed]
I'm working on a django/python API. I've been trying to configure smtp settings but it's refusing connection to the host. I've tried running the telnet command, turning off my firewall, and created an inbound rule but still nothing works. Any help? -
Issue in making a Pie Chart using django with fully dynamic data
I have a Django backend that is sending this dict : {'New': 1, 'Pending': 0, 'Done': 0} I have to make a pie chart with this, So I tried: labels: ["{% for key, value in pie.items %}{{key}}{% endfor %}"] and the output is "NewPendingDone" instead of New, Pending, Done My Full code is : var config = { type: 'pie', data: { datasets: [{ data: ["{% for key, value in pie.items %}{{value}}{% endfor %}"], backgroundColor: [ '#dc3912', '#ff9900', '#3366cc' ], label: '' }], labels: ["{% for key, value in pie.items %}{{key}}{% endfor %}"] <-- here }, options: { responsive: true, plugins: { legend: { position: 'top', }, title: { display: true, text: '' } } } }; Here's the ss of the current situation. Pie Chart -
Django Postgres database with multiple schema. How to add records to specific schema through shell
Iam currently working on django multi tenant using shared database with multiple schema approach. How can I add records to specific schema through shell.How can I get the specific schema database objects in views.py -
Django (DRF) crashing when creating shapely LineString
I have an Django based Rest API application using DRF. On one endpoint an shapely Linestring is created from a list of tuples containing 2d coordinates. When creating the linestring with more than two points the application crashes without error message. # works fine data = [(430739.78125, 5642007.5), (430662.03, 5642191.5)] # not working data = [(430739.78125, 5642007.5), (430662.03, 5642191.5), (430623.1, 5642283.0)] I have already reinstalled all dependencies but could not solve the issue. -
how to serialize when fields are not known in django-rest-framework?
I want to serialize a dictionary where field_name is not fixed, it can be anything and i need to validate if type of field_value is correct according to what type should be provided to field_name. e.g: { "attributes": { attribute_name: attribute_vale . . . (can contain such more pairs) } } Is there any serializer way that can help me to serialize the key-value pair of attributes dictionary? -
Attribute Error: 'QuerySet' object has no attribute 'name'
in my Django project, I have a list of items where users specify categories while submitting "Crate New Item" form. The default route shows this list of items with the title, description and category of the item. Users can click on each category to be redirected to that related category's page where I'm trying to display all items under that category. To do that, I want to check if the category submitted in the form is already in our Category database. If yes, the item should be added under the existing category's page and if not, a new category should be created. However, I get an attribute error while trying to check that and I'm stuck. Would appreciate any help. AttributeError at /create 'QuerySet' object has no attribute 'name' models.py: class User(AbstractUser): pass class Category(models.Model): name = models.CharField(max_length = 64, null = True) class AuctionItem(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, related_name = "created_by") title = models.CharField(max_length = 64) description = models.TextField() price = models.DecimalField(max_digits = 100 ,decimal_places = 2) image = models.URLField(blank = True) category = models.ForeignKey(Category, on_delete = models.CASCADE, related_name = "item_category") date = models.DateTimeField(auto_now_add = True) urls.py: urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", … -
How to get list as a value from another model of a serializer key's value in DRF serializer?
Models: class SellerHub(BaseModel): name = models.CharField(blank=False, max_length=255) address = models.TextField( blank=True, ) status = models.BooleanField(default=True) contact_person = models.CharField(blank=False, max_length=255) hub_type = models.ForeignKey(SellerHubType, on_delete=models.CASCADE) latitude = models.DecimalField( max_digits=22, decimal_places=16, blank=True, null=True ) longitude = models.DecimalField( max_digits=22, decimal_places=16, blank=True, null=True ) image = models.ImageField( default="default_images/default_seller_hub.png", upload_to=seller_hub_image_path, ) status = models.BooleanField(default=True) class Meta: app_label = "seller_hub" def __str__(self): return self.name class SellerHubPhone(BaseModel): seller_hub = models.ForeignKey(SellerHub, on_delete=models.CASCADE) phone = PhoneNumberField(blank=False, max_length=255) status = models.BooleanField(default=True) def __str__(self): return f"{str(self.phone)} for {self.seller_hub.name}" Serializers: from rest_framework import serializers from seller_hub.selectors import seller_phone from phonenumber_field.serializerfields import PhoneNumberField class SellerHubPhoneSerializer(serializers.Serializer): phone = PhoneNumberField() class SellerHubSerializer(serializers.Serializer): id = serializers.IntegerField() name = serializers.CharField(max_length=255) address = serializers.CharField() image = serializers.ImageField() phone = serializers.SerializerMethodField("get_phone") def get_phone(self, obj): hub_phone = seller_phone(obj) # Returns a queryset of SellerHubPhone objects print("Phone: ", hub_phone) serializer = SellerHubPhoneSerializer(hub_phone, many=True) return serializer.data This is my current output: "data": [ { "id": 1, "name": "Test Seller Hub", "address": "Test seller Address", "image": "http://127.0.0.1:8000/media/default_images/default_seller_hub.png", "phone": [ { "phone": "+8801777777777" }, { "phone": "+491783379222" } ] } ] Expected Output: "data": [ { "id": 1, "name": "Test Seller Hub", "address": "Test seller Address", "image": "http://127.0.0.1:8000/media/default_images/default_seller_hub.png", "phone": [ "+8801777777777", "+491783379222" ] } ] Here SellerHub might have multiple phone numbers, so I am … -
How to run crontab in docker container with django?
Currently i am run python3 manage.py crontab add in docker bash,but cron not run. Please check the screenshot here cron adding message show but also return /bin/sh: 1: /usr/bin/crontab: not found error. -
Django django-two-factor-auth Error 'two_factor_tags' is not a registered tag library
I needed 2FA for my Staff members so I installed django-two-factor-auth But there seems to be an issue with the 'two_factor_tags' in core/login.html file Error message : 'two_factor_tags' is not a registered tag library . Must be one of: admin_list admin_modify admin_urls cache crispy_forms_field crispy_forms_filters crispy_forms_tags crispy_forms_utils example i18n l10n log static tz Using : Django==4.1 django-otp==1.1.3 django-phonenumber-field==6.4.0 django-two-factor-auth==1.14.0 phonenumbers==8.12.54 Any help is much appreciated. I did remove the tag from the code but it might bug my entire login system. -
Django Celery calling redis but I am using RabbitMq as Message broker
I am using celery and RabbitMq as message broker with Django and Docker. after putting my docker image up I run the following command: docker-compose run --rm web bash to enter my container and then I run: celery -A wine_shop worker --loglevel=info instead of getting a confirmation that my borker is working I get the following message: [2022-08-31 09:30:57,796: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6380//: Error 99 connecting to localhost:6380. Cannot assign requested address.. Trying again in 2.00 seconds... (1/100) I can notice that the transport is wrong, it should be calling the py-amqp transport but it's calling redis. -------------- celery@4c40607a9f71 v5.2.6 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-5.15.0-46-generic-x86_64-with-glibc2.31 2022-08-31 09:30:57 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: wine_shop:0x7f2546178460 - ** ---------- .> transport: redis://localhost:6380// - ** ---------- .> results: - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery Any ideas on how to solve it? Down here you can find my configuration files: Settings.py from pathlib import Path import os from decouple import config # Build paths … -
getting error in django models while using foreign key
I am using foreign key in django models. But getting error. models.py: class subscription(models.Model): duration_choice = ( ("Monthly", "Monthly"), ("1 Year", "1 Year"), ("2 Year", "2 Year"), ) Duration = models.CharField(max_length=100,choices=duration_choice) Price=models.IntegerField(default=0) def __str__(self): return self.Duration class pro_Members(models.Model): subscription_type = models.ForeignKey(subscription,on_delete=models.CASCADE, default="") start_date=models.DateField(blank=True, null=True) expire_date= models.DateField(blank=True, null=True) is_active=models.BooleanField(default=False) I used subscription models as foreign key in pro_members model. But getting an error. column firmApp_pro_members.subscription_type_id does not exist LINE 1: SELECT "firmApp_pro_members"."id", "firmApp_pro_members"."su... anyone here can help. I tried my best but can not solve it. -
Django return, Profile matching query does nor exit
I'm new to Django and I'm working on an Instagram clone project as a beginner. And I didn't get this error. I imported the user The Profile class is created here, and it is successfully migrated. and this is my views.py someone please answers this where is my mistake? -
Is the server running on that host and accepting TCP/IP connections?
I am working on a Django project as a Front-End developer. I am getting " django.db.utils.OperationalError: connection to server at "13.234.81.119", port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections?" many times when I try to run the server using the command python manage.py runserver on VS Code Because of this, I have to restart the server, and sometimes luckily server works. I did the following things to resolve the problem: NOTE: I am using windows 11. 1) deleted temporary files using the command %temp% 2) reinstalled psycopg 2.9.2 3) I reset the TCP/IP settings in services on my PC. but the problem did not solve. I am attaching the screenshots of the complete error log. Please help me to resolve the issue, I will be grateful to you -
Nested serializer representation for PrimaryKeyRelatedField
I want to add and remove products to an order by only using their ids, but I want the order representation to look like a nested serializer. My Models: class Product(models.Model): title = models.CharField(max_length=200) price = models.DecimalField(max_digits=1_000, decimal_places=2) def __str__(self): return self.title class Order(models.Model): date = models.DateField() products = models.ManyToManyField(Product, blank=True, related_name='orders') My Serializers: class ProductSerializer(serializers.ModelSerializer): price = serializers.DecimalField(max_digits=1_000, decimal_places=2, coerce_to_string=False) class Meta: model = Product fields = ['id', 'title', 'price'] class OrderSerializer(serializers.ModelSerializer): products = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), many=True) class Meta: model = Order fields = ['id', 'date', 'products'] I'm trying to get the below representation: { "id": 1, "date": "2021-08-12", "products": [ { "id": 1, "title": "Item 1", "price": 19.99 }, { "id": 3, "title": "Item 3", "price": 49.99 } ] } However, if I want to create the above order the json should look like this: { "date": "2021-08-12", "products":[1, 3] } And if I want to add a product with id==2 to the above order it should look like this: { "id": 1, "date": "2021-08-12", "products":[1, 3, 2] } I've tried overriding the to_representation() method and adding a nested serializer there, but I have no idea how to go about it. Should it look something like this, or am … -
being able to encode url parameters in django template while using url tag to prevent NoReverseMatch error
I'm writing a project with python 3.10 and django 4.1 I defined the following route: app_name = 'admin_extend' urlpatterns = [ path('add_fav/<str:name>/<str:add_url>/<str:admin_url>/', views.add_fav, name='add_fav'), ] now i have 3 parameters here, name, add_url and admin_url. both add_url and admin_url contains '/' so i need to be able to escape them in the django template. this is my code in the template: <a href="{% url 'admin_extend:add_fav' name=model.name add_url=model.add_url admin_url=model.admin_url %}" class="changelink">{% translate 'Fav' %}</a> lets say the parameters value are name='foo', add_url='/a/b/c/', admin_url='/c/d/e/', the route fails with NoReverseMatch: Reverse for 'add_fav' with keyword arguments '{'name': 'foo', 'add_url': '/a/b/c/', 'admin_url': '/c/d/e/'}' not found. 1 pattern(s) tried: ['admin_extend/add_fav/(?P<name>[^/]+)/(?P<add_url>[^/]+)/(?P<admin_url>[^/]+)/\\Z'] i tested it and if i provide the parameters without / characters then i get no error. my problem is i really can't find anywhere how to escape these parameters, i googled and checked on stackoverflow a lot for example i can't use the {% filter urlencode %} before and after because the url needs to be validated first and then it will go through the urlencode, i learned that i can't run python code in these templates so i can't use urlqoute from django.utils.http and using urlencode filter in this way is not a … -
Django: Why model manager (objects) get_queryset() method executes during initialization phase?
I'm building a SAAS site, which currently uses django_tenants with postgresql for a physical separation of tenants into different schemas. I've decided to move everything into a single schema and impliment logical data separation instead. During my proof-of-concept phase, I've added a new middleware with the new tenant logic, and left the existing middleware (from django_tenants) in place. From my settings: MIDDLEWARE = [ 'tenants.middleware.main.TenantMainMiddleware', 'utilities.middleware.TenantMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] The existing one from django_tenants is the first one: TenantMainMiddleware - my new one is the next line down: TenantMiddleware Basically, I will add a ForeignKey field to each model that needs tenant separation, and my middleware will load the appropriate tenant instance based on the subdomain part of the domain. For example: demo.mysite.com - will cause a lookup on "demo" in the tenant table. The resulting tenant object will be added to the request object, which is, in turn, stored in thread local storage. Here's my middleware: class TenantMiddleware(MiddlewareMixin): def process_request(self, request): current_tenant = connection.tenant # This is temporary to connection.set_schema_to_public() # allow the existing subdomain = self.get_subdomain_from_request(request) # tenant code to still work try: tenant = VTenant.objects.get(subdomain__iexact=subdomain) except VTenant.DoesNotExist: raise APIInvalidRequest(_('No tenant for subdomain …