Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSS Not Loading for Browsable APIs in Django with DRF Despite Whitenoise
I am working on a Django project utilizing Django Rest Framework for APIs. I've encountered an issue where the CSS is not loading for the browsable APIs. I am using Whitenoise to serve static files, but the problem persists. Here’s the relevant part of my settings.py: STATIC_LOCATION = "assets/" MEDIA_LOCATION = "media/" STATICFILES_DIRS = [ BASE_DIR / "assets", ] STATIC_ROOT: str = "static" MEDIA_ROOT: str = "media" STATIC_URL = "/assets/" MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", #... ] STORAGES = { "staticfiles": { "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage", }, } My custom css and js are stored in assets dictory and i want to store correct static files in static dir. I've followed the standard configuration for Whitenoise, but its rendering a blank page without html and css for the DRF browsable API. I have also tried without whitenoise, and it is serving html file without statics(css and js). Any suggestions or guidance on what might be going wrong or what else I should check would be greatly appreciated! -
FAQ FUNCTIONALITY implement into blog section
Please guide me how we implement question & answer based FAQ series as per our different blog. each blog have different FAQ. How admin can add multiple FAQ as per requirement. how this functionality update the database dynamically... admin and frontend logic or provide guidance -
anymail with django framework setting the cc in the email message is not working
I am using Django+Anymail to send email notifications via mandril but if I try to add cc in the email message then that gets converted to to message and you won't see the cc details in your email client. -
How to add the evey objects to Many-to-Many relationship model
class MyUserGroup(BaseModel): my_user_types = m.ManyToManyField('MyUserType',blank=True) I have this models which has the many-to-many relation ship to type. Now I want to give the every MyUserType objects to this model such as muy = MyUserType() muy.save() muy.my_user_types.add(MyUserType.objects.all()) However this shows the error like this, TypeError: Field 'id' expected a number but got <SafeDeleteQueryset [<MyUserType:A>, <MyUserType: B>, <MyUserType: C>]>. How can I make this? -
How can I filter, search, and sort fields from a GenericForeignKey that have a GenericRelation in Django?
I have a Django model, AssetAssociation, which contains a GenericForeignKey to various models (Assets, User, Locations). The AssetAssociation model looks like this: from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey class AssetAssociation(models.Model): asset = models.ForeignKey(Assets, on_delete=models.CASCADE, related_name='asset_association') target_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) target_id = models.UUIDField() target_object = GenericForeignKey('target_type', 'target_id') # User / Asset / Location checkout_date = models.DateField(null=True, blank=True) expected_checkin_date = models.DateField(null=True, blank=True) checkin_date = models.DateField(null=True, blank=True) action_type = models.CharField(max_length=50, choices=ASSOCIATION_ACTION_TYPE_CHOICES) And here are the related models: from django.contrib.contenttypes.fields import GenericRelation class Assets(models.Model): name = models.CharField(max_length=100, blank=True, null=True) asset_tag = models.CharField(max_length=255) asset_associations = GenericRelation('AssetAssociation', content_type_field='target_type', object_id_field='target_id') class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) asset_associations = GenericRelation('AssetAssociation', content_type_field='target_type', object_id_field='target_id') class Locations(models.Model): name = models.CharField(max_length=100) asset_associations = GenericRelation('AssetAssociation', content_type_field='target_type', object_id_field='target_id') How can I effectively filter and sort on these fields using Django's ORM? Specifically, how do I write a filter function that allows filtering on these fields by using the GenericRelation? -
Django template does not inherit tag from parent
I would like to get a clarification of the following. Is it necessary to add the {% load static %} tag on every child template in my project? So far I have not been able to get my child templates to inherit this tag from their parents. However, the book I read states the following "We need to add the static files to our templates by adding {% load static %} to the top of base.html. Because our other templates inherit from base.html, we only have to add this once." This appears not be true from my experience. thanks for you help. -
How to get current user in save method of a django model?
I have the following django model: class Listing(models.Model): STATUS_CHOICES = [ ('available', 'Available'), ('rented', 'Rented'), ('unavailable', 'Unavailable'), ('fake', 'Fake'), ] id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) description = models.TextField() status = models.CharField(max_length=12, choices=STATUS_CHOICES, default='available') def save(self, *args, **kwargs): ## if self.status == 'fake' and ......: raise PermissionDenied("Cannot save listing with 'fake' status for non-admin users.") super().save(*args, **kwargs) I wander how I can get the current authenticated user to see if that user is superuser then they can set the status to fake, others cannot. I I try to see what is in args and kwargs. But they are empty -
Unable to Get Redis Working with Django on Windows
I'm working on a Django Channels project that requires Redis as the channel_layer. However, I've discovered that Redis is not natively supported on Windows, as it's primarily designed for Linux environments. While I understand that I can use Docker or a Virtual Machine to run Redis on Windows, I'm looking for an alternative solution that allows me to use Redis without relying on Docker or any Virtual Machine. Is there any way to set up Redis on Windows that avoids these options? Any guidance or suggestions would be greatly appreciated. -
Server Error (500) and strange symbols inside a form
I set up a Raspberry Pi with Ubuntu server as OS. I followed this guide: Guide from digitalocean It all seemed to work good until I opened a page with a form that looks some kind of strange (unwanted brackets before and after "Name:": The code behind looks like this: # models.py class Category(models.Model): name = models.CharField(max_length=50) def __str__(self) -> str: return self.name # forms.py class CategoryForm(forms.ModelForm): class Meta: fields="__all__" model = Category widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}) } # views.py def categories(request: HttpRequest): if request.method == 'POST': filledForm = CategoryForm(data=request.POST) if filledForm.is_valid(): newCategory = filledForm newCategory.save() categoryForm = CategoryForm() categories = Category.objects.order_by('name') args = { 'categoryForm': categoryForm, 'categories': categories, } return render(request, 'categories.html', args) And the HTML code: <div class="container"> <h2>Categories</h2> <br> <form action="{% url 'categories' %}" method="post"> {% csrf_token %} {{ categoryForm }} <input type="submit" class="form-control btn-secondary" name="submit-new-category" value="Add"> </form> <br> <table class="table table-hover"> <tbody> {% for category in categories %} <tr> <td> <a href="{% url 'category_edit' category.id %}"> <div> {{ category.name }} </div> </a> </td> </tr> {% endfor %} </tbody> </table> </div> When I try to post a filled Category-Form, Apache answers with a Server Error (500). I checked the log file (/var/log/apache2/error.log), but there is … -
Class Based View for User Registraion using Django
Which Class Based View is perfect for User Registration ? from django.views.generic.edit import FormView or from django.views import View Is there any other Class Based View for User Registration ? -
TypeError: Object of type CartItem is not JSON serializable
I've a view class which stores the list of cartItem object in the session: View class: class AddCart(View): def post(self, *args, **kwargs): prod_id = self.request.POST.get('prod-id') product = Product.objects.get(pk=prod_id) quantity = int(self.request.POST.get('quantity')) cart = self.request.session.get('CART_ID') if cart is None: cart = Cart(self.request) cartItem = CartItem(product_id=prod_id, name=product.name, quantity=quantity, image=product.image, totalprice=float(product.price) * quantity, unitprice=product.price) cart.update(cartItem) print("Cart updated in View") # del self.request.session[settings.CART_ID] return JsonResponse({'status': 'Added to cart'}) Cart class looks like: class Cart(object): def __init__(self, request): # def __init__(self): self.session = request.session cart_id = settings.CART_ID cart = request.session.get(cart_id) self.cart = cart if cart else [] # self.cart = [] def update(self, cartItem): cartList = self.cart print("cart list",cartList, "cartItem:",cartItem) found = False totalquantity = 0 for cart in cartList: if cart.product_id == cartItem.product_id: found = True totalquantity = cart.quantity + cartItem.quantity cartList.remove(cart) if not found: cartList.append(cartItem) else: newItem = CartItem(product_id=cartItem.product_id,name=cartItem.name,image=cartItem.image,quantity=totalquantity,unitprice=cartItem.unitprice,totalprice=totalquantity*cartItem.unitprice) cartList.append(newItem) self.cart = cartList self.session[settings.CART_ID] = cartList def __len__(self): return len(self.cart) CartItem class looks like: class CartItem(object): def __init__(self, product_id, name, image, quantity, unitprice, totalprice): self.product_id = product_id self.name = name self.image = image self.quantity = quantity self.unitprice = unitprice self.totalprice = totalprice def __str__(self): return f"{self.product_id}-{self.name}-{self.image}-{self.quantity}-{self.unitprice}-{self.totalprice}" But when post method of AddCart view called get below error: Last few lines of stack Trace: … -
How to filter a query in Django for week_day using a specific timezone?
I am trying to filter data by the day of the week. That's easy enough with the week_day filter. The problem is, since all dates are stored as UTC, that is how it's filtered. How can I localize a query? For instance, trying to count all the records that have been created on specific days, I use this: chart_data = [ data.filter(created__week_day=1).count(), # Sunday data.filter(created__week_day=2).count(), # Monday data.filter(created__week_day=3).count(), # Tuesday data.filter(created__week_day=4).count(), # Wednesday data.filter(created__week_day=5).count(), # Thursday data.filter(created__week_day=6).count(), # Friday data.filter(created__week_day=7).count(), # Saturday ] How can I get these queries to count those records localized to the 'America/New_York' timezone, for instance? -
Postbuild command in elastic beanstalk doesn't work but command works when ssh into EC2 instance
In my current setup, I have a django backend running in Elastic Beanstalk and a private RDS instance using mysql engine. When I deploy, I want to migrate any migrations that haven't been migrated yet. This is the config file in my .ebextensions: container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 /var/app/current/python/manage.py migrate --noinput" leader_only: true This deploys successfully, but when I check the logs it gives me this output: [INFO] Command 01_migrate [INFO] -----------------------Command Output----------------------- [INFO] Operations to perform: [INFO] Apply all migrations: admin, app, auth, contenttypes, sessions [INFO] Running migrations: [INFO] No migrations to apply. It says no migrations to apply when there are migrations that haven't been applied yet. I ran the same exact command after I ssh into the EC2 instance for my EB application and it applied the migrations successfully. I can't troubleshoot what the problem may be. -
Auto-fill form fields in clean() method
I use model form for editing records in DB. I have some business logic for auto-fill attributes, which should happen after passing validation of some business rules. In some cases, that auto-fill is based both on instance initial attributes values and current form fields values. For example, different rules apply whether it was a change of some attribute or not. Note: I have no such cases when auto-fill based on other models except one that model form based on. So my question: Is it correct to auto-fill attributes in form clean() method? After reading a few various sources, I'm not sure I fully understood if it's acceptable and if it is, in what cases. A few words why it's not convenient for me to separate validation and auto-fill: My case is that I have quite complex validation rules and almost every time these rules passed, I need to do some auto-filling. For now I have 2 methods, one in form clean() method for validation, and one in form save() method for auto-filling. Every time I need to change business rules, I should make changes in both these methods. It's not very convenient and besides that can lead to slowing down … -
Django: Templates template not found when attempting to access function rendering template
I have a file structure: Resilience_Radar_R2 Leadership_Questions_App Leadership_Questions templates questions.html I have defined a function, riskindex, that should render questions.html and include some text on the page. I also have an index function that simply sends an HttpResponse if teh request is blank The index function works fine at http://127.0.0.1:8000/Leadership_Questions_App/ but the riskindex at http://127.0.0.1:8000/Leadership_Questions_App/riskindex returns an error: TemplateDoesNotExist at /Leadership_Questions_App/riskindex/ Leadership_Questions/questions.html Request Method: GET Request URL: http://127.0.0.1:8000/Leadership_Questions_App/riskindex/ Django Version: 5.0.7 Exception Type: TemplateDoesNotExist Exception Value: Leadership_Questions/questions.html Exception Location: /Users/xxx/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages/django/template/loader.py, line 19, in get_template Raised during: Leadership_Questions_App.views.riskindex Python Executable: /Users/xxx/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/bin/python Python Version: 3.12.3 Python Path: ['/Users/xxx/Documents/Work/Python ' 'Projects/Dashboard/Reslience_Radar_R2', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python312.zip', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/lib-dynload', '/Users/xxx/Documents/Work/Python ' 'Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages'] Server time: Sat, 10 Aug 2024 19:44:06 +0000 Terminal directory is: (.venv) (base) xxx@MacBook-Pro Reslience_Radar_R2 % It appears to be looking in different directory than the one where the python code resides. Reslience_Radar_R2 urls.py rom django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('Leadership_Questions_App/', include("Leadership_Questions_App.urls")) ] Leadership_Questions_App urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("riskindex/", views.riskindex, name="riskindex"), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Leadership Questions") def riskindex(request): description = … -
Why is it possible to create a model with a ManyToManyField without providing a value for the ManyToManyField?
As every field in django model is required. So how when creating an object of model which is having a field with many to many relationship to another model. We can create this model object without specifying many-to-many field value ? -
Cant serve static files in Django but serving from media
Django is v5.1 Have this settings.py: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This urls.py: urlpatterns = [ path('graphql', include('api.urls')), path('mdeditor/', include('mdeditor.urls')), path('admin/', admin.site.urls), path('', RedirectView.as_view(url=reverse_lazy('admin:index'))), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This overridden admin/base.html: {% extends 'admin/base.html' %} {% load static %} {% block extrahead %} <link rel="shortcut icon" href="{% static 'favicon.ico' %}" /> {% endblock %} This structure: And it's not serve static files from static folder. Just shows 404. But serving static files from media folder. I have absolutely no idea where the error can be found here. -
Import could not be resolved by any source; ModuleNotFound
I cannot make migrations due to the issue stated in the title. All of the files shown in explorer have the same issue. I didn't notice the issue until I went to make migrations for polls and returned the error: ModuleNotFoundError: No module name 'polls.apps.PollsConfigdjango'; polls.apps is not a package I am doing the basic Django tutorial and this is the only issue I have had so far. I tried changing polls.apps.PollsConfig in the installed apps section to have django at the end (as it is shown in the console error). I tried changing polls\apps.py to 'from mysite.apps' which shows the same error, as well as 'from polls.apps' which shows a circular error. I did this to see if VSCode would remove the underline showing there was no longer an error. 'from polls.apps' did remove the underline, however when making the migration it showed a circular error in powershell. I'm figuring on this being a simple beginner error and am hoping someone will know what the issue is at a glance. It wouldn't bother me at all to start this over and do it again but since I clearly made an error and therefor likely didn't understand something it would … -
Django Rest Framework - testing serializers vs testing views
I'm writing a new Django app with Django Rest Framework and trying to use TDD as much as I can but I'm a bit unsure as to where to draw the line between testing the serializer and testing the view. Let me give you an example. If I have the following serializer:- class EventMembershipSerializer(serializers.ModelSerializer): select = serializers.BooleanField(required=False) class Meta: fields = ['event'] def validate(self, attrs): if not attrs["event"].started: if "is_selected" in attrs: raise serializers.ValidationError( {"select": "Cannot set selected for event in the future."} ) return super().validate(attrs) and the following view:- class EventMembershipViewSet(viewsets.GenericViewSet): queryset = Event.objects.all() serializer_class = EventSerializer then I can write this to test the serializer:- def test_create_select( self, past_event_factory, ): event = past_event_factory() data = { "event": event.hashid, "select": True } with pytest.raises( ValidationError, match="Cannot set selected for event in the future." ): serializer = EventMembershipSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() and this to test the view:- def test_create( self, past_event_factory, api_client ): url = reverse(<url>) event = past_event_factory() data = { "event": event.hashid, "select": True, } response = api_client.post(url, data, format="json") assert response.status_code == status.HTTP_400_BAD_REQUEST assert response.data["non_field_errors"][0] == "Cannot set selected for event in the future." But this really feels like I'm testing the same thing twice to me. If … -
Django Query calculate date with `relativedelta` error: can't adapt type 'relativedelta' [Updated]
I'm facing a tricky problem and couldn't find a solution online. I hope someone here can help me figure out a "clean" way to do this. What I want to do? I want to calculate the expiration date based on the model fields: rate_type, rate_repeat, timestamp. My Django Model looks like this (I omitted unnecessary parts): class LoanModel(ContractBase): class RateType(models.TextChoices): DAILY = "DAILY", _("Daily") WEEKLY = "WEEKLY", _("Weekly") MONTHLY = "MONTHLY", _("Monthly") YEARLY = "YEARLY", _("Yearly") timestamp = models.DateTimeField( auto_now_add=True, editable=True, db_comment=_("Creation date"), help_text=_("Creation date"), verbose_name=_("Creation date"), ) rate_type = models.CharField( max_length=255, choices=RateType.choices, db_comment=_("Contract rate type: Daily, Weekly, Monthly, Yearly"), help_text=_("Contract rate type: Daily, Weekly, Monthly, Yearly"), verbose_name=_("Rate type"), ) rate_repeat = models.PositiveIntegerField( validators=[MinValueValidator(1), MaxValueValidator(8)], db_comment=_("Interest rate repetition value"), help_text=_("Interest rate repetition value. The Contract is Active for: Rate repeat * Rate type"), verbose_name=_("Rate repeat"), ) ... def get_expiration_delta(self): """ Calculate the delta of the loan """ if self.rate_type == LoanModel.RateType.DAILY.name: delta = relativedelta(days=+self.rate_repeat) elif self.rate_type == LoanModel.RateType.WEEKLY.name: delta = relativedelta(weeks=+self.rate_repeat) elif self.rate_type == LoanModel.RateType.MONTHLY.name: delta = relativedelta(months=+self.rate_repeat) elif self.rate_type == LoanModel.RateType.YEARLY.name: delta = relativedelta(years=+self.rate_repeat) else: raise ServerError(_("Unknown rate type: %(rate_type)s") % {'rate_type': self.rate_type}) return delta def loan_expired_date(self): """ Return the date when the loan will expire :return: date """ … -
Hosting django rest framework and react in shared hosting like milesweb
Currently I am developing a web app using django rest framework as backend and react as frontend. I have almost completed my development. Next I need to deploy my web app. But I am so confused which hosting technique should I use. The hosting budget is atmost ₹4000. Can I able to host my app in shared hosting platform like milesweb. Could anyone please guide me by helping me to choose the right hosting platform I am currently developing a web app with python django rest framework backend and react as frontend. I want to deploy it in any shared hosting platform. -
Docker & Django : How to dockerize my django project and run it in a specific server ip?
I want to dockerize my django project and run it on a specific server says 192.168.156.94:8000. How do I do that? Thank you Dockerfile # Use Python 3.12.2 image based on Debian Bullseye in its slim variant as the base image FROM python:3.12.2-slim-bullseye # Set an environment variable to unbuffer Python output, aiding in logging and debugging ENV PYTHONBUFFERED=1 # Define an environment variable for the web service's port, commonly used in cloud services ENV PORT 8080 # Set the working directory within the container to /app for any subsequent commands WORKDIR /app # Copy the entire current directory contents into the container at /app COPY . /app/ # Upgrade pip to ensure we have the latest version for installing dependencies RUN pip install --upgrade pip # Install dependencies from the requirements.txt file to ensure our Python environment is ready RUN pip install -r requirements.txt # Set the command to run our web service using Gunicorn, binding it to 0.0.0.0 and the PORT environment variable CMD gunicorn server.wsgi:application --bind 0.0.0.0:"${PORT}" # Inform Docker that the container listens on the specified network port at runtime EXPOSE ${PORT} command line docker build -t django-docker-project:latest . docker run -p 8000:8080 \ --env PIPELINE=production … -
Why the html and css codes is not appearing in the page of a django form wizard page?
contest_selection.html: {% extends "wizard_form.html" %} {% load widget_tweaks %}` {% load i18n %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Landing Page</title> <link rel="stylesheet" href="{% static 'styles/mainStyle.css' %}" /> <link rel="stylesheet" href="{% static 'styles/LandingPageStyle.css' %}" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <div class="container"> <div class="Header"> <img src="{% static 'images/###.png' %}" alt="######" class="headerimg1"> <span>######################</span> <img src="{% static 'images/#####.png' %}" alt="######" class="headerImg2"> </div> <hr /> <br /><br /> <div> <p class="subtitle" style="margin-bottom: 20px;">Choose the <span style="color: #C83762;"> contests </span> you are registering in:</p> <br /> <form method="post" > {% csrf_token %} <div class="container_box"> {% for contest in contests %} <div> <label class="checkbox-container"> <input type="radio" name="contest" value="{{ contest.id }}" id="checkbox{{ forloop.counter }}" data-color="{{ contest.color }}"> <span class="checkmark" id="checkbox{{ forloop.counter }}" data-color="{{ contest.color }}"> <!-- color edit it later below--> <p style="font-weight: 800; font-size: 24px;">{{ contest.name.split('-')[0] }}-<span style="color:black;">{{ contest.name.split('-')[1] }}</span></p> <p>{{ contest.description }}</p> </span> </label> </div> {% endfor %} </div> <button type="submit">Next</button> </form> </div> <br /> <hr /> <br /> <div class="footer"> <span>Strategic partner</span> <img src="{% static 'images/#####.png' %}" alt="#######"> </div> </div> <script> document.addEventListener('DOMContentLoaded', (event) => { const radioButtons = document.querySelectorAll('input[type="radio"][name="contest"]'); radioButtons.forEach(radio => { radio.addEventListener('change', (event) => { radioButtons.forEach(rb => { const checkmark … -
Production Deployment (Apache24 with VueJS/Axios to Django DB)
I’ve hit a brick wall trying to understand how to get my PROD SSL front-end (Apache with VueJS/Axios) talking to my back-end (Django apps/views/models + database using SQLite for very lightweight I/O). All hosted on private Windows Server 2022 VM]. Clearly many options exist for the myriad configs possible but none I’ve read seem to fit this setup specifically ie running django purely as db server serving queries from rest axios calls from vuejs code, and with django sitting outside of apache (reviewed mod_wsgi, wsgi, gunicorn, etc, etc). Mod_wsgi may be the way fwd but not convinced yet. This is my 1st dep so still a bit of a newbie - just want to ensure I’m going down the right track tech wise. So at a high-level (happy to do the detailed reading) which route should I be taking?? Many thanks! PS: I ack the collectstatic step. NB: My localhost setup is all working fine using npm run serve for the front end and runsslserver for the backend. -
Django Query calculate date with `relativedelta` error: can't adapt type 'relativedelta'
I'm facing a tricky problem and couldn't find a solution online. I hope someone here can help me figure out a "clean" way to do this. This is my current function to retrieve all expired loans (it works): queryset = super().get_queryset().filter(is_active=True) expired_loans_ids = {loan.pk for loan in queryset if loan.is_expired()} expired_loans = queryset.filter(pk__in=expired_loans_ids) return expired_loans However, it's not ideal because I'm not just using a query; I must retrieve everything first. What I wanted to do was something like this: from dateutil.relativedelta import relativedelta queryset = super().get_queryset().filter(is_active=True) expired_loans = queryset.annotate( expiration_date=ExpressionWrapper( F('timestamp') + relativedelta(months=1), output_field=DateField() ) ).filter(expiration_date__lt=Now()) return expired_loans But I get this error when using relativedelta: django.db.utils.ProgrammingError: can't adapt type 'relativedelta' It works with timedelta, but each month has a different number of days... How can I accomplish something like this?