Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is Plotly displaying empty space when displaying a graph through django data?
I am trying to print a pie graph using from Django but it is showing an empty space instead of printing the pie chart. I used the instructions from https://plotly.com/javascript/pie-charts/ but I am getting an error. How do I fix it? views.py labels = list(account_graph.keys()) # ['Food', 'Gas', 'Friends'] data = list(account_graph.values()) # [-6.09, -20.0, -7.0] return render(request, "finances/account.html", {'labels': labels, 'data': data}) account.html <div id='expenses'></div> <script> var data = [{ values: {{data|safe}}, labels: {{labels|safe}}, type: 'pie' }]; var layout = { height: 400, width: 500 } Plotly.newPlot('expenses', data, layout); </script> -
Send request to View Django, without receiving any response
I ask the user a question on my website and if the answer is yes, I will send two data to view Django using a JavaScript file and using Ajax. I want to get this data in View Django and not send any HttpResponse to the user. If we do not send a response in the view, it will give an error. How should I do this? Thanks ValueError: The view tourist.views.planing did not return an HttpResponse object. It returned None instead. def planing(request): if request.is_ajax(): # Get user location from user location.js file: latitude = request.POST.get('latitude', None) longitude = request.POST.get('longitude', None) # To save data request.session['latitude'] = latitude request.session['longitude'] = longitude elif request.method == "GET": return render(request, "tourist/planing.html") elif request.method == "POST": # To retrive data: latitude = request.session.get('latitude') longitude = request.session.get('longitude') if latitude is not None : latitude = float(latitude) longitude = float(longitude) . . . return render(request, "tourist/map.html") -
How to store each months data in django model
I am creating an app where people can log in and create a committee and invite another users to join their committee and then whoever joined it will pay the committee each month till the end date. and one of the users will get the committee at the end of each month, I am having an issue I dont know how to store data of users who are paying month by month. I have created all these django models. but now the missing part is the storing of each months data, so that I can show the status as pending or completed. class Committee(models.Model): committee_creator = models.ForeignKey(Profile, on_delete=models.CASCADE) committee_name = models.CharField(max_length=100) committee_members_limit = models.IntegerField() committee_amount_per_month = models.IntegerField(default=0) committee_month_period = models.IntegerField(default=0) committee_amount_limit = models.IntegerField(null=True) committee_starting_date = models.DateTimeField(auto_now_add=False) committee_ending_date = models.DateTimeField(auto_now_add=False) class Participants(models.Model): participants_name = models.ForeignKey(Profile, on_delete=models.CASCADE) participants_committee_name = models.ForeignKey(Committee, on_delete=models.CASCADE) participants_paid_status = models.BooleanField(default=False) participants_amount_paid = models.IntegerField() participants_payment_slip = models.ImageField(upload_to='images/', null=True, blank=True) -
Django ChoiceField and RadioSelect return EnumMeta error
I have a ChoiceField that I would like to show as Radio selection but I get the following error: EnumMeta.call() missing 1 required positional argument: 'value' Here it is the code model.py class Answer(models.IntegerChoices): NO = 0, _('No') YES = 1, _('Yes') form.py question = forms.ChoiceField( choices=Answer, widget=forms.RadioSelect() ) I've followed the django documentation and I can't figure it out the nature of the error, thank you for any explanation that you can give me -
How to record audio from browser and upload to django server?
I have to record an audio from the browser and upload it to the django server, can someone help me? My django view: @api_view(['POST']) def audio_analysis(request): audio_data = request.FILES['audio'] # view content return render(request, 'homepage.html') -
After setting correct environment I am still facing this issue while deploying django app on heroku
I have added STATIC_ROOT in my setting.py file but still I am facing this error while deploying my app on heroku. Pictures of my settings.py file are attached below. Please help. Error: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. settings.py settings.py -
Django - Error received when anonymous user submits form
In one of my views I have a form where when a user logs in and submits the form, it works fine. However, when an anonymous user submits the form I get the following error: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x1052fd3a0>>": "User_Inquiries.user" must be a "CustomUser" instance. This form needs to be submitted whether a user is anonymous or logged in. What do I need to do in order to resolve this issue? Code below. Any help is gladly appreciated. Thanks! views.py def account_view_contact(request): form = ContactUsForm(request.POST or None, request.FILES or None,) user_profile = User_Inquiries.objects.all() user_profile = User_Info.objects.all() user = request.user if request.method == "POST": # checking if request is POST or Not # if its a post request, then its checking if the form is valid or not if form.is_valid(): contact_instance = form.save(commit=False) # "this will return the 'Listing' instance" contact_instance.user = user # assign 'user' instance contact_instance.save() # calling 'save()' method of model return redirect("home") context = { 'form': form, 'user_profile': user_profile } return render(request, 'contact.html', context) models.py class User_Inquiries(models.Model): email = models.EmailField(max_length=100, null=True) name = models.CharField(max_length=100, null=True) subject = models.CharField(max_length=100, null=True) message = models.CharField(max_length=100, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, null=False, on_delete=models.CASCADE) date_submitted = models.DateTimeField(auto_now_add=True, null=True) class Meta: … -
why git push heroku master giving error at every library?
I have following content in requirements.txt -ip==21.0 aioredis==1.3.1 bs4==0.0.1 django-binary-database-files==1.0.10 django-cors-headers==3.7.0 django-templated-email==2.4.0 djangochannelsrestframework==0.3.0 djoser==2.1.0 msgpack==1.0.2 mysqlclient==2.0.3 pandas==1.3.4 pillow==8.3.1 pip-chill==1.0.1 ply==3.11 psycopg2==2.8.6 psycopg2-binary==2.8.6 pylint-django==2.4.2 pyopenssl==21.0.0 service-identity==21.1.0 sklearn==0.0 waitress==2.0.0 whitenoise==5.3.0 but whenever I use git push heroku master this is giving same error at every library remote: ERROR: Could not find a version that satisfies the requirement aioredis==1.3.1 (from versions: none) remote: ERROR: No matching distribution found for aioredis==1.3.1 I have tried removing aioredis==1.3.1 from requirements.txt then it is giving error on next one and so on. what the exactly issue is? and how can I solve this? -
Django migration dependencies not being honoured
I get that to ensure that a given set of migrations are run before others we need to add the dependent permissions in the dependencies array. I seem to be doing that properly, however, when the migrations are run the dependent ones are not run before the current one and that creates other issues. Here are the details - thanks in advance Django version 2.2.5 File Name: equipment/migrations/0006_add_group_permissions.py class Migration(migrations.Migration): dependencies = [ ("hfauth", "0027_dispatch_staff_permissions"), ("equipment", "0005_add_tractor_manager"), ] operations = [ migrations.RunPython(add_permissions, reverse_code=remove_permissions), ] in the above example, ideally, a ("hfauth", "0027_dispatch_staff_permissions") should run before the current file That's not happening which causes other issues. How do I ensure that some dependencies are executed before running the current one. -
Django admin select like permission field
How to create form in admin panel like this one? It's default admin user view. My looks like that, but i want two "windows" class RoleAdmin(admin.ModelAdmin): list_display = ('name', ) fieldsets=( (None, {'fields': ('name', )}), (_('Role Permissions'), { 'fields': ('permissions', ), }), ) -
why git push heroku master giving error at every library?
I have following content in requirements.txt -ip==21.0 aioredis==1.3.1 bs4==0.0.1 django-binary-database-files==1.0.10 django-cors-headers==3.7.0 django-templated-email==2.4.0 djangochannelsrestframework==0.3.0 djoser==2.1.0 msgpack==1.0.2 mysqlclient==2.0.3 pandas==1.3.4 pillow==8.3.1 pip-chill==1.0.1 ply==3.11 psycopg2==2.8.6 psycopg2-binary==2.8.6 pylint-django==2.4.2 pyopenssl==21.0.0 service-identity==21.1.0 sklearn==0.0 waitress==2.0.0 whitenoise==5.3.0 but this is giving same error at every library remote: ERROR: Could not find a version that satisfies the requirement aioredis==1.3.1 (from versions: none) remote: ERROR: No matching distribution found for aioredis==1.3.1 I have tried removing aioredis==1.3.1 from requirements.txt then it is giving error on next one and so on. what the exactly issue is? and how can I solve this? -
Django ModelForm, not saving data
I'm using ModelForm to create a form, then I'm using this form to create a new instance in the database. But the form is not saving data, it's just reloading the page when the form submmited. I'm also uploading an image. forms.py from django import forms from django_summernote.widgets import SummernoteWidget from events.models import Event class EventCreateForm(forms.ModelForm): class Meta: model = Event fields = "__all__" widgets = { "content": SummernoteWidget(), } def __init__(self, *args, **kwargs): super(EventCreateForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs["class"] = "form-control" self.fields["start_datetime"].widget.attrs["class"] += " datetimepicker" self.fields["finish_datetime"].widget.attrs["class"] += " datetimepicker" self.fields["image"].widget.attrs["class"] = "custom-file-input" self.fields["address"].widget.attrs["rows"] = 3 views.py from django.urls import reverse_lazy from django.views.generic import ListView from django.views.generic.edit import FormView from django.contrib.auth.mixins import LoginRequiredMixin from events.models import Event from events.forms import EventCreateForm class EventListView(LoginRequiredMixin, ListView): model = Event context_object_name = "events" class EventFormView(LoginRequiredMixin, FormView): template_name = "events/event_form.html" form_class = EventCreateForm success_url = reverse_lazy("dashboard:events:home") event_form.html <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="card-body"> <div class="form-group"> <label>Title</label> {{ form.title }} </div> <div class="row"> <div class="col-sm-4"> <div class="form-group"> <label>Start Date and Time</label> {{ form.start_datetime }} </div> </div> <div class="col-sm-4"> <div class="form-group"> <label>Finish Date and Time</label> {{ form.finish_datetime }} </div> </div> <div class="col-sm-4"> <div class="form-group"> <label for="exampleInputFile">Image</label> <div class="input-group"> <div class="custom-file"> {{ … -
I cannot import summer notes in django
when i try to import summernoteModelAdmin in admin using from djangosummernote.admin import SummernoteModelAdmin it shows error Import "djangosummernote.admin" could not be resolved admin.py: from django.contrib import admin from djangosummernote.admin import SummernoteModelAdmin from .models import BlogPost class BlogPostAdmin(SummernoteModelAdmin): summernote_fields = ('content') admin.site.register(BlogPost, BlogPostAdmin) -
Dynamic link in Django always calls the first url path
In urls.py within urlpatterns I have below two lines urlspatterns = [ ... path('<slug:productSlug>', ProductView.as_view(), name = 'viewProduct'), path('<slug:boxSlug>', BoxView.as_view(), name = 'BoxView'), ... ] In my html template I have two links <a href="{% url 'viewProduct' item.productSlug %}" class="btn btn-outline-primary" tabindex="-1" role="button" aria-disabled="true">product view</a> <a href="{% url 'BoxView' item.boxSlug %}" class="btn btn-outline-primary" tabindex="-1" role="button" aria-disabled="true">Box View</a> The problem is even though I specified BoxView in the {% url 'BoxView' ... %} it keeps calling the viewProduct path. If I reverse the order of the two paths in urlPatterns then, it keeps calling the 'BoxView'. What I don't understand is it keeps calling whatever it finds first in urlPatterns. -
why pip freeze is giving error Could not generate requirement for distribution -ip 21.0?
pip freeze > requirements.txt giving an error WARNING: Could not generate requirement for distribution -ip 21.0 (c:\python39\lib\site-packages): Parse error at "'-ip==21.'": Expected W:(abcd...) How to remove this error and what the error exactly it is? following is the content of the file after running the command pip freeze > requirements.txt requirments.txt aioredis==1.3.1 asgiref==3.3.1 astroid==2.4.2 async-timeout==3.0.1 attrs==21.2.0 autobahn==21.3.1 Automat==20.2.0 beautifulsoup4==4.9.3 bs4==0.0.1 certifi==2020.12.5 cffi==1.14.5 channels==3.0.4 channels-redis==3.3.1 chardet==4.0.0 colorama==0.4.4 constantly==15.1.0 coreapi==2.3.3 coreschema==0.0.4 cryptography==3.4.7 daphne==3.0.2 defusedxml==0.7.1 Django==3.0.11 django-binary-database-files==1.0.10 django-cors-headers==3.7.0 django-render-block==0.8.1 django-templated-email==2.4.0 django-templated-mail==1.1.1 djangochannelsrestframework==0.3.0 djangorestframework==3.12.2 djangorestframework-simplejwt==4.7.1 djoser==2.1.0 hiredis==2.0.0 hyperlink==21.0.0 idna==2.10 incremental==21.3.0 isort==5.7.0 itypes==1.2.0 Jinja2==3.0.1 joblib==1.1.0 lazy-object-proxy==1.4.3 MarkupSafe==2.0.1 mccabe==0.6.1 msgpack==1.0.2 mysqlclient==2.0.3 numpy==1.21.4 oauthlib==3.1.0 pandas==1.3.4 Pillow==8.3.1 ply==3.11 psycopg2==2.8.6 psycopg2-binary==2.8.6 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.20 PyJWT==2.1.0 pylint==2.6.0 pylint-django==2.4.2 pylint-plugin-utils==0.6 pyOpenSSL==21.0.0 python-dateutil==2.8.2 python3-openid==3.2.0 pytz==2020.5 requests==2.25.1 requests-oauthlib==1.3.0 scikit-learn==1.0.1 scipy==1.7.2 service-identity==21.1.0 six==1.15.0 sklearn==0.0 social-auth-app-django==4.0.0 social-auth-core==4.1.0 soupsieve==2.1 sqlparse==0.4.1 threadpoolctl==3.0.0 toml==0.10.2 Twisted==21.7.0 twisted-iocpsupport==1.0.2 txaio==21.2.1 typing-extensions==3.10.0.2 uritemplate==3.0.1 urllib3==1.26.3 waitress==2.0.0 whitenoise==5.3.0 wrapt==1.12.1 zope.interface==5.4.0 above is the content of the file after running the command pip freeze > requirements.txt. I am new to django any help will be apreciated! -
Django tests pass locally but not on Github Actions push
My tests pass locally and in fact on Github Actions it also says "ran 8 tests" and then "OK" (and I have 8). However, the test stage fails due to a strange error in the traceback. Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 421, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: near "SCHEMA": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/runner/work/store/store/manage.py", line 22, in <module> main() File "/home/runner/work/store/store/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/core/management/commands/test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/test/runner.py", line 736, in run_tests self.teardown_databases(old_config) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django_heroku/core.py", line 41, in teardown_databases self._wipe_tables(connection) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django_heroku/core.py", line 26, in _wipe_tables cursor.execute( File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/opt/hostedtoolcache/Python/3.9.9/x64/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise … -
Django "__str__ returned non-string (type tuple)"
I've seen similar problems but still cannot solve mine. I'm making e-commerce ticket system. Here's the code. class Event(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, db_index=True) banner = models.ImageField(upload_to='banners/' ,null=True, blank=True) description = models.TextField(blank=True) address = models.CharField(max_length=255) slug = SlugField(max_length=255, blank=True) event_date_time = models.DateTimeField() price_1 = models.DecimalField(max_digits=5, decimal_places=2) pool_1 = models.IntegerField() pool_date_1 = models.DateTimeField() price_2 = models.DecimalField(max_digits=5, decimal_places=2) pool_2 = models.IntegerField() pool_date_2 = models.DateTimeField() price_3 = models.DecimalField(max_digits=5, decimal_places=2) pool_3 = models.IntegerField() def __str__(self): return ( self.id, self.name, self.banner, self.description, self.address, self.slug, self.event_date_time, self.price_1, self.pool_1, self.pool_date_1, self.price_2, self.pool_2, self.pool_date_2, self.price_3, self.pool_3 ) class Ticket(models.Model): id = models.AutoField(primary_key=True) event = models.ForeignKey(Event, related_name='ticket', on_delete=models.CASCADE) slug = SlugField(max_length=255, blank=True) date_sold = models.DateTimeField() price = models.DecimalField(max_digits=5, decimal_places=2) bought_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, related_name='buyer') promotor = models.CharField(max_length=4, blank=True) def __str__(self): return ( self.id, self.slug, self.date_sold, self.price ) I'm not sure which one of those values returns error, could someone please explain to me which value and why returns tuple? I've tried many combinations and was still not able to solve it. -
Django aggregate combine two expressions in one dict as output field
I have this code, which aggregates queryset and count amount of objects with condition: queryset = queryset.aggregate( first_win=Count( "score", filter=Q(score__first_score=5), output_field=FloatField(), ), second_win=Count( "score", filter=Q(score__second_score=5), output_field=FloatField(), ), ) And this is response format: { "first_win": 78.26086956521739, "second_win": 17.391304347826086 } I want to change it and combine two or more values in one. Can I somehow make it look like this? { "win_info": { "first_win": ... "second_win": ... } } -
Authentication failed django
I get an error password authentication failed for user "usertodoproject". Really losing my patience, so far I have done couple of new databases and used fpr example this ALTER USER todouser WITH PASSWORD 'todo'; it did not help either. Any ideas? settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'todoproject', 'USER': 'usertodoproject', 'PASSWORD': 'todoprojectpass', 'HOST': 'db', 'PORT': '5432', } } db: image: postgres environment: - POSTGRES_DB=todoproject - POSTGRES_USER=usertodoproject - POSTGRES_PASSWORD=todoprojectpass ports: - 5432:5432 -
Django Rest Framework Send Image in Email
Hello I have faced an Issue regarding sending email In django rest API. The Idea is user sends email and Uploads image from serializer part and I want to send same image to users Email. But I am not getting image in email. here is the code I have been working. models.py class Mail(BaseModel): full_name = models.CharField(max_length=100) image = models.ImageField(upload_to=mail_image_to) email = models.EmailField() below is my serializer class MailSerializer(serializers.ModelSerializer): class Meta: model = Mail fields = '__all__' class AddMailSerializer(MailSerializer): class Meta(MailSerializer.Meta): fields = ( 'full_name', 'image', 'email', ) views.py class AddMailView(generics.CreateAPIView): """ Use this endpoint to add mail """ serializer_class = serializers.AddMailSerializer def perform_create(self, serializer): return AddMailUseCase(serializer=serializer).execute() I usually write my rest of code in usecase.py class AddMailUseCase: def __init__(self, serializer): self.serializer = serializer self.data = serializer.validated_data def execute(self): self._factory() def _factory(self): self._mail = Mail(**self.data) self._mail.save() SendEmail( context={ "fullname": self.data['full_name'], 'image': self.data['image'] } ).send(to=[self.data['email']]) I am using django-templated-mail 1.1.1 to send email here is my rest of code. from templated_mail.mail import BaseEmailMessage class SendEmail(BaseEmailMessage): template_name = 'email.html' and finally my email.html {% load i18n %} {% block subject %} {% blocktrans %}Email Successfully Sent {% endblocktrans %} {% endblock subject %} {% block text_body %} {% blocktrans %}You're receiving this … -
SimpleJWT TokenObtainPairView API Precondition required
I am implementing authentication system in Django using SimpleJWT. I have done the installations, and added the urls, similar to the tutorial. But when I'm running the curl request to verify. I'm getting the 428 "Precondition required" status along with empty response. Its working when I'm testing on my local though. settings.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=30), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } Also appended 'rest_framework_simplejwt', in the INSTALLED_APPS. Can anyone help me with this? -
Django Debug Toolbar
I'm using Django But Django Debug Toolbar doesn't show on Chrome & Firefox. I have done all steps for config, that said on the official site of Django-debug-toolbar. Django Version: 3.1.4 Python Version: 3.9.0 -
Django: Registration form on modals available on multiple pages
I have the following scenario: I have a navbar available on all the pages of my website. The navbar has a button that opens a modal for registering. The modal has a form. The corresponding Django form is injected via a Context Processors (as recommended here). My problem, however, is that I don't know how to process the request (registration or login) in such a way that I don't need to have this logic repeated on every view. -
why pip freeze > requirements.txt giving error?
pip freeze > requirements.txt giving an error WARNING: Could not generate requirement for distribution -ip 21.0 (c:\python39\lib\site-packages): Parse error at "'-ip==21.'": Expected W:(abcd...) How to remove this error and what the error exactly it is? -
how to find mutual objects in 2 queries in Django
I'm doing 2 queries in Django and I need to find the objects that exist in both quires, is there a fast ORM or function for this? Here is my code : from_lines_objects = Line.objects.filter( Q(starting_station=from_station_object) | Q(end_station=from_station_object) | Q( inlinestation__in_line_station=from_station_object)).distinct() to_lines_objects = Line.objects.filter( Q(starting_station=to_station_object) | Q(end_station=to_station_object) | Q( inlinestation__in_line_station=to_station_object)).distinct() what I need to do is to create a third variable that contains only the objects that existed in both queries .. any help?