Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make an Api to create unique URL's for a Form View (Like Googles Forms uniques URLS)
I'm new in Django Rest Framework and Django. I'm trying to make a service Api. The bussiness rule is "If post a field Email, this service return me a unique URL to go to a survey view". But, I'm only can make services with username and Password with AuthToken and only views with static url. Can you Help me?. Thanks in advance! -
How to make some fields optional in Django ORM
I've coded a function that signs up a user. In my sterilizer the name field is optional but whenever I try to create a user without giving a name, I just face KeyError: 'name'. what should I do to make this code work? def post(self, request): if request.user.is_anonymous: data = RegisterationSerializer(data=request.data) if data.is_valid(): User.objects.create_user(email=data.validated_data['email'], username=data.validated_data['username'], password=data.validated_data['password'], name=data.validated_data['name']) return Response({ "message": f'{data.validated_data["email"]} account was created successfully' }, status=status.HTTP_201_CREATED) else: return Response(data.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response({ "message": "You already authorized" }, status=status.HTTP_400_BAD_REQUEST) -
django-cascading-dropdown-widget - doesn't give me an error but both my dropdown are filled and nothing is cascaded based on parent selection
I don't want to explicitly write an AJAX code to implement cascading dropdown for my django app. While researching alternate methods I came across this django-cascading-dropdown-widget package. I tried following the documentation but the cascade does not work. It doesn't give me an error but both my dropdown are filled and nothing is cascaded based on parent selection. Has anyone tried this packing and how? https://pypi.org/project/django-cascading-dropdown-widget/ -
Clear field in M2M relationship
I have a model which has a field with reference to the same model: class Department(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=100, blank=True, verbose_name='Description') subsidiary = models.ManyToManyField('self',null=True,blank=True, symmetrical=False, related_name='subsidiary_name') superior = models.ForeignKey('self',null=True,blank=True, related_name='superior_name', on_delete = models.SET_NULL) status = models.BooleanField(default=True) I have also save method overriding: def save(self, *args, **kwargs): if self.status: # do smth else: self.subsidiary.clear() # save the instance super().save(*args, **kwargs) I just want to clear my field subsidiary , but my solution doesn't work. Could you help me? -
Page not found at /about/. The current path, about/, did not match any of these. Why can't django follow my URL path?
I'm sure this question has been asked many times before but I'm sure I'm doing everything exactly as the tutorial says and it's still not working. I can access the home page just fine but not the about page. Here is screenshot of the error: https://i.stack.imgur.com/oFNAJ.png I have the URL path in my .urls file (file below) from django.urls import path from . import views urlpatterns = [ path('', views.homepage, name='main-home'), path('about/', views.about, name='main-about'), ] And in the .urls file I have referenced the .views file (below) from django.shortcuts import render from django.http import HttpResponse def homepage(request): return HttpResponse('<h1>Home</h1>') def about(request): return HttpResponse('<h1>About</h1>') I could be missing something blatantly obvious but I've been staring at this for hours now and still can't figure out why it can't find the page. -
check if object exist before saving django rest framework
When i post new data i want to check create new man object and dok object related to man objects but if man object alredy exist i want to append related dok to it any idea how to start i'm totally new to rest_framework class Man(ListCreateAPIView): queryset = Man.objects.all() serializer_class = ManSerial model.py class Man(models.Model): name = models.CharField(max_length=50,unique=True) age = models.IntegerField() def __str__(self): return self.name class Dok(models.Model): man = models.ForeignKey(Man,on_delete=models.CASCADE,related_name="dok_man") cool = models.CharField(max_length=400) def __str__(self) : return str(self.man) serializer.py class Dokserial(serializers.ModelSerializer): class Meta: model = Dok fields ='__all__' class ManSerial(serializers.ModelSerializer): data = Dokserial(source="dok_man",many=True) class Meta: model = Man fields = '__all__' -
Django:How i can call the values of the fields of a form that i want to display properly when i want to generate a pdf printout
Hi stackoverflow team; Am newbie on django ,I Hope i can find solution or someone can help me because am really stuck on , I have spent the whole day searching without reaching my goal; I want to generate a printout after fill out a form , this form contain the fields "longeur", "largeur", "element", the user will fill out this form then he will click on a button to display the "moment" and the "area" that would be calculated automatically and be displayed under the form. but on the printout I would for now just display the values typed by the user in the field "longuer" and "largeur" Here is the story of my code; I have a the model class in models.py of the form(formulaire): class Forms(models.Model): element = models.CharField(verbose_name=" Component ", max_length=60, default="e1") hauteur = models.FloatField(verbose_name=" Height ") longuer = models.FloatField(verbose_name=" Length between posts ") in the views.py: I have defined the function "forms_render_pdf_view" for generating the pdf where I have passed the fields of the form("longeur" and "largeur" to the dictionary "context") that i want their values to be displayed on my pdf printout. def forms_render_pdf_view(request, *args, **kwargs): template_path = 'pages/generate_pdf.html' context = {'longuer':request.GET.get('longuer'), 'largeur':request.GET.get('largeur')} response … -
Add sound to push notifications
I'm using django-push-notifications to send push to our ios users (using APNS). from push_notifications.models import APNSDevice, APNSDeviceQuerySet from apps.notifications.db.models import Notification from apps.users.db.models import User class APNSService: def __init__(self, user: User, title: str, body: str, data: dict): self.user = user self.title = title self.body = body self.data = data def get_devices(self) -> APNSDeviceQuerySet: return APNSDevice.objects.filter(user=self.user) def send_message(self): return self.get_devices().send_message( message=dict( title=self.title, body=self.body ), badge=Notification.objects.filter(recipient=self.user, unread=True).count(), extra=self.data ) The problem is, that notifications comes without a sound. According to the docs, there should be extra field to execute the sound when notification is received. How to do this? -
Get respectives values from Django annotate method
I have the following query: result = data.values('collaborator').annotate(amount=Count('cc')) top = result.order_by('-amount')[:3] This one, get the collaborator field from data, data is a Django Queryset, i am trying to make like a GROUP BY query, and it's functional, but when i call the .values() method on the top variable, it's returning all the models instances as dicts into a queryset, i need the annotate method result as a list of dicts: The following is the top variable content on shell: <QuerySet [{'collaborator': '1092788966', 'amount': 20}, {'collaborator': '1083692812', 'amount': 20}, {'collaborator': '1083572767', 'amount': 20}]> But when i make list(top.values()) i get the following result: [{'name': 'Alyse Caffin', 'cc': '1043346592', 'location': 'Wu’an', 'gender': 'MASCULINO', 'voting_place': 'Corporación Educativa American School Barranquilla', 'table_number': '6', 'status': 'ESPERADO', 'amount': 1}, {'name': 'Barthel Hanlin', 'cc': '1043238706', 'location': 'General Santos', 'gender': 'MASCULINO', 'voting_place': 'Colegio San José – Compañía de Jesús Barranquilla', 'table_number': '10', 'status': 'PENDIENTE', 'amount': 1}, {'name': 'Harv Gertz', 'cc': '1043550513', 'location': 'Makueni', 'gender': 'FEMENINO', 'voting_place': 'Corporación Educativa American School Barranquilla', 'table_number': '7', 'status': 'ESPERADO', 'amount': 1}] I just want the result to be like: [{'collaborator': '1092788966', 'amount': 20}, {'collaborator': '1083692812', 'amount': 20}, {'collaborator': '1083572767', 'amount': 20}] -
Django code work on local machine but dose not work on heroku
my Django code works on my computer but when I pushed it onto Heroku, it shows and error, but whene I run the program on my machine, it works fine. can anyone help me please. The error : 2022-02-11T17:26:36.187430+00:00 app[web.1]: <QueryDict: {'csrfmiddlewaretoken': ['bB8ABomINOKodDyyfQbC8ykkl9Rmormxv9D3X7kVJpyeHeJDKaFeqSPFhZJiThzC'], 'colors': [''], 'size': ['270'], 'colors_ca': [''], 'blurriness': ['4'], 'edges': ['with edges'], 'points': ['5000'], 'back_color': ['#191919'], 'letters': ['$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,"^`\'. '], 'blur': ['71'], 'style': ['cartooning']}> 2022-02-11T17:26:36.191835+00:00 app[web.1]: user>>> admin 2022-02-11T17:26:36.194190+00:00 app[web.1]: media\img\20\866E71D6-7AA1-4429-AB3F-99823DDF29B0.jpeg 2022-02-11T17:26:36.194192+00:00 app[web.1]: path is up 2022-02-11T17:26:36.226445+00:00 app[web.1]: Internal Server Error: /home_f/cartoonify_f/ 2022-02-11T17:26:36.226446+00:00 app[web.1]: Traceback (most recent call last): 2022-02-11T17:26:36.226447+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner 2022-02-11T17:26:36.226447+00:00 app[web.1]: response = get_response(request) 2022-02-11T17:26:36.226455+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response 2022-02-11T17:26:36.226456+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2022-02-11T17:26:36.226456+00:00 app[web.1]: File "/app/app/views/views.py", line 273, in cartoonify 2022-02-11T17:26:36.226457+00:00 app[web.1]: cartoon, total_color = cartooning(path, request) 2022-02-11T17:26:36.226457+00:00 app[web.1]: File "/app/app/views/views_filters_func.py", line 606, in cartooning 2022-02-11T17:26:36.226457+00:00 app[web.1]: print('befor resizing -- origainal 50px small image: ', img.shape) 2022-02-11T17:26:36.226458+00:00 app[web.1]: AttributeError: 'NoneType' object has no attribute 'shape' 2022-02-11T17:26:36.227187+00:00 app[web.1]: 10.1.13.21 - - [11/Feb/2022:17:26:36 +0000] "POST /home_f/cartoonify_f/ HTTP/1.1" 500 64458 "https://pixelifier.herokuapp.com/home_f/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" 2022-02-11T17:26:36.227822+00:00 heroku[router]: at=info method=POST path="/home_f/cartoonify_f/" host=pixelifier.herokuapp.com request_id=9121505b-0838-4c88-bc0f-67cbf633667d fwd="37.239.124.11" dyno=web.1 connect=0ms service=10399ms status=500 bytes=64759 … -
How can I migrate a Wordpress website to Django
I currently have a fully functional Wordpress website that is mostly static. It is a marketing website that mainly displays static webpages. My client would however want to add new features such as accounts functionality and others using the Django web framework. I am well versed in Django, but I would like to know what the best approach is to migrate the Wordpress site into a Django project. Or if there is a better way. Thank you. -
DRF: Updating a model in another models serializer or view
so I have a User and schools model which are related as an Owens(ManyToMany), student, and staff, if an owner registers and creates a school, I would like to perform a partial update to the Owens field of the request.user from having a null/blank or previously created schools to adding the newly created school serializers.py class SchoolSerializerBase(serializers.ModelSerializer): ... class Meta: model = School fields = ... def validate(self, attrs): ... return attrs def create(self, validated_data): instance = School.objects.create( ... ) instance.save() return instance and i have a simple view for it class CreateSchoolView(generics.CreateAPIView): queryset = School.objects.all() permission_classes = [IsSchoolOwner, ] serializer_class = SchoolSerializerBase My question: how do I update the request.user.ownes field and add the school instance to it?? -
django.db.utils.IntegrityError: The row in table 'main_page_projects' with primary key '1' has an invalid foreign key
Created first project model and populated it with some data, then tried to add profile model to it (no data there) through foreign key and while trying to do a migration for linking profile model with projects model getting an error: django.db.utils.IntegrityError: The row in table 'main_page_projects' with primary key '1' has an invalid foreign key: main_page_projects.profile_id contains a value '1' that does not have a corresponding value in main_page_profile.id. Value nr 1 was picked during the makemigration: It is impossible to add a non-nullable field 'profile' to projects without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. I googled around and looked also stackoverflow, probably if I delete migration files and sqlite3 database then migrations should work, but I would like to know how to make it to work without deleting migration files and database. If populate profile then migration also works, but why it won't create a link with default values? What should I do differently or where … -
Django Image not showing up in django when using template tags
When i try calling an image like this {{ profile.image.url }} it works in the profile page, but in the home page when i do {{ post.user.profile.image.url }} nothing shows up and that is not what i expect. i have also tried checking if the image url work and yes it's working. NOTE: It working fine as expected in the profile page but in index.html it seems like nothing is showing up. index.html {% for post in post_items %} <a href="{{post.user.profile.image.url}}" class="post__avatar"> <img src="{{post.user.profile.image.url}}" alt="User Picture"> </a> <a href=""{{ post.user.username }}</a> models.py class Profile(models.Model): user = models.ForeignKey(User, related_name='profile', on_delete=models.CASCADE) image = models.ImageField(upload_to="profile_pciture", null=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) def __str__(self): return f'{self.user.username} - Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) -
Django (dj-rest-auth) Custom user registration with a ForeignKey
I have created a custome user in my App, and points to a timezone record, in the TimeRegion Model. model.py class TimeRegion(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False,) tz_key=models.CharField(max_length=200,) class CustomUser(AbstractUser): id=models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False,) user_timezone=models.ForeignKey(TimeRegion,verbose_name="Time Zone",on_delete=models.DO_NOTHING, blank=True, null=True) Extended the API call to include the custom field. serializers.py class CustomRegisterSerializer(RegisterSerializer): first_name = serializers.CharField() last_name = serializers.CharField() statement_agreement = serializers.BooleanField() user_timezone = serializers.UUIDField() #Tried CharField() and PrimaryKeyField() def get_cleaned_data(self): super(CustomRegisterSerializer, self).get_cleaned_data() return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'password2': self.validated_data.get('password2', ''), 'email': self.validated_data.get('email', ''), 'first_name': self.validated_data.get('first_name', ''), 'last_name': self.validated_data.get('last_name', ''), 'user_timezone': self.validated_data.get('user_timezone', ''), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.user_timezone = self.cleaned_data.get('user_timezone') user.save() return user setting.py REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'api.serializers.CustomRegisterSerializer' } However whenever I run an API test to check that I am able to register a new user, get the following error message: test code # Get the timezone record url_timezone = 'http://127.0.0.1:8000/api/v1/timezonelist/' response_timezone = self.client.get(url_timezone, content_type='application/json') #Register the user to the first timezone: url_signup = 'http://127.0.0.1:8000/api/v1/dj-rest-auth/registration/' params_signup={ 'first_name': 'John', 'last_name': 'Tester', 'email':'testuser@email.com', 'password1':'pwdktudchJsuec123', 'password2':'pwdktudchJsuec123', 'user_timezone': response_timezone.data[0]['id'], } response_signup = self.client.post(url_signup, data=json.dumps(params_signup), content_type='application/json') responce: Traceback (most recent call last): File "/code/api/tests.py", line 45, in test_from_start response_signup = self.client.post(url_signup, data=json.dumps(params_signup), content_type='application/json') File "/usr/local/lib/python3.9/site-packages/rest_framework/test.py", … -
How To Decrypt Content In The Backend Then Pass It To The Frontend With Other Attributes
I'm building a Django social media, that focuses on privacy and anonymity, and I'm trying to build E2EE functionality, but I can't add any JavaScript in the project, so the decryption of the messages, notes is done locally and is stored in a temporary method like a dictionary or a list, then passed to the frontend, my problem is how to pass other attributes to the frontend? like messages are made like this: class Message(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) msg = models.BinaryField(null=False, blank=False) date = models.DateTimeField(default=timezone.now) to = models.ForeignKey(User, related_name='received', on_delete=models.CASCADE, blank=False, null=False) res = models.CharField(max_length=5, blank=False, null=False) author = models.ForeignKey(User, blank=False, null=False, related_name='sent', on_delete=models.CASCADE) so the msg that is the content of every message is the encrypted field, and when the messages view is loaded the messages are decrypted with the users private key class messages(LoginRequiredMixin, View): def get(self, request, touser, *args, **kwargs): if User.objects.filter(username=touser).exists(): user = User.objects.get(username=touser) msgs = Message.objects.filter(Q(to=request.user)|Q(author=request.user)) try: key = request.COOKIES['key'] except: return redirect('set-key') private_key = serialization.load_pem_private_key(request.user.profile.privatekey, password=key.encode('utf-8'),) messagescontent = [] for mess in msgs: plaintext = private_key.decrypt(mess.msg, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) messagescontent.append(plaintext.decode()) context = {'msgs': messagescontent,} else: messages.warning(request, 'User Doesn\'t Exist') return redirect('messages-list') return render(request, 'posts/messages.html', context) so … -
Django ModuleNotFoundError: No module named 'core'
I was working on a blog. The static files are in a bucket on aws and the website is being hosted on heroku. Each time i try to edit a blog post ie(http://127.0.0.1:8000/admin/blog/post/1/change/) I keep getting this error: File "C:\Users\Hp\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'core' Here is my settings.py: """ Django settings for proton project. Generated by 'django-admin startproject' using Django 4.0.2. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os import django_heroku import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secret key' # SECURITY WARNING: don't run with debug turned on in production! … -
django error using if statement with or condtion
I am if using if statement with or condition if batch == (None or 0): raise error and also if batch is not None and farm ==(None or 0): raise error -
django.core.exceptions.ImproperlyConfigured: Set the EMAIL_HOST environment variable
I'm tyring to deploy my app to heroku. after successfully running git push heroku main i'm tyring to run the command heroku run python manage.py makemigrations and i'm getting this error File "/app/.heroku/python/lib/python3.10/site-packages/environ/environ.py", line 367, in get_value value = self.ENVIRON[var] File "/app/.heroku/python/lib/python3.10/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'EMAIL_HOST' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 393, in execute self.check() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/urls.py", line 35, in check_url_namespaces_unique if not getattr(settings, 'ROOT_URLCONF', None): File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, … -
Django Plotly Dash Scatter chart loses interactivity when DataTable added
I am using the django-plotly-dash utility to embed Dash apps into a Django page. If I have a Plotly Scatter chart on the same app as a Dash DataTable then the chart loses it's interactivity. -
Django loading data from fixture fails after schema migration
I have recently came across a problem while trying to reload fixtures to my database after a schema migration. I applied a schema migration which added a new field to my model. The database schema is indeed updated with the new field. However I can't reload fixtures: python manage.py loaddata data.json gives the following error "django.db.utils.OperationalError: Problem installing fixture '/../data.json': Could not load app.CheckupType(pk=1): no such column: name_de" The file data.json contains the same existing data in the database with the new field name_de. When I check the SQL database (or with python manage.py inspectdb), the field name_de exists. But when I run python manage.py dumpdata, there is no such field name_de. I tried to manually add the missing field in python manage.py shell, but I get the following error : "OperationalError: no such column: app_checkuptype.name_de" How can I synchronize my database model to my django model to have my fixtures updated with my new field? I tested the same procedure on another machine and it runs without any issues... -
mssql isn't an available database backend or couldn't be imported
I'm following this guide. Mssql-django and I have Django version 3.2.12 I already installed mssql-django 1.1.1 modified my settings.py to have 'ENGINE': 'mssql', But im still receving this error django.core.exceptions.ImproperlyConfigured: 'mssql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
Django convert external API data into a queryset without actually interacting with local database
In my Django project im fetching data from an external API. It is possible to convert the API data into a django model or class. The resulting data shell be used in a view form which is using django-filter to filter the information by user input. The django-filter instance expects a queryset as input. How do i turn the external API data into a queryset without interacting with the local database in any form? -
Django ORM join a Raw Query
I want to join a fairly complex subquery to a Django ORM queryset: The resulting query should be like: select id from webshop_product left outer join ( select product_id, count(extra_col) as quantity from ( select product_id, col1 as extra_col from xyz where x = 123 and y = 456 union select product_id, col2 as extra_col from abc where a = 234 and y = 534 ) as t1 ) as t2 on t2.product_id = webshop_product.id The subquery in the left outer join clause is quite complex, it involves aggregating from a union from different tables, and I can not write it in the ORM. I tried writing it in the ORM, but I could not achieve the UNION on different tables.... so I want to join it as raw subquery, and annotate the quantity column. Something like: Product.objects.all().join("my complex raw subquery") Is this possible in the Django ORM? -
How can create mega drop down in django?
Anyone can tell me how to create mega menu drop down in django I create but i want if 5 random category and 3 subcategory of every category i am able to display category but not able to display subcategory so how I can display sub category by category