Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the color of a shapefile layer in Django Admin's Leaflet map based on a field's value?
I'm working on a GeoDjango project where I'm displaying a shapefile layer in a Leaflet map embedded in the Django Admin interface. I need to dynamically color the geometry (geom field) in the map based on the value of another field in the model called mean_ctrl. Django Admin with Geom Field Here’s the color scheme I want to implement: def get_color(mean_ctrl): if mean_ctrl < 60: return "#38A800" elif 60.1 <= mean_ctrl <= 120: return "#55FF00" elif 120.1 <= mean_ctrl <= 170: return "#FFFF00" elif 170.1 <= mean_ctrl <= 220: return "#FFAA00" elif 220.1 <= mean_ctrl <= 270: return "#FF0000" else: return "#C500FF" I am looking for guidance on how to apply this color scheme to the Geom field on the Leaflet map in Django admin. Any guidance would be very helpful! Thank you. -
How to get all fields with choices in a Django model?
I have a Django model with dozen fields with Choice options and I want to serialize their values to write an CSV file. How can I traverse the fields to find the ones with Choices options? Something like that: for field in MyModel._meta.fields: if field.has_choices_on_it(): print(f.name) -
Optimize request to db Django
which way is better? and why? queryset = Tariff.objects.filter(user=user).order_by('-created_at').first() or queryset = Tariff.objects.filter(user=user).order_by('created_at').last() You need to get the newest record from the database, which way is better and faster? -
I am unable to add my django project to a github repository due to a loop of errors
I am trying to connect my Django project to a Git repository but whenever I try to stage, commit, then push I get an error when I push about how "The branch "main" has no remote branch. Would you like to publish this branch?" I click okay then it says "Can't push refs to remote, Try running "Pull" first to integrate your changes." but when I pull I get the following error "Git: There is no tracking information for the current branch" so I am completely lost and I am unsure as to what else to provide for this problem to be fixed since this is also my first time doing a solo coding project. I have tried looking up what to do but whenever I do its nothing that helps with the current situation because its a whole loop of me not knowing what the cause is and where to start looking. -
Deploying Django REST API backend on AZURE
I have tried to solve how to deploy Django project on Azure, been following many tutorials but in this point i cant point whats the issue. Deploying from GitHub, deployment have been success whew times but i cant to access to my application, i get mostly 404 or application error when run trough browser. I have postgre locally migrated but i want to use Azure postgre DB. Been pandering with ENV variables, i cant to connect to SHH to apply migrations, CONN CLOSE..etc So i have no idea where to start now actually? I have tried Microsoft guides, guides from internet, asking help from ChatGPT. I want to deploy my Django app on Azure but have no idea now , 'how to' . -
How to create a dropdown Django admin filter with select2?
I am working on a Django admin customization where I need to create dropdown filters with select2. I am using the django-admin-autocomplete-filter package, which works fine for foreign keys but it seems regular fields are not supported. For example, my Collection model has an IntegerField (months). I added list_filter = [AutocompleteFactory(‘Months’, ‘months’] inside the CollectionAdmin and I get this error: DeferredAttribute object had now attributed ‘get_queryset’ -
How can i resolve this issue on REnder
ERROR: Ignored the following versions that require a different python version: 1.21.2 Requires-Python >=3.7,<3.11; 1.21.3 Requires-Python >=3.7,<3.11; 1.21.4 Requires-Python >=3.7,<3.11; 1.21.5 Requires-Python >=3.7,<3.11; 1.21.6 Requires-Python >=3.7,<3.11 ERROR: Could not find a version that satisfies the requirement pkg_resources==0.0.0 (from versions: none) ERROR: No matching distribution found for pkg_resources==0.0.0 What I've Tried: Upgrading pip with pip install --upgrade pip. Upgrading setuptools with pip install --upgrade setuptools. Attempted to create a virtual environment. Any advice on how to resolve these errors would be greatly appreciated! -
Anotation after filter (freeze queryset) Django
In the process of model annotation there is a need to filter the finished list. But the value of the annotation "rank" after the filter() becomes "1" because it has only one element. Without filtering the queryset everything works fine request_user = ( MainUser.objects.select_related("balance_account") .annotate(coin_balance=F("balance_account__coin_balance")) .annotate(rank=Window(expression=RowNumber(), order_by="-coin_balance")) .filter(id=data.get("user_id")) .first() ) Is there a way to avoid the race or freeze the filtered queryset? -
nh3 and mark_safe usage in django markdown
I am using the nh3 library with my Django project to sanitize my HTML of my rendered markdown. I also have fenced code blocks and code block highlighting implemented. If I do not use mark_safe on my nh3 cleaned markdown, all my rich text markdown becomes html code. If I use mark_safe in my Post model after cleaning the markdown, it no longer appears as html code. This is what I have in my Post model's get_message_as_markdown function responsible for generating markdown: from markdown import markdown import nh3 def get_message_as_markdown(self): clean_content = nh3.clean(self.message) rendered_content = markdown(clean_content, extensions=['fenced_code', 'codehilite']) return mark_safe(rendered_content) Is this "safe" to do? Thanks in advance! -
How can I dynamically instantiate multiple apps through django plotly dash?
I am using https://django-plotly-dash.readthedocs.io/en/latest/index.html to build a dash app. I want to dynamically create a new app when the symbol is different. I think this will create a new entry in django_plotly_dash_statelessapp table. How can I achieve this? Example: @app.callback( Output("example-graph", "figure"), [Input("input-element-id", "value")] ) def update_figure(input_value, session_state=None, **kwargs): symbol = session_state["symbol"] # Each unique symbol creates a different app instance new_figure = { "data": [ {"x": [1, 2, 3], "y": [input_value, input_value + 1, input_value + 2], "type": "bar"} ], "layout": {"title": f"Updated Chart for {symbol}"} } return new_figure Call in my view: class SomeDetailView(DetailView): model = SomeModel context_object_name = "detail" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Access the current session and add `symbol` to it session = self.request.session django_plotly_dash_objs = session.get("django_plotly_dash", {}) django_plotly_dash_objs["symbol"] = context["detail"].symbol session["django_plotly_dash"] = django_plotly_dash_objs return context -
Django background task not runnng
I am trying to send an email with a django background task. But the problem is that when I run python manage.py process_tasks nothing happens. I am just stuck in part where it looks like it is running but nothing is returned to the terminal logger = logging.getLogger(__name__) @background(schedule=1) def notify_user(): logger.info("Task started") smtp_server = "smtp.gmail.com" port = 465 sender = "email" password = "password" context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: server.login(sender,password) print("Yes") user = get_user_model() I have tried changing the intervals in between runs to 60(seconds) but it wasn't working so I changed it to 1(second) to see if it would work. But alas it doesnt -
Different behaviour when redirecting on local vs production Astro + Django + Nginx
I have deployed an webapp using Astro, Django and Nginx. I am testing the integration with Stripe using Stripe Checkout. So I set up a html form: <form method="post" action=`${baseDomain}users/signup`> ... </form> where baseDomain = http://localhost:8000/api/ if in dev mode and baseDomain = https://example.com/api/ in production. The /users/signup endpoint is handled by a view that ends up calling a function for the redirection to stripe similar to the example in Stripe Checkout. When testing it in my local environment it works great, I am able to access the test checkout form, pay for the product and I am redirected to my custom success page. Here's a screenshot of the Network tab in my browser DevTools: However in production I get the following error: Even though the status is OK for the Stripe Checkout page the browser issues a GET request back to form endpoint, resulting of course in a method not allowed error. What I can notice is that the type of request has changed from document to fetch and the initiator chain is not exactly the same. This is the initiator chain in my local environment This is the initiator chain in prod: I've tried redirecting to just "https://google.com" … -
Django template rendering order... - problem with include and partial and blocks
I've got: ViewChild.html: {% extends 'app1/parent.html' %} {%block title%} my title {%endblock title%} Then I've got Parent.html: {%include 'html_parts/modal_part.html' %} That uses partial view: {%block title%} {%endblock title%} Unfortunately, the view is not rendered correctly ie. 'my title' is not displayed. (it is all ok with application, paths, etc. All files are placed in coorect folders). It is only something with the logic of rendering. Possibly, I can't use in parent view a partial, that defines block, that is going to be filled by child view? Any advices? -
EndpointConnectionError using Localstack with Django
I'm working on setting up Localstack in my Django app so we don't need to connect to S3 for local development. This is the relevant part of my docker-compose: app: build: context: . dockerfile: docker/app.Dockerfile command: > bash -c "poetry run python manage.py runserver_plus 0.0.0.0:8000 --reloader-type watchdog" ports: - 8000:8000 - 5678:5678 volumes: - .:/app - venv:/app/.venv depends_on: - db - celery - elasticsearch - localstack stdin_open: true tty: true networks: - proxynet localstack: container_name: localstack image: localstack/localstack ports: - '4566:4566' volumes: - ./localstack-data:/var/lib/localstack - /var/run/docker.sock:/var/run/docker.sock And I have these settings in my settings.py file: MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR("media") DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_DEFAULT_ACL = "private" AWS_S3_ACCESS_KEY_ID = "local" AWS_S3_SECRET_ACCESS_KEY = "local" AWS_S3_ENDPOINT_URL = "http://localhost:4566" AWS_STORAGE_BUCKET_NAME = "mybucket" But no matter what I try, when I try to upload a file in my application, I get a botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "http://localhost:4566/mybucket". This only happens when the request to S3 is made through the Django request/response cycle, because I have a few scripts I wrote that are working fine with localstack. For example: #!/bin/bash export AWS_ACCESS_KEY_ID=local export AWS_SECRET_ACCESS_KEY=local export AWS_DEFAULT_REGION=us-east-1 aws s3api create-bucket --bucket "$1" --endpoint-url http://localhost:4566 # Check if the bucket creation was successful … -
How to get the log and result of websocket async_to_sync calling
I have websocket and simply send the mesasges to channel_layer from channels.layers import get_channel_layer channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( '{}'.format(mychannelname), { "type": "chat_message", "message": "send you" } ) It seems works well and messages goes to client browser, however I want to know if it works well or not from server. Is it possible or can I get the number of clients connected to channel? My consumers.py makes channels import json from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = self.scope["url_route"]["kwargs"]["room_name"] await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.send(text_data=json.dumps({ 'channel_name': self.channel_name })) async def disconnect(self, close_code): print("some disconnect") await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] print("receive data",text_data_json) print("channel_name:",self.channel_name) print("group_name:",self.room_group_name) if text_data_json['type'] == "register": self.user_id = text_data_json['message'] print("user_id is:",self.user_name) #res = await self.save_message_to_db(message) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': "nicelydone", } ) async def chat_message(self, event): print("someone call chat_message") message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) -
When I deployed Django in gunicorn and nginx, the admin login cannot login. But in development mode, it worked fine. Any advice?
When I input the correct admin login, the page just refreshed and came back to the same page. how should i troubleshoot? i have also done collectstatic and update my nginx configuration to the same static directory. Anyone can advise how to troubleshoot or debug? -
Upload multiple file objects to API as 2d array of files
I am trying to build an API using django which support file uploads as an array of array. An example of what I am trying to achieve is, [ { "string": "Some string", "files": [ "<uploaded file object 1>", "<uploaded file object 2>" ] }, { "string": "Some string", "files": [ "<uploaded file object 3>" ] }, { "string": "Some string", "files": [] } ] I dont want to use base64 encoded files for this since the files can be sometimes large, so I dont want to increase the overheads using base64. **how can I achieve this API call in the most efficient way and what would be most appropriate structure to call this API and help with some javascript frontend code do it. ** I tried to move this to a FormData where I can acheive the a above upload like below but I am not able to call the API from the frontend, it doesnt work probably because I am writing wrong code. strings: ["Some string", "Some string", "Some string"] files: [["<uploaded file object 1>", "<uploaded file object 2>"], ["<uploaded file object 3>"]] For my backend I am using django(rest framework), here is the relevant part of the … -
What are good practices when using Vault to secure a containerized Django application?
I need help with a school project; I have a Django app and a Vault server in separate containers (database and other things too, but they are not important here). I am struggling to understand what should and should not be done when using Vault to ensure my app's security. It's also worth mentioning that the entire project needs to be compiled and ready to use with a single 'make' command, so Vault's initialization, key storage, unsealing, etc., must be handled in scripts. Where should I store Vault's token and root key once initialized? Storing them in plain text files doesn't seem secure, but I'm not sure of other options. Same with the TLS certificates and keys. When is Vault supposed to be sealed? Should Vault be unsealed and then sealed again with each request? Or should Vault remain unsealed as long as the app is running? But in that case, sealing it seems pointless. Is storing keys on the host machine and passing them to containers via environment variables a secure approach? Sorry if these questions seem basic, but this project is a big deal, and I want it to be secure. Thanks! -
Getting :- Error exchanging code for token: invalid_request
So I have been trying to make an extension using MyAnimeList API to fetch user data and upon callback after authorization of the user. It seems there seem to be some problem with my access token def mal_callback(request): code = request.GET.get('code') # Exchange the code for an access token token_response = post( 'https://myanimelist.net/v1/oauth2/token', data={ 'client_id': settings.MAL_CLIENT_ID, 'client_secret': settings.MAL_CLIENT_SECRET, 'code': code, 'grant_type': 'authorization_code', 'redirect_uri': settings.REDIRECT_URI, } ).json() if 'access_token' not in token_response: error_message = token_response.get('error', 'Unknown error') logger.error("Error exchanging code for token: %s", error_message) return redirect('/error/') logger.error("Token response: %s", token_response) access_token = token_response['access_token'] # Retrieve user information user_info_response = get( 'https://api.myanimelist.net/v2/users/@me', headers={'Authorization': f'Bearer {access_token}'} ).json() # Log the user info response # Make sure user_info_response is valid if 'name' not in user_info_response: # Handle error error_message = user_info_response.get('error', 'Unknown error') logger.error("Error retrieving user info: %s", error_message) return redirect('/error/') # Redirect to an error page or handle as needed username = user_info_response['name'] # Create or get the user user, created = User.objects.get_or_create(username=username) # Create or update the ExternalUser model external_user, _ = ExternalUser.objects.update_or_create( user=user, defaults={ 'provider': 'MAL', 'access_token': access_token, 'refresh_token': token_response.get('refresh_token'), 'token_expires_at': token_response.get('expires_at'), } ) # Log the user in login(request, user) return redirect('/') I rechecked all variable and constant values and … -
Recover Custom Field when Editing Django Admin Form
Given the current models in models.py: from django import forms from django.db import models from decimal import Decimal from datetime import datetime, date class Order (models.Model): assignment = models.ForeignKey("Assignment", on_delete=models.RESTRICT) qty = models.PositiveIntegerField(default=1) order_date = models.DateField() price = models.DecimalField(max_digits=10, decimal_places=2) class Assignment (models.Model): assig_year = models.PositiveSmallIntegerField() customer = models.ForeignKey("Customer", on_delete=models.CASCADE) agent = models.ForeignKey("Agent", on_delete=models.CASCADE) class Agent (models.Model): name = models.CharField(max_length=32) surname = models.CharField(max_length=32) class Customer (models.Model): name = models.CharField(max_length=64) I need to provide users with an admin custom form which allows to create and update orders in a more intuitive way. In order to do that, I exclude the assignment field (which bounds a Customer with a Sales Agent for a given year, but may not be so obvious to fill in for a user) and include a custom field for the user to select just a Customer instead. Based on this input and the order date, I internally look for the specific assignment that fulfills this criteria and assign it to the order to be stored in the Database. It looks like this: admin.py from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.contrib import admin from django.db.models import CharField from django import forms from django.db import models from .models import Customer, … -
My login and register page doesnt work when i click the button and my url config is good
i am building a django project and i keep getting this error:- django.db.utils.IntegrityError: null value in column "id" of relation "validation" violates not-null constraint DETAIL: Failing row contains (null, 7, 839510, 0, 2024-10-29 19:51:34.057435+00, f, null). I think it is something to do with my datbase,i use pgadmin views.py from django.shortcuts import redirect, render from django.contrib.auth import login, authenticate from django.core.mail import send_mail from django.utils import timezone from .forms import UserRegistrationForm, UserLoginForm, VerificationForm from .models import Validation # User Registration View def register_view(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) token = random.randint(100000, 999999) Validation.objects.create(user=user, token=token, expired=timezone.now() + timezone.timedelta(hours=1)) send_mail( 'Your Verification Code', f'Use this code to verify your account: {token}', settings.DEFAULT_FROM_EMAIL, [user.email], ) return redirect('verification') else: form = UserRegistrationForm() return render(request, 'registration/register.html', {'form': form}) # Verification View def verify_view(request): if request.method == 'POST': form = VerificationForm(request.POST) if form.is_valid(): token = form.cleaned_data['token'] try: validation = Validation.objects.get(user=request.user) if validation.token == int(token) and validation.expired >= timezone.now(): validation.validation_status = True validation.save() return redirect('profile') else: # Handle case where verification fails except Validation.DoesNotExist: pass else: form = VerificationForm() return render(request, 'registration/verify_email.html', {'form': form})models.py # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) status = models.CharField(max_length=50, … -
Can't Load URL Error on Facebook Login Integration: Missing 'Facebook Login' Product in Developer Console
Question: I'm integrating Facebook Login into my Django web application hosted at https://weddingcloset.store. In the Facebook Developer Console, I set up an app and added weddingcloset.store and www.weddingcloset.store to the App Domains in the Basic settings. I also added the Privacy Policy URL and Site URL.Dashboard error message. Additionally, in my Facebook Developer Console, the "Add Product" option, which includes Facebook Login, does not appear in the sidebar. I cannot find the OAuth Redirect URI field either, making it impossible to specify the redirect path. This is code of my setting.py , I am using django # settings.py from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-x(m$y#9=ko8*q(z8@=0ct%8v6sppw(+9!^mt$tt^926%!0%shf' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'login_via_facebook', ] MIDDLEWARE = [ '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', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'social_logins.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', # Fixed typo here ], }, }, ] WSGI_APPLICATION = 'social_logins.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { … -
How to add additional fields in model serializer in django ModelViewSet?
Cart Serializer classs class CartSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) menuitem = MenuItemSerializer(read_only=True) price = serializers.SerializerMethodField(method_name='calculate_price') menuitem_id = serializers.IntegerField(write_only=True) user_id = serializers.IntegerField(write_only=True) class Meta: model = Cart fields = ['id', 'user', 'menuitem', 'quantity', 'unit_price', 'price', 'menuitem_id', 'user_id'] validators = [ validators.UniqueTogetherValidator( queryset=MenuItem.objects.all(), fields=('id',), message="Menuitem should be unique in this curt" ), validators.UniqueTogetherValidator( queryset=User.objects.all(), fields=('id'), message="User should be unique") ] def calculate_price(self, item: Cart): print(item.unit_price * item.quantity) return item.unit_price * item.quantity add_cart method in CartItemsViewSet class @action(detail=True, methods=['post']) def add_cart(self, request, pk=None): if request.user.is_authenticated: user = request.user else: return Response('User is not authenticated', 403) # print(request.data) # print(request.user.id) # user_id = user.id # menuitem_id = request.data['menuitem_id'] # quantity = request.data['quantity'] # unit_price = request.data['unit_price'] # id = request.data['id'] # pack_data = {'user_id': user_id, 'menuitem_id': menuitem_id, # 'quantity': quantity, 'unit_price': unit_price, 'id': id} serializer = serializers.CartSerializer( data=request.data) if serializer.is_valid(raise_exception=True): print(serializer.validated_data) serializer.save(user_id=user.id) return Response('Item is added successfully.', 201) Cart Model class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) menuitem = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.SmallIntegerField(), unit_price = models.DecimalField(max_digits=6, decimal_places=2) price = models.DecimalField(max_digits=6, decimal_places=2) class Meta: unique_together = ('menuitem', 'user') I want to implement a login user add a menu item to their cart. But the problem is that I do not add additional field 'user_id' when save … -
Latency to be addressed in django for M2M relationship in ModelAdmin dropdown
I have a group of mailboxes which needs to be populated based on customer login and the domains he owns. Customer:User is 1:1 relationship. Tried: views.py: class MailboxAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return Mailbox.objects.none() qs = Mailbox.objects.all() # Check if the user is in the 'customers' group if self.request.user.groups.filter(name='customers').exists(): print('customer login in mailbox autocomplete view.......') # Filter based on the customer's email qs = qs.filter(domain__customer__email=self.request.user.email).only('email') elif self.request.user.groups.filter(name__in=['resellers']).exists(): # Filter based on the reseller's email qs = qs.filter(domain__customer__reseller__email=self.request.user.email).only('email') if self.q: # Further filter based on user input (e.g., email matching) qs = qs.filter(email__icontains=self.q) print(qs.values('email')) return qs in the apps urls.py: path('mailbox-autocomplete/', views.MailboxAutocomplete.as_view(), name='mailbox-autocomplete'), ] in models.py: class GroupMailIdsForm(forms.ModelForm): class Meta: model = GroupMailIds fields = "__all__" mailboxes = forms.ModelMultipleChoiceField( queryset=Mailbox.objects.none(), widget=autocomplete.ModelSelect2Multiple(url='mailmanager:mailbox-autocomplete') ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance.pk: # Check if the instance is being updated if self.request.user.groups.filter(name='customers').exists(): self.fields['mailboxes'].queryset = Mailbox.objects.filter(domain__customer__email=self.request.user.email) elif self.request.user.groups.filter(name='resellers').exists(): self.fields['mailboxes'].queryset = Mailbox.objects.filter(domain__customer__reseller__email=self.request.user.email) in admin.py: class GroupMailIdsAdmin(ImportExportModelAdmin): resource_class = GroupMailIdsResource ordering = ('address',) filter_horizontal = ('mailboxes',) and in settings.py: INSTALLED_APPS = [ 'mailmanager.apps.MailmanagerConfig', 'admin_confirm', 'dal', 'dal_select2', 'django.contrib.admin', 'jquery', ] with other required django apps. The autocomplete is not working. Django version 4.2 used django-autocomplete-light==3.11.0 IS there something I am missing. I am trying to solve … -
Can Django make this multiple tables query in a single statement?
Let simplify the problem. Say I have two models: class Man(models.Model): # some fields class Job(models.Model): man = models.ForeignKey(Man) # other fields Here, my logic is that, some man may have a job, some may not. Now I want to make a query to select men with the info if the man have a job. If I write the query in SQL, then something like: select m.*, j.id from man m left join job j on m.id=j.id where m.some_condition So that if j.id is null, then the man has no job. How to make this query in Django ORM?