Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make datetime callable in puthon module?
from datetime import datetime, timedelta start = datetime.now() if datetime.now() - start() > timedelta(seconds=5): 'datetime.datetime' object is not callable the problem in the 'if' string. Thanks if you can help me. -
i have a rest api that has a list of question categories and im trying to render it with vue
my model looks like this models.py and it works fine when i try something like {{question.category}} but i have an "add question" vue page that has question body to add and a submit button i wanna add a list of the available categories so it can be chosen with the question. i tried something like this : <select > <option v-for="(category, index) in question.category" :key="index" > {{category.name}} </option> </select> and tried a couple of more things idk how to import the list of categories or if what im trying is wrong, what is the best way to do something like this ? thanks in advance. -
docker-compose unable to connect mysql
I see multiple solutions for this question but still I am unable to make progress hence posting this question I have react+django+mysql app and I want to deploy that into docker, but when I am trying to do my sql image is not created, it says db uses and image, skipping. but I see there was no image created for mysql (it had one but I force deleted, so it can get create new one), I tried solution given here and tried to run below command docker run mysql -h 127.0.0.1 -P 3306 but it asked me give password, root password etc, what went wrong for me? below is my logs PFb my docker-compose.yaml version: '3.2' services: db: image: mysql:8.0 ports: - '3302:3306' environment: MYSQL_DATABASE: 'motor_vehicle_collision' MYSQL_USER: 'creditshelf_user' MYSQL_PASSWORD: '12345678' MYSQL_ROOT_PASSWORD: '12345678' networks: - db-net web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/motor_vehicle_crash ports: - "5000:8000" depends_on: - db frontend: restart: always command: npm start container_name: front build: context: ../../../react code/collision-UI/collision-info dockerfile: Dockerfile ports: - "3000:3000" stdin_open: true depends_on: - web networks: - db-net networks: db-net: driver: bridge below is my python project Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN mkdir /collision_bike_info WORKDIR /collision_bike_info ADD requirements.txt /collision_bike_info/ … -
Django URL directing to wrong view
I am creating a Django application and have a couple URL'S path('survey/<url_id>/<token>/', views.take_questionnaire, name='take-survey'), path('survey/results/<url_id>/', views.view_results, name='view-results'), I am trying to access the 'view-results' url - http://127.0.0.1:8000/survey/results/lqH16jwM19Y6LLd/ - but for some reason this is triggering the 'take-survey' url. If i change the order of the urls they seem to work, but im curious as to what is causing this. I have never encountered this before, maybe i missed something when learning about django urls. Could someone explain why the first URL is getting triggered rather than the second? -
Django admin save bug
I am using Python 3.8, Django 3.1.2 with PostgreSQL 13.1 . I have a simple webapp using the django administration site for crud actions. Sometimes when i insert data with the django admin add form and click the "save" button django makes strange behaviour (i cannot see the patron that trigger this bug), adding two identical objects to database instead of one. I have been searching but cannot find the solution. This is the only code i have in save_model() function. def save_model(self, request, obj, form, change): if obj._state.adding is True: obj.username = request.user obj.date_input = datetime.datetime.now() super().save_model(request, obj, form, change) Example: If i have a simple model Book with title and author fields (django put id automatically), sometimes when i try to add a Book ('book1','author1') this bug behaviour result in: id title author 1 book1 author1 2 book1 author1 -
Django Model Formset very slow on POST
I am trying to allow users to modify multiple records in one screen, so Django Formsets seemed to be the best bet. Each form in the formset contains 9 foreign key fields which leads to running many many queries. I solved this on form rendering side by using Jquery Autocomplete for each of these, this reduced the render time from 30 or 40 seconds down to about 3 or 4 (reduced hundreds of queries down to 4). The performance problem I now have is on the POST side - it is still running hundreds of duplicate queries according to Django Debug Toolbar when the form is submitted. I have spent hours reading through formset documentation and suggestions on various blogs and here. The last thing I tried was to set the formset queryset to a custom query and with select_related() for each ForeignKey field. This does appear to make the main query include alot of joins according to DjDT but it does not eliminate the remaining hundreds of queries on POST. I've already pulled all my hair out, so maybe someone has a suggestion or can see what I've done wrong? My models: class Info(AbstractAddArchive): item= models.ForeignKey(ITEM, on_delete=models.PROTECT) rec= models.ForeignKey(Log, … -
Django API call not rendering in templates
i am making an API call to get weather, but i am not able to loop through the results in template also note that i am able to print the result in terminal Here is my code: def index(request): url = 'http://api.weatherapi.com/v1/current.json?key={}&q={}&aqi=no' api_key = 'MY_KEY' # print(response.text) cities = City.objects.all() weather_data = [] for city in cities: response = requests.get(url.format(api_key, city)).json() city_weather = { 'city': city.name, 'temperature': response['current']['temp_c'], 'description': response['current']['condition']['text'], 'icon': response['current']['condition']['icon'], } weather_data.append(city_weather) print(weather_data) context = { 'weather_data': city_weather } return render(request, 'weather_app/index.html', context) Here is my template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% for city_weather in weather_data %} {{city_weather.temperature}} {% endfor %} </body> </html> This is the result i get in terminal [{'city': 'Cairo', 'temperature': 19.0, 'description': 'Partly cloudy'}, {'city': 'Paris', 'temperature': 7.0, 'description': 'Partly cloudy'}, {'city': 'Tokyo', 'temperature': 13.8, 'description': 'Patchy rain possible'}] Not sure why i am not able to pass the result to template, is there something i am missing -
How to serve images added via user in Django in deployment
I have a Django E-commerce App on the cloud. I have configured to add products and images from admin. It was working fine in the development server but doesnt work in deployement. I cant find any good answers anywhere, google seems to be filled with resources about serving static files. Some answers are that apache would be required but i use nginx so how would that work. Help would be appreciated.. models.py class Product(models.Model): name = models.CharField(max_length=150) price = models.PositiveIntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) description = models.TextField(default='' , null=True , blank=True) image = models.ImageField(upload_to='uploads/products/') old_price = models.PositiveIntegerField(default=299) image2 = models.ImageField(upload_to='uploads/suits/', null=True, blank=True) image3 = models.ImageField(upload_to='uploads/suits/', null=True, blank=True) tags= ArrayField(models.CharField(max_length=20, blank=True, null=True)) settings.py config MEDIA_URL = "/image/download/" MEDIA_ROOT = BASE_DIR urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Check fields/fieldsets/exclude attributes of class CustomUserAdmin error in admin
I am getting this error even though I have already removed and migrated again. Initially, I added as extra boolean field is_vehicle_owner after Abstracting a Usermodel and then it was removed later. But i get this error. Any help will be appreciated. FieldError at /admin/accounts/customuser/1/change/ Unknown field(s) (is_vehicle_owner) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. Request Method: GET Request URL: http://127.0.0.1:8000/admin/accounts/customuser/1/change/ Django Version: 3.1.4 Exception Type: FieldError Exception Value: Unknown field(s) (is_vehicle_owner) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. Exception Location: C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py, line 711, in get_form Python Executable: C:\Users\DELL\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.0 Python Path: ['E:\Django\projects\carpool', 'C:\Users\DELL\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\DELL\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\DELL\AppData\Local\Programs\Python\Python39', 'C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Thu, 18 Mar 2021 18:28:58 +0000 Traceback Switch to copy-and-paste view C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py, line 709, in get_form return modelform_factory(self.model, **defaults) … ▶ Local vars C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\models.py, line 555, in modelform_factory return type(form)(class_name, (form,), form_class_attrs) … ▶ Local vars C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\models.py, line 268, in new raise FieldError(message) … ▶ Local vars During handling of the above exception (Unknown field(s) (is_vehicle_owner) specified for CustomUser), another exception occurred: C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py, line 614, in wrapper return … -
Adapter to handle requests for APIs that exists on another server
So this is the scenario: I have a server(say SERVER A), that has the following rest APIs /questionnaire/{questionnaire_id} /questionnaire/ /questionnaire/question/{question_id} questionnaire/question/ Now I have a second server(say SERVER B), that has some other APIs. Now SERVER B has a frontend(say FRONTEND B), that access both backend SERVER A and SERVER B Requirements: I do not want to directly access SERVER A from FRONTEND B, instead, I want to access backend SERVER B that will authenticate the request coming from FRONTEND B and in turn, hit backend SERVER A to get the response. Now I do not want to write a duplicate APIs on SERVER B to hit the the corresponding APIs on SERVER A. What I want is an adapter that handles all API request whose URL starts with "/questionnaire/" and authenticate the user or request and then hit the SERVER A, receive the data and return it to FRONTEND B. So is there any tool inbuilt in Django for this or if there is any workaround to make it possible? Thanks in advance. -
Django: Trouble filtering my Artist model to show objects from the request user
So I have a model in a different app that records a user's 5 favorite artists. The model is uses the user as a foreign key through my own custom userprofile model. So I want to display the list of favourite artists linked to the request profile when I log in and I want to display it. But im having trouble filtering it because I keep getting an error saying the request user needs to be a userprofile instance. Heres my music model from django.db import models from accounts.models import UserProfile # Create your models here. class Artist(models.Model): artist_name = models.CharField(default='', max_length=200) artist_name2 = models.CharField(default='', max_length=200) artist_name3 = models.CharField(default='', max_length=200) artist_name4 = models.CharField(default='', max_length=200) artist_name5 = models.CharField(default='', max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) as_pro = models.OneToOneField(UserProfile, on_delete=models.CASCADE, related_name='artist') def __str__(self): return f"{self.as_pro}-{'Artist List'}" and heres my profile view in the accounts app def profile(request): userprofile = UserProfile.objects.get(user=request.user) obj = Artist.objects.filter(as_pro=request.user) context = { 'userprofile': UserProfile, 'obj' : obj, } return render(request, 'accounts/profile.html', context) heres also my profile template where I want to display it but like I said I'm finding it hard to crack why I cant display a simple list. </div> <p>{{ obj.artist_name }}</p> <p>{{ obj.artist_name2 }}</p> <p>{{ … -
Javascript file calls another jsfile from the wrong directory
I am currently using OTree, which is a Python framework that allows to run experiment online, using Django for the web-side if I am not mistaken. Basically, it is really easy to implement things in it, except if one wants to modify a bit the HTML page, for instance, by incorporating live objects (such as video games, etc...) on the HTML page. That is my case. I am trying to implement a UNO game in my experiment. Since I virtually know next to nothing to Javascript, I am using a UNO game built in Construct 3 for all the coding. If I understood it right, to call script in Django, one needs to write as follows: <script src="{% static 'my_app/script.js' %}" alt="My script">. So this is what I did. My code for the HTML page can be found below: {% extends "global/Page.html" %} {% load otree %} {% block content %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"> <meta name="generator" content="Construct 3"> <meta name="description" content="UNO"> <link rel="manifest" href="{{ static "HTML_Uno/appmanifest.json" }}"> <link rel="apple-touch-icon" href="{{ static "HTML_Uno/icons/icon-128.png" }}"> <link rel="apple-touch-icon" href="{{ static "HTML_Uno/icons/icon-256.png" }}"> <link rel="apple-touch-icon" href="{{ static "HTML_Uno/icons/icon-512.png" }}"> <link rel="icon" type="image/png" href="{{ static "HTML_Uno/icons/icon-512.png" }}"> <link rel="stylesheet" … -
Django Reverse for 'edit' with no arguments not found
I'm new to Django. I just laid out a new project to teach myself how routing works. I have a template that works like a 'detail view' to show information about an item in my database, and that template includes a button that should allow you to 'edit' this item. Clicking the button gives me: NoReverseMatch at /4/edit Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['(?P<id>[^/]+)/edit$'] Here is the template. I am trying to call the dashboard app's 'edit' view and pass the current article's ID in as an argument. {% extends 'dashboard/components/layout.html' %} {% block content %} <div id='detail-container'> <div class='detail-sidebar'> <a href='{% url 'dashboard:edit' id=article.id %}'>Edit</a> </div> <div class='article detail-article'> <h1 class='article-title'>{{ article.article_title }}</h1> <p class='article-body'>{{ article.article_body }}</p> </div> </div> {% endblock %} Here is my urls.py file. To my understanding this should match the pattern named 'edit' from django.urls import path from . import views app_name = 'dashboard' urlpatterns = [ path('', views.index, name='index'), path('new/', views.NewPost, name='new'), path('<id>/', views.ArticleDetailView, name='article'), path('<id>/edit', views.EditArticleView, name='edit'), ] And finally, here is the view that the edit path should call. I'm aware that the logic is probably not right when it comes to rendering a form with … -
Is it possible to use multiple slash Django URL as one variable in Django?
I'm new to Django. I'm using Django for 5months. I'm now creating a project. In that project, I've links like this: https://localhost:8000/example.com/example/path/ In the URL the example.com/example/path/ can be dynamically long as like this example.com or example.com/asset/css/style.css or domain.com/core/content/auth/assets/js/vendor/jquery.js I've used <str:domainurl> But is not working. As it has multiple forward slashes. And the forward slashes URL length generated while web scrapping. So is there is a way to use the full URL as one variable? -
Query all connected ancestors or children in a self relation table
Suppose I have a table 'prlines' with a self relation on adjacent records: id | prev_id ------------ 1 | NULL 2 | NULL 3 | 1 4 | 2 5 | 3 6 | 5 I want to get all connected IDs (previous/next) of a certain record. For example: SELECT `prev_id` FROM `prlines` ... WHERE id = 5; Should produce this output: prev_id ------- 3 1 6 What I am doing currently is making a nasty while loop in Django that generates multiple queries to follow the relationship for each record. Any ideas to achieve this in a single mysql query? -
Modal not showing long messages, problem with javascript function arguments
I am facing a problem when I try to show message content in modal. I am trying to build a view which has a list of messages (table), and by clicking a message title, the user would be able to see the message content in modal view. It works for short messages, but for some reason nothing happens with longer messages. I think the issue is with my function 'displayMessage' to which I pass two elements: message title and message content. Here is the snippet from the table view: <table id="msg-table" class="table table-striped"> <thead> <tr> <th id="message-date" scope="col">Date</th> <th id="message-content" scope="col">Message</th> </tr> </thead> <tbody> {% for message in messages %} <tr> <td>{{ message.date }}</td> <td onclick="displayMessage('{{message.content,}}', '{{ message.title }}')"> {{ message.title }} </tr> <div id="myModal" class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="message-title"></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p id="message-content"></p> </div> </div> </div> </div> {% endfor %} </tbody> </table> And this is the function for displaying the Modal: function displayMessage(message, title) { var modal = document.getElementById("myModal"); var close = document.getElementsByClassName("close")[0]; // Change the modal text and display document.getElementById("message-title").innerHTML = title; document.getElementById("message-content").innerHTML = message; modal.style.display = "block"; close.onclick = function … -
dictionary update sequence element #0 has length 0; 2 is required
I was working on my project and everthing worked fine. I tried to open the server in another browser and this error appeared. I stopped the project and start it agian and it stop working on my main browser aswell. I dont have any idea what this cause it. Internal Server Error: /account/login/ Traceback (most recent call last): File "A:\repos\topanime\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "A:\repos\topanime\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "A:\repos\topanime\venv\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "A:\repos\topanime\venv\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "A:\repos\topanime\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "A:\repos\topanime\venv\lib\site-packages\django\template\base.py", line 168, in render with context.bind_template(self): File "C:\Python\Python391\lib\contextlib.py", line 117, in __enter__ return next(self.gen) File "A:\repos\topanime\venv\lib\site-packages\django\template\context.py", line 244, in bind_template updates.update(processor(self.request)) ValueError: dictionary update sequence element #0 has length 0; 2 is required [18/Mar/2021 18:52:01] "GET /account/login/ HTTP/1.1" 500 86400 If there is any other information that you need tell me. -
User Frontend Selection That Loads Images From Database With Django
I have a drop down bar with a multi selection tool. A user picks from titles of graphs stored in a model for the graphs they want to display. How can I use those selections to display these graphs? I am using Ajax to send the data to the backend. From that data I created a new context_dict full of the model objects we want displayed. I want to either display in the same template or link to another template that can use this context dict. I do not know the best way to do this. Here is some of my code below. Models: from django.db import models class ChartPrac(models.Model): title = models.CharField(max_length=256) chart = models.ImageField() def __str__(self): return self.title Views: def querier(request): if request.method == 'POST': options_arr = request.POST.get('optionsArr') options = options_arr.split(':') options = options[1:] print(options) context_arr = [] context_graphs = {} i = 0 for elements in options: charts_to_display = ChartPrac.objects.get(title=elements) context_arr.append(charts_to_display) i += 1 context_graphs['titles'] = context_arr return HttpResponse(options_arr) else: graph_titles = ChartPrac.objects.all() context_dict = {'titles': graph_titles} print(context_dict) print(type(context_dict['titles'])) return render(request, 'graph_querier/base.html', context=context_dict) Urls: from django.urls import path from graph_querier import views app_name = 'graph_querier' urlpatterns = [ path('', views.index, name='index'), path('querier/', views.querier, name='querier'), # path('graph/', views.graph, … -
Django REST API auth token ERR_CONNECTION_REFUSE
I have my django project with angular front-end running on a server, when I try to visit my website with the server it's working fine, but trying to connect remotely to the website using my computer I cant authenticate. Note that i can visit public pages fine but when I'm trying to loggin i got ERR_CONNECTION_REFUSE . PS : I'm running django with cmd : python manage.py runserver 0.0.0.0:8000/ and using my computer I can connect to the django backend office all working fine but connecting from my website ( front end ) I got the error . In my settings.py : ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True -
Get reoccurring date from rrule Django / Python
I make two requests, one to get a collection of events that have valid dates, and then an additional function to find dates within the returned valid events: def valid_data(matches, start_date, end_date): for prices in matches: if prices.rule: until = ( prices.rule.until if prices.rule.until and prices.rule.until <= end_date else end_date) dtstart = ( prices.start_date if prices.start_date >= start_date else start_date) prices_dates = price_rrule( frequency=prices.rule.frequency, interval=prices.rule.interval, byweekday=tuple(prices.rule.byweekday) or None, bymonthday=tuple(prices.rule.bymonthday) or None, until=until, dtstart=dtstart) if start_date in price_dates: return prices The response I get back in other areas of my code is fine, it'll return the event (prices) within the start - end dates, those that are occurrences inside these dates, don't come back with an actual date - how could I modify the above so I can attach dates to reoccurrence and maybe return this as a list as I only get the one item back. -
I want to make a progress bar ,but don't use celery lib. so I writ the code, it works, but have some problem
I use a variable like a global variable. I think it a bad idea when multiple users run at the same time, the progress bar is messy. who can help me improve this code, please? num_progress = 0 # This is bad idea def show_progress_page(request): # return JsonResponse(num_progress, safe=False) return render(request, 'progress.html') def process_data(request): global num_progress for i in range(12345666): # ... Some thing in progress num_progress = int(i * 100 / 12345666) # print 'num_progress=' + str(num_progress) res = num_progress # print 'i='+str(i) # print 'res----='+str(res) return JsonResponse(res, safe=False) def show_progress(request): print('show_progress----------' + str(num_progress)) return JsonResponse(num_progress, safe=False) -
How can i show friends of users in ManyToManyField
I am building a BlogApp and I am trying to access only friends in ManyToManyField. BUT it is not working for me. What i am trying to do I am trying to show only list of friends in ManyToManyField. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') friends = models.ManyToManyField("Profile",blank=True) class Video(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) add_users = models.ManyToManyField(Profile,related_name='taguser') What have i tried I also did ManyToManyField('friends)` but it didn't worked for me. I don't know what to do. Any help would be Appreiated. Thank You in Advance -
django filter two ManyToManyField equal
class VideoUserModel(models.Model): user = models.ManyToManyField(get_user_model()) viewlist = models.ManyToManyField(get_user_model(), related_name='view_list', blank=True, null=True) I want to get the queryset of user list equal viewlist. How to do this? VideoUserModel.objects.all().filter(user=**viewlist**) -
How to use selected value by a user?
I want to allow user to pick a dog food brand from a database. When he selects it, I want to use his submitted value and return him how many calories it has. I am stuck and don't know what to do next. models.py class DogFoodDry(models.Model): brand = models.CharField(max_length=25) name = models.CharField(max_length=100) calories_per_kg = models.IntegerField(null=False) forms.py class DogFoodDryForm(forms.Form): brand = forms.CharField(max_length=25) name = forms.CharField(max_length=100) calories_per_kg = forms.IntegerField() views.py def get(self, request, id): form = DogFoodDryForm() dog = Dog.objects.get(id=id) foods = DogFoodDry.objects.all() context = {'dog':dog, 'foods':foods} return render(request, 'dog_info.html', context) dog_info.html <form method="GET"> <select> <option value="">--------</option> {%for food in foods %} <option value="">{{food.brand}} | {{food.name}}</option> {%endfor%} </select> <input type="submit" value="Select"> </form> -
Q model and or query giving incorrect result
I want perform below SQL query using Q models SELECT * FROM motor_vehicle_collision.collision_data_collisiondetails where (numberOfCyclistInjured > 0 or numberOfCyclistKilled > 0) and (longitude != '' and latitude != ''); for that I have written below query query = Q(numberOfCyclistInjured__gt=0) query.add(Q(numberOfCyclistKilled__gt=0), Q.OR) query.add(~Q(latitude=''), Q.AND) query.add(~Q(longitude=''), Q.AND) but still I am getting data having latitude/longitude empty, how should I rectify it?