Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using both firebase-admin and pyrebase
I am new to dev, I am using firebase react and django in order to create my app In react, I am using firestore and firebase storage to store basic stuffs, I got to use that in my Django So I have to use both pyrebase (for firebase storage) and firebase-admin (for firestore) [ I know I can use firebase-admin to do both but it's hard to find storage details ] how do I initialize both together -
How to get auto end date based on selection of start date and no. of days of travel
I am new with Django and coding. After doing Local Library and Polls tutorial on MDN and Django respectively. I am now working on travel itinerary app. Where I want that my model should be able to take start date as enter by user and based on number of nights selected by user should auto fill the end date. Example: Start Date: 09-July-21 No. of Nights: 05 End Date: 14-July-21 Code for models.py is as follows, I will be using Postgresql DB for this project class Packages(models.Model): title_package = models.CharField(max_length=300) no_of_nights = models.SmallIntegerField() summary = models.TextField(max_length=3000) start_date = models.DateField(help_text='should not allow client to book in past') end_date = models.DateField(help_text='based on start date selection and no. of nights client is staying.') -
Django - How to implement a search box
I'm struggling to implement a search bar and could really do with a few suggestions on how it could be done. I'm quite a novice, so please bear with me. My difficulties lie more with the general understanding of what needs to be built than with a specific line of code and somehow that's making it even harder for me to find an answer. In summary, I have: Django Models: Recipe Tags (M2M with Recipe) Category (ForeignKey with Recipe) etc. I've written Graphene schemas to query the database (Postgres) by Tags, Categories and numerous Recipe attributes (e.g.: Recipe name). You can filter the recipes displayed on the frontend with those queries, by clicking on e.g. a certain category name. What I'd however also like to have, is a search box where a user can enter a keyword of their choice on the frontend, and get back all the recipes that have something matching that keyword. I don't know what or how to build something like that. To my novice mind, it seems like a search box of that sort would essentially be a query where I don't know what the filter is in advance, i.e. "fresh" as an input could … -
I newly start django and launc server once but now its now working and showing me following errors. my all settings are default
PS C:\Users\Prem\Desktop\demo> django-admin runserver manage.py Traceback (most recent call last): File "c:\users\prem\appdata\local\programs\python\python39\lib\runpy.py", line 197, in run_module_as_main return run_code(code, main_globals, None, File "c:\users\prem\appdata\local\programs\python\python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\Prem\AppData\Local\Programs\Python\Python39\Scripts\django-admin.exe_main.py", line 7, in File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\core\management_init.py", line 419, in execute_from_command_line utility.execute() File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\core\management_init.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\conf_init_.py", line 82, in getattr self.setup(name) File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\conf_init.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Template data not passing into Django view.py
Create account form We are trying to get the name, email-ID and password through post method in the form, we get the data as none instead of the data filled in the form. view.py from django.http import HttpResponse # Create your views here. def sign_up_in(response): email = response.POST.get('eemail') #Getting the data of email by the name of eemail print(email) #Trying to print the email that we got from the form return render(response, "main/sign_up_in.html",{}) HTML code There are two forms and we are trying to get the data from the first form. The first form is for creating the account and the second is for signing in. <h2 class="form_title title">Create Account</h2> <div class="form__icons"><img class="form__icon" src="svg_data" alt=""><img class="form__icon" src="svg_data"><img class="form__icon" src="svg_data"></div><span class="form__span">or use email for registration</span> <input class="form__input" type="text" placeholder="Name" name="eemail"> <input class="form__input" type="text" placeholder="Email"> <input class="form__input" type="password" placeholder="Password"> <button class="form__button button submit">SIGN UP</button> </form> <form method="POST" class="form" id="b-form" action=""> <h2 class="form_title title">Sign in to Website</h2> <div class="form__icons"><img class="form__icon" src="svg_data" alt=""><img class="form__icon" src="svg_data"><img class="form__icon" src="svg_data"></div><span class="form__span">or use your email account</span> <input class="form__input" type="text" placeholder="Email" name="eemail"> <input class="form__input" type="password" placeholder="Password"><a class="form__link">Forgot your password?</a> <button class="form__button button submit">SIGN IN</button> </form> url.py from . import views urlpatterns = [ path("", views.Home, name = "Homes"), path("sign/", … -
Assigning multiple leads to users and changing the category in django
Hey guys im trying to make a function in django for assigning multiple leads to an user or changing the lead category using FormView and AJAX. What im trying to do is from the datatable select all paginated rows and below have the form to submit. HERE IS MY CODE: forms.py class AssignForm(forms.Form): user = forms.ModelChoiceField(queryset=User.objects.none()) category = forms.ModelChoiceField(queryset=Category.objects.none()) def __init__(self, *args, **kwargs): request = kwargs.pop("request") users = User.objects.all() categories = Category.objects.all() super(AssignForm, self).__init__(*args, **kwargs) self.fields["user"].queryset = users self.fields["category"].queryset = categories views.py: class LeadAssignView(LoginRequiredMixin, generic.FormView): form_class = AssignForm template_name = "leads/lead_assign.html" def get_form_kwargs(self, **kwargs): kwargs = super(LeadAssignView, self).get_form_kwargs(**kwargs) kwargs.update({ "request":self.request }) return kwargs def get_context_data(self, **kwargs): context = super(LeadAssignView, self).get_context_data(**kwargs) context['leads'] = Lead.objects.all() return context def form_valid(self, form, request): user = form.cleaned_data["user"] category = form.cleaned_data["category"] if request.method == "POST": lead_ids = request.POST.getlist('id[]') for id in lead_ids: lead = Lead.objects.get(id=self.kwargs["pk"]) lead.user = user lead.category = category lead.save() return super(LeadAssignView, self).form_valid(form) And here is how i get the selected data from te datatable in the template ('leads/lead_assign.html'): <table id="misen" class="table table-bordered nowrap table-sm" cellspacing="0" style="width:100%"> <thead class="thead-dark"> <tr> <th class="text-center">#</th> <th class="text-center"><input type="checkbox" name="" id="site_select_all"></th> <th class="text-center">Name</th> <th class="text-center">Phone</th> <th class="text-center">Data Creation</th> <th class="text-center">Source</th> <th class="text-center">Category</th> <th class="text-center">User</th> <th class="text-center">Action</th> </tr> </thead> … -
Nginx static files 404 with django swagger rest api
I have Django rest API application and swagger for that is working fine locally. I am trying to configure it using containers and deploy it on ECS. Now when I build and run the container the application works fine (I mean the swagger UI is appearing). When I attach the application load balancer to it, on the browser it is giving me 404 files not found for js and CSS files. Here is the console output from the web browser. Here is my Nginx config file # nginx.default add_header X-Content-Type-Options nosniff; include /etc/nginx/mime.types; add_header X-XSS-Protection "1; mode=block"; server { listen 8020; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location / { proxy_pass http://127.0.0.1:8010; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static { root /home/app/codebase; } } THe path of static folder inside docker container is /home/app/codebase/static/ Also added the following lines in the Django Settings.py file. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') Not sure what am I missing. Any leads will be appreciated. I have looked into these questions. The problem is something similar but not sure what I'm missing. -
How to display the CommentForm in my django template?
I am trying to display the CommentForm on Django template but it just wont display. I have a ViewBased Form class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = PostForNewsFeed fields = ['description', 'pic', 'tags'] template_name = 'feed/create_post.html' def form_valid(self, form, request,pk): post = get_object_or_404(PostForNewsFeed, pk=pk) if request.method == 'POST': if form.is_valid(): data = form.save(commit=False) data.post = post data.username = request.user data.save() form = NewCommentForm() return redirect('post-detail', pk=pk) else: form = NewCommentForm() return render(request,'feed/post_detail.html', {'form':form}) <div class="row"> <div class="col-md-8"> <div class="card card-signin my-5"> <div class="card-body"> <form class="form-signin" method="POST" id="post-form"> {% csrf_token %} <fieldset class="form-group"> <br /> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit" > Comment</button ><br /> </div> </form> </div> </div> </div> </div> The CommentForm Doesnt get displayed. -
Match and subtract QuerySet with dict in django
I have two variables containing the following output: city_sum_added: <QuerySet [{'city': '8000', 'cinnamon__sum': None, 'peber__sum': Decimal('240.00')}, {'city': '9000', 'cinnamon__sum': Decimal('250.00'), 'peber__sum': None}, {'city': '9800', 'cinnamon__sum': Decimal('500.00'), 'peber__sum': None}]> our_total: {'Hovedlager': [Decimal('3167.50'), Decimal('752.50')], 'Odense': [Decimal('177.50'), Decimal('10.00')], 'Holstebro': [Decimal('52.50'), Decimal('12.50')], 'Hjørring': [Decimal('57.50'), 0], 'Rødekro': [Decimal('325.00'), Decimal('70.00')], 'Esbjerg': [Decimal('125.00'), Decimal('30.00')], 'Århus': [Decimal('492.50'), Decimal('20.00')], 'København': [Decimal('45.00'), 0], 'Ålborg': [Decimal('380.00'), Decimal('102.50')]} In city_sum_added we see the city number (zip code) and then amount of cinnamon and peber in decimals. In our_total we see the city name and then two decimals being cinnamon and peber too (starting with cinnamon) I now wanna take my our_total and match the city with the one from city_sum_added before I subtract the amount of cinnamon and peber in our_total with the amount in city_sum_added. The names and numbers of the cities comes from this model, where you see what numbers belongs to what city when they are going to be matched: class InventoryStatus(models.Model): CITIES = [ ('9800', 'Hjørring'), ('9000', 'Ålborg'), ('7500', 'Holstebro'), ('8000', 'Århus'), ('6700', 'Esbjerg'), ('6230', 'Rødekro'), ('5220', 'Odense'), ('2300', 'København'), ('4682', 'Hovedlageret'), ] cinnamon = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) peber = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) city = models.CharField(max_length=4, choices=CITIES) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) is_deleted = … -
When I try to happen to the second URL I created it says "Page not found" and "calls it" 3. ^ (? P <path>. *) $
It does not show me the url created. When I try to go to the localhost it tells me: admin / Bag/ ^ (? P . *) $ The created URL calls it ^ (? P . *) $. How can I do? urls.py from django.urls import path from . import views urlpatterns = [ path('', views.Borsa), path('Investimenti', views.Investimenti) ] urls.py (project) from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('Borsa/', include('Borsa.urls')), ]+static(settings.MEDIA_URL, document_root =settings.MEDIA_ROOT) views.py from django.shortcuts import render from .models import Aziende def Borsa(request): Borsa = Aziende.objects.all() return render(request, 'Borsa/Home.html', {'Borsa': Borsa},) def Investimenti(request): return render(request, 'Borsa/Investimenti.html') Thanks in advance! -
Filter list of objects, check if exists
I have a local database which contains objects and a remote one that should have the same values. I check for any differences every time someone refreshes certain page. I am loading remote dataset into list of objects. I am stuck at checking if someone deleted object from remote location. Deleting local one is fairly simple. for row in cursor_from_pyodbc: w = LzWidlak(some_id=row[0], another_value=row[1]) remote_objects.append(w) for remote_object in remote_objects: if MyModel.objects.filter(some_id=remote_object.some_id).exists(): ... I have no idea how to do it the other way around. It seems like there is no filter function on my list of objects? for local_object in MyModel.objects.all(): if remote_objects.filter(some_id=local_object.some_id).exists(): ... It throws: Exception Value: 'list' object has no attribute 'filter' I feel there is a simple way to do that but don't know what it is. -
Django timeout before submitting background task
I maintain a Django app hosted on Heroku. We use DRF intensively to serve our FE app. Django version: 2.2.21. Celery version: 4.2.2 We have an endpoint that works perfectly well 99% of the time, but sometimes, it timeouts. We use Sentry to monitor and you can find the traces here. FYI but maybe it is not useful, this endpoint: Has very little processing then starts a background task. In the breadcrumb of Sentry, we can see that the REDIS LPUSH command is triggered at the very end of the 20s heroku timeout. It is happening only in production and not staging and we cannot reproduce it It seems to me that the function calls is going back and forth between django/core/handlers/exception.py in inner at line 34 django/utils/deprecation.py in __call__ at line 94 This has been happening for months now and we still do not have a solution. Any idea as to why this might happen? And why only in certain cases? Thank you very much for the help! Robin Bonnin -
Django: Toggle Logged in users
Here, in this project, I want to show toggle green when admin is logged in and others user's toggle red as well as when other user is logged in,their toggle must be in green color and other remaining in red color. This is my template. <table class="table table-hover text-nowrap" id="rooms"> <thead> <tr> <th>SN</th> <th>Users</th> <th>Email</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> {% for user in object_list %} <tr> <td>{{forloop.counter}}</td> <td>{{user.username }}</td> <td>{{user.email}}</td> <td> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </td> <td> <span ><a class="btn btn-info mr-2" href="{% url 'dashboard:passwordreset' %}" ><i class="fa fa-edit m-1" aria-hidden="true" ></i>Reset Password</a ></span> </td> </tr> {% endfor %} </tbody> </table> When admin is logged in the toggle of admin must be in green color and whereasee other users toggle must be in red color, same as when other users are logged in their toggle must be in green color. This is my views class UsersListView(SuperAdminRequiredMixin, AdminRequiredMixin, ListView): template_name = 'dashboard/users/userlist.html' login_url = '/login/' redirect_field_name = 'user_list' paginate_by = 5 def get_queryset(self): return User.objects.all() -
Send data to multiple websocket connection in django channels
I am working on a chat app and want to know if there is a way to send data to multiple websocket connections from one websocket connection -
Django forms save override
override save method in a form, I have an image that needs to be saved in a different database, but the rest of the fields should go to the default one, also I should store the image id in the default database class TbUserRegisterForm(CustomUserCreationForm): email = forms.EmailField() image = forms.ImageField() class Meta: model = TbUser fields = ['username', 'image', 'email', 'sex', 'role', 'department', 'password1', 'password2'] -
{% request.user ==" "%} Checking User and rendering html element with if else Django Templatetag
Html code: {% if request.user== "Sangam" %} <li class=""> <a class="text-left " href="landscapes.html" role="button" aria-haspopup="true" aria-expanded="false"><i class="flaticon-bar-chart-1"></i> Landscape </a> </li> {% endif %} {% if request.user == "Sam" %} <li class=""> <a class="text-left " href="characters.html" role="button" aria-haspopup="true" aria-expanded="false"><i class="flaticon-bar-chart-1"></i> Characters </a> </li> {% endif %} I want to do is if the user is Sangam then render a certain html element for him only. But,It doesn't render so. Can I do this?.Also,I wonder how can we render certain html elements to users that we have list him/her to a certain Group in Django-admin panel -
Geojson data shifts when using leaflet Ajax
Am using django and data in my backend seems so accurate when I overlay on Leaflet openstreetmap, when I try to load to my template the geojson data shifts. This is my django admin view. for my template this is what I get. need help to finalize my project -
Custom Error Response on Invalid Credentials [RestFramework_JWT]
I am using restframework_jwt in django. I want to return a custom error response on invalid login credentials. Right now, I am getting this: { "non_field_errors": [ "Unable to log in with provided credentials." ] } I want to return a custom JSON response like this: { "success":false, "message":"Invalid Credentials", "code":401, "data":[] } Kindly help me in this. -
Global search query params based on user role
##I'm getting this error how to solve this one For the global search filter based on user role I have made this function what I have done wrong anyone can suggest me or guide me to get APIs. Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'django.db.models.query.QuerySet'> class SearchView(APIView): def get(self, request): user = self.request.user data = {} q = request.GET.get('q','') customer_obj = Customer.objects.filter(Q(customer__icontains=q) | Q(country__icontains=q) | Q (industry__industry__icontains=q) | Q(location__icontains=q) | Q(outcome__icontains=q) | Q(contact_person__icontains=q)) data['customers'] = CustomerSerializer(customer_obj, many=True, context={'request': request}).data if user.groups.name in ['CEO', 'Admin']: return Customer.objects.all() elif user.groups.name == 'Manager': return Customer.objects.filter( Q(created_by=user) | Q(created_by__reports_to=user) ) else: return Customer.objects.filter(assigned_to=user) events_obj = Event.objects.filter(Q(status_type__icontains=q) | Q(customer_name__customer__icontains=q) | Q(activity_type__icontains=q) | Q(priority_type__icontains=q) | Q(visibility_type__icontains=q) | Q(organization_type__icontains=q) |Q(contact_name__icontains=q) | Q(location__icontains=q) | Q(subject__icontains=q)) data['events'] = EventSerializer(events_obj, many=True, context={'request': request}).data if user.groups.name in ['CEO', 'Admin']: return Event.objects.all() elif user.groups.name == 'Manager': return Event.objects.filter( Q(created_by=user) | Q(created_by__reports_to=user) ) else: return Event.objects.filter(assigned_to=user) inquiry_obj = Newinquiry.objects.filter(Q(customername__icontains=q) | Q(types__icontains=q) | Q(region__icontains=q) |Q(owner__icontains=q) | Q(irr_no__icontains=q) | Q(contactperson__icontains=q) | Q(targetdate__icontains=q) | Q(briefinquirydescription__icontains=q)) data['inquirys'] = NewinquirySerializer(inquiry_obj, many=True, context={'request': request}).data if user.groups.name in ['CEO', 'Admin']: return Newinquiry.objects.all() elif user.groups.name == 'Manager': return Newinquiry.objects.filter( Q(created_by=user) | Q(created_by__reports_to=user) ) else: return Newinquiry.objects.filter(assigned_to=user) customer_po_obj = PoDetail.objects.filter(Q(customer_name__customer__icontains=q) | Q(region__icontains=q) … -
Make sure all list items based on fields exists in table efficiently
I have a model like this: class MyModel(models.Mode): foo = models.CharField(...) bar = models.CharField(...) and I have a list contains foo and bar field values. I want to check all of items in this list, exists in the database. For example: my_list = [{'foo': 'foo_1','bar': 'bar_1'}, {'foo': 'foo_2','bar': 'bar_2'}] I want to check all records exists values corresponding to the list items fields in the database. I can change my list structure. I can do it with for loop but I want to find more efficient way. Is it possible with single query?. Is there any suggestion? -
Django user.save() method
I am working on two legacy databases, the mysql stores all data and mongodb stores just images. I want to implement a method such that when the user saves the form, that has data and an image - the data should be stored in mysql which it does right now, and an image to the mongodb. The mysql stores a reference id to the image that is stored in the mongodb so I need to generate one for mysql. Since storing image in mongodb requires some additional work because it is stored in chunks in my case { "contentType": "png", "md5": "20481950baf03b7f467f824739eb68c4", "chunks": [ { "data": { "$binary": { "base64": "binarydata", "subType": "00" } } }, { "data": { "$binary": { "base64": "binarydata", "subType": "00" } } } ] } ] So I need to convert the image to base64 and so on, therefore I want to have something like a method on save that will create an uuid for mysql image id, and after that to use this uuid to send it with the processed image to the mongodb Here is my user model class TbUser(AbstractBaseUser, PermissionsMixin): id = models.CharField(primary_key=True, max_length=32, default=uuid.uuid4) username = models.CharField( max_length=40, blank=True, null=True, unique=True, … -
"The request's session was deleted before the request completed. The user may have logged out in a concurrent request"
"The request's session was deleted before the request completed. The user may have logged out in a concurrent request" I am facing this error when trying to use 2 request.session(). In my code my using two request.session() to store variables.After one request successfully completed,its going to another request and throwing this error. request.session['dataset1'] = dataset1.to_json() request.session['total_cols'] = total_cols // getting error here Please help to resolve the same. -
Invalid HTTP_HOST header even if set properly in settings.py
I am getting this error if I access it, DisallowedHost at /accounts/login Invalid HTTP_HOST header: 'galentichrms.tk'. You may need to add 'galentichrms.tk' to ALLOWED_HOSTS. I know what this means & I have properly set the galentichrms.tk in my settings.py like this, ALLOWED_HOSTS = ['galentichrms.tk', '45.93.100.82',] It was working till friday but today getting this error. I have tried to set '*' in the ALLOWED_HOSTS but still getting the same error.I am using nginx+gunicorn for the server. Any help would be appreciated.Please let me know if you need more details. -
How to save polygon data on Elasticsearch through Django GeoShapeField inside NestedField?
The models looks like - class Restaurant(models.Model): zones = JSONField(default=dict) The document looks like- @registry.register_document class RestaurantDocument(Document): zone = fields.NestedField(properties={"slug": fields.KeywordField(), "polygon_zone": fields.GeoShapeField()}) class Index: name = 'restaurant_data' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = Restaurant def prepare_zone(self, instance): return instance.zone After indexing the mapping looks like- "zone": { "type": "nested", "properties": { "polygon_zone": { "type": "geo_shape" }, "slug": { "type": "keyword" } } } But when I am saving data on zones field by following structure- [{"slug":"dhaka","ploygon_zone":{"type":"polygon","coordinates":[[[89.84207153320312,24.02827811169503],[89.78233337402344,23.93040645231774],[89.82833862304688,23.78722976367578],[90.02197265625,23.801051951752406],[90.11329650878905,23.872024546162947],[90.11672973632812,24.00883517846163],[89.84207153320312,24.02827811169503]]]}}] Then the elasticsearch mapping has been changed automatically by the following way- "zone": { "type": "nested", "properties": { "ploygon_zone": { "properties": { "coordinates": { "type": "float" }, "type": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } } } }, "polygon_zone": { "type": "geo_shape" }, "slug": { "type": "keyword" } } } That's why when I try to search on zone__polygon_zone field, it always returns empty because its not polygon type data. So, how can I save polygon data on elasticsearch trough django by nested geoshape field? -
How to get an a value for an particular record only (by ignoring filter condition ) in django ORM
For the the below model, class Comments(models.Model) comment_text= models.CharField(max_length=1000) type = models.CharField(max_length=5) date = models.DateTimeField(default=timezone.now()) In my views, I am getting the latest comments with text>125 . now If the comment type is "System", I have to display those comments by ignoring the filter condition (even though they are less than 125 chars) with regulars comments properly sorted by latest how to achieve it ? In short the filter condition shouldn't apply on comments of type 'System' (but should apply on all other comments)and it should should appear in the results with all other comments in the sorted order. comments=Comments.objects.filter(comment_text__length__gte=125).order_by("-date")