Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
one-to-many to many-to-many Relationship in Django model
I am looking for a relationship that A user creates an incident, Select multiple types And every type has many subtypes that users select from front-end I have a table called the incident, Incident name - XYZ type - Multiple types subtype - Multiple subtypes * Note A type has many subtypes in the system I am trying to do the below, Incident name - type - M2M(Type) Type name - subtype - M2M(Subtype) Subtype Name - Please suggest if the below design is good to go. Thanks! -
GET operation using Django rest_framework gets ConnectionRefusedError [Errno 111] after several hours of normal operation
I setup use Django to create a APP (let's call it central APP) that aggregate operation data from multiple applications on remote server. I then installed Django REST_Framework, to allow other applications, like Prometheus to get information from my Django central APP. The related Django APPs is shown below INSTALLED_APPS = [ ... #central APP I created 'django_prometheus', #This is not used 'rest_framework', 'django_filters', 'drf_multiple_model', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Other applications, like Prometheus, can successfully get info return. The API call frequency is 1 minutes per GET request. However, after around 5 hour of normal operation, Django will stop working. It seems the Djagon rest_framework cause the exception: File "/home/centos/.local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc The full exception return is shown below: (full exception removed since the system says "This looks like spam") In the past two weeks, I have disabled the REST_Framework API url, meaning other applications can not get info from the central APP through REST API. And the system is running fine. So I am pretty sure the problem comes from the API call. I have also tried things like changing the allowed Memory allocation for MySQL, change the localhost to '127.0.0.1', but … -
Can’t Access Procfile with Heroku (Django)
I can’t access wsgi in heroku Procfile web:gunicorn Medical_Portal.Medical_Portal.wsgi My files : My wsgi file in Medical_Portal/Medical_Portal/wsgi.py -
Django: Prepopulate Formset with ManyToMany Relationship and additional Fields
I have two models with an M2M relationship and extra fields: A menu is a compilation of many courses (i.e. dishes). The M2M relationship is reflected in MenuItem class/table. MenuItem has two additional fields: course_type (i.e. starter, appetizer, etc.) and course_position (to keep track of the position). models.py class Menu(models.Model): creator = models.ForeignKey(User, related_name='creator_id_menu', on_delete=models.PROTECT) menu_name = models.CharField(max_length=100, default='', verbose_name=_('menu name'), help_text=_('i.e. saturday night fajita night')) menu_description = models.CharField(max_length=300, default='', verbose_name=_('menu description'), help_text=_('this menu will blow your mind...')) menu_item = models.ManyToManyField(Course, through='MenuItem', blank=True) class Course(models.Model): creator = models.ForeignKey(User, related_name='creator_id_course', on_delete=models.PROTECT) course_name = models.CharField(max_length=100, help_text=_('give your creation a nice name!')) course_description = models.CharField(max_length=300, default='', verbose_name=_('course description'), help_text=_('give your creation a brief description!')) class MenuItem(models.Model): menu = models.ForeignKey(Menu, on_delete=models.CASCADE, verbose_name=_('menu name')) course = models.ForeignKey(Course, on_delete=models.PROTECT, verbose_name=_('course name')) course_type = models.CharField(choices=CourseType.choices, max_length=3, verbose_name=_('course type')) course_position = models.PositiveSmallIntegerField(verbose_name=_('course position')) forms.py class CourseForm(forms.ModelForm): course_type = forms.ChoiceField(choices=MenuItem.CourseType.choices) course_description = forms.Textarea() class Meta: model = Course fields = ['course_name', 'course_description'] CourseFormset = modelformset_factory(Course, form=CourseForm, extra=0) I can prepopulating the ModelFormset with the data from Course, but don't know, how to correctly access the MenuItem instance. That is why, my views.py misses the request.POST processing. views.py def update_menu_with_courses(request, pk): context = {} menu_instance = Menu.objects.get(id=pk) # initializing forms … -
Django datetimefield can't show d-m-y in templates
I was make a small project. I create a class Groups in model had create_date = datetimefield(). When I show create_date in template it just show the time I create. But when I add the |date=:"d-m-Y" it don't show any thing. Did you know how to change it. Thank! models.py class Group(models.Model): name = models.TextField(max_length=200,unique=True) slug = models.SlugField(allow_unicode=True,unique=True) descripsion = models.TextField(max_length=800,default=' ') image = models.ImageField(upload_to='group_pics/',default='group_pics/default_group.jpg', height_field=None, width_field=None, max_length=None) create_date = models.TimeField(auto_now_add=True) templates <h2>{{ group.name|safe }}</h2> <h4>{{ group.descripsion|safe }}</h4> <p>{{ group.create_date}}</p> If I don't use |date:"d-m-Y".It show time. But when I add the |date:"d-m-Y". It only show the name and descripsion. -
Django SMTP error sending e-mail with https(SSL) - deploying in AWS ElasticBeanstalk
Im sending an account verification e-mail and im utilizing AWS-EB to deploy it,in local with localhost it's functioning, but with https I get an error(I just configured the gmail to allow other apps, I don't know if I need to set an configuration at ElasticBeanstalk) The only configuration I did in Gmail was to allow less secure apps nothing else, and I have an recuperation e-mail and number, but my to steps verification is disabled and my number verification too. settings.py: if DEBUG: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'pleaeseSomebodyHireMeIWillBeTheHardestWorker@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword bla bla bla' # important else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' {% autoescape off %} Hi {{ user.user_name }}, Sua conta foi registrada com {%comment%} http://{{ domain }}{% url 'account:activate' uidb64=uid token=token %} {%endcomment%} https:/{{ jamelaumn.com }}{% url 'account:activate' uidb64=uid token=token %} {% endautoescape %} views.py def account_register(request): if request.user.is_authenticated: return redirect('account:dashboard') if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False email_to = user.email user.save() email_subject = 'Ative sua conta' current_site = get_current_site(request) message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) html_message = "<br> oi </br>" email_body = message … -
How to send notification to a perticular user id from django
I am able to send notification from admin to all using this github code https://github.com/priyanshu2015/django-channels-celery but not able to send notification to a perticular userid what modification should i do to achive this. also from view i want send notification to user specific. -
postgres hstore removed from django model, but getting error in testing
I removed the postgres hstore field when I rewrote my models. But I'm getting this error. django.db.utils.ProgrammingError: type "hstore" does not exist LINE 1: ...r(254) NULL UNIQUE, "bio" text NOT NULL, "follow" hstore NUL... This follow hstore field doesn't exist anymore. I tried migrating again, but changes are already made. I used a many to many field to create following, I was just trying to learn what hstore field could do when I added it. Does Django still think I have an hstore field? This stackoverflow answer says that testing started working when hstore extension was added to template1 postgres database. Should I just try that? But if my model doesn't use hstore, why would I need to? -
how to create three tables in nested-serializer objects using django rest framework
I am trying to create a three model nested objects in django rest framework models.py class Project(models.Model): project_id = models.AutoField(primary_key=True, unique=True) project_name = models.CharField(max_length=100) class ProjectSite(models.Model): site_id = models.AutoField(primary_key=True, unique=True) site_name = models.CharField(max_length=200,name='project_site_name') project_id = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True, related_name="projectid") class Assignment(models.Model): assignment_id = models.AutoField(primary_key=True) assignment_name = models.CharField(max_length=150) site_id = models.ForeignKey(ProjectSite,related_name="projectsiteidkey", on_delete=models.CASCADE) assigned_to_id = models.ForeignKey('auth.User',related_name="assignedtoidfkey",on_delete=models.CASCADE) serializer.py class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' class ProjectSiteSerializer(serializers.ModelSerializer): class Meta: model = ProjectSite fields = '__all__' class AssignedUserSerializer(serializers.ModelSerializer): class Meta: model = Assignment fields = '__all__' class CreateNewProjetSerial(serializers.ModelSerializer): site_name = ProjectSiteSerializer(many=True) assigned_to_id = AssignedUserSerializer(many=True) class Meta: model = Project fields = ['site_name','project_name','assigned_to_id'] def create(self, validated_data): site_name = validated_data.pop('site_name') assigned_to_id = validated_data.pop('assigned_to_id') projects = Project.objects.create(**validated_data) for i in site_name: ProjectSite.objects.create(site_name=projects, **i) for j in assigned_to_id: Assignment.objects.create(assigned_to_id=projects, **j) return projects view.py class MultieCreateAPIView(generics.CreateAPIView): queryset = Project.objects.all() serializer_class = CreateNewProjetSerial I would like to post a JSON object like this { "site_name": [{"site_name": "site1"}, {"site_name": "site2"}], "project_name": "test_project", "assigned_to_id": [{"assigned_to_id":2}, {"assigned_to_id":3}] } When I try to post this I got error with "Cannot assign "<Project: test_project>": "Assignment.assigned_to_id" must be a "User" instance". Thank you for helping me in advance. -
Routing Problem in calling API from REACT using Redux
I have create api with Python (django restframework). I am calling that api from my react applicaation using redux. It works fine when i call it like this const {data} = await axios.get(`http://127.0.0.1:8000/api/products/${id}`) but when i change the url to const {data} = await axios.get(`api/products/${id}`) It then makes a request to a different route ( http://localhost:3000/product/api/products/6) and I want it to make a call to (http://localhost:8000/api/products/6 I have added the path in django server and allowed calls from the react app. and it is working perfectly when i was working with other routes. for example it was working fine when i was making call to this route const {data} = await axios.get('api/products/') -
In Django rest framework, can I modify serializer instead of accepting 2 lists to accept a list of objects containing them
I am trying to modify the way I want to accept data from endpoints without modifying the model defined for it. Hence I want to modify the serializer. I am not sure how should I redefine it. I have a serializer defined as class AssetWorkorderSerializer(MaxenBaseSerializer): id = ReadOnlyField() assets = PrimaryKeyRelatedField( many=True, read_only=False, allow_null=False, queryset=models.Asset.objects.all(), ) assignee = PrimaryKeyRelatedField( many=False, read_only=False, allow_null=True, queryset=User.objects.all() ) checklists = PrimaryKeyRelatedField( many=True, read_only=False, queryset=Checklist.objects.all() ) assigned_by = PrimaryKeyRelatedField( many=False, queryset=User.objects.all()) deadline = ReadOnlyField() overdue = ReadOnlyField() class Meta: model = models.AssetWorkorder fields = "__all__" So objects accepted are: { "count": 1, "next": null, "previous": null, "results": [ { "url": "https://<some-url>/assetworkorders/29/", "id": 29, "assets": [ 292, 293 ], "assignee": 33, "checklists": [ 7, 8, 9 ], "assigned_by": 32, "deadline": "2022-03-31", "overdue": true, "created": "2022-03-31T03:52:59.123745Z", "updated": "2022-03-31T17:18:49.599963Z", "name": "Service HVACs", "description": "Service HVACs", "status": "OP", "priority": "LO", "duedate": "2022-03-31", "scheduleddate": "2022-03-30", "notifications_enabled": false }, ] } Instead I want to accept like this: { "count": 1, "next": null, "previous": null, "results": [ { "url": "https://<some-url>/assetworkorders/29/", "id": 29, "assetChecklist": [ {"asset": 292, "checklists": [7,8]}, {"asset": 293, "checklists": [8,9]}, ], "assignee": 33, "assigned_by": 32, "deadline": "2022-03-31", "overdue": true, "created": "2022-03-31T03:52:59.123745Z", "updated": "2022-03-31T17:18:49.599963Z", "name": "Service HVACs", "description": "Service HVACs", … -
Django ModuleNotFoundError: No module named 'models'
I'm building a web app in Django to purchase movie tickets. All the logic handling the database is in the 'ticket_handler' app. The actual website is in the 'movie_site' app and I'm building a restful api in the 'ticketing_api' app. Whenever I try to import something from one app to another, I get a "ModuleNotFound" error. Here is my directory structure: Movie_Ticketing_Service |- movie_server | |- movie_server | | |- __init__.py | | |- asgi.py | | |- settings.py | | |- urls.py | | |- wsgi.py | |- movie_site | | |- migrations | | |- templates | | |- __init__.py | | |- admin.py | | |- apps.py | | |- forms.py | | |- models.py | | |- tests.py | | |- urls.py | | |- views.py | |- ticket_handler | | |- migrations | | |- __init__.py | | |- admin.py | | |- apps.py | | |- billing_handler.py | | |- mail_handler.py | | |- models.py | | |- tests.py | | |- ticket_handler.py | | |- views.py | |- tecketing_api | | |- migrations | | |- __init__.py | | |- admin.py | | |- apps.py | | |- forms.py | | |- models.py … -
django.contrib.admin.sites.NotRegistered: The model User is not registered
I am trying to register my custom user model to the admin site (I have name my custom user model User), but I am getting this error. as I understood that I should unregister the original User model then register my custom model and this what I have tried to do!! ---------setings.py------- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', # This is custom user model ] AUTH_USER_MODEL = 'users.User' ---------users/admin.py------- from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User as MyUser # my Custom User Model from django.contrib.auth.models import User admin.site.unregister(User) class MyUserAdmin(UserAdmin): list_display = ('username', 'email') admin.site.register(MyUser,MyUserAdmin) -
How to send image from Expo Image Picker to Django REST using axios
I have spent about a week on this and cannot understand what is going on. I need to upload images from React-Native (EXPO) to Django REST. It seems to be that axios is sending an object instead of an image (I think). React Native EXPO Image Picker/Axios: const pickImage = async () => { // No permissions request is necessary for launching the image library let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [4, 3], quality: 1, }); if (!result.cancelled) { const formData = new FormData(); formData.append("image", { uri: result.uri, name: "image.jpeg", type: "image/jpeg", }); try { const response = await axiosInstance({ method: "post", url: `/api/businesses/84/upload_image/`, data: formData, headers: { "Content-Type": "multipart/form-data" }, }) console.log(response.data); } catch (error) { console.log(error.response.data); } } }; Django API: class BusinessProfileViewSet(MixedPermissionModelViewSet): """ API endpoint that allows business profiles to be viewed, created, or edited. """ queryset = BusinessProfile.objects.all().order_by('-created_on') serializer_class = BusinessProfileSerializer permission_classes_by_action = { 'list': [IsOwnerOrStaff], 'create': [AllowAny], 'update': [IsOwnerOrStaff], 'retrieve': [IsOwnerOrStaff], 'partial_update': [IsOwnerOrStaff], 'destroy': [IsAdminUser] } paginator = None parser_classes = [MultiPartParser, FormParser] @action(methods=['post'], detail=True, permission_classes=[IsAuthenticated]) def upload_image(self, request, pk=None): try: print(request.data) image = request.data except KeyError: raise KeyError('Request has no image attached') business_profile = BusinessProfile.objects.get(user=request.user) business_profile.image = image business_profile.save() return … -
Django - send_mail -No error while trying to send e-mail, but no e-mail is Sent
Im trying to send an verification email to new registred accounts, but the e-mail is not being sent, the html page that is being loaded when I send the e-mail is being perfectly loaded, and I dont get an error in console aaaaaaaaaaaaaaaaaaaaaa if DEBUG: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'jamelaumn@gmail.com' EMAIL_HOST_PASSWORD = xxxxx # important else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' def account_register(request): if request.user.is_authenticated: return redirect('account:dashboard') if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False email_to = user.email user.save() email_subject = 'Ative sua conta' current_site = get_current_site(request) message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) html_message = "<br> oi </br>" email_body = message send_mail([email_to], subject=email_subject, message=message, from_email=settings.EMAIL_HOST_USER, html_message=html_message) """ email = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [email_to]) email.send() """ return HttpResponse('registered succesfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) def account_activate(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return redirect('account:dashboard') else: return render(request, 'account/registration/activation_invalid.html') -
Raw sql query issue in Django
I am trying to to make an SQL query to impliment the answer given here. The user suggested I try doing a raw sql query to solve. I am having issues implimenting what he suggests. For example, this is what I have so far. ingredients = ["eggs", "bacon", "salt"] recipes = Recipe.objects.raw('select whattocook_RecipeIngredients \ from whattocook_Recipe a \ inner join whattocook_RecipeIngredients b \ on a.id = b.recipe_id and b.ingredient in (ingedients) \ group by recipeingredients \ having count(*) >= 2') But this does not work. His answer says to do this recipe_list = Recipe.objects.raw('select a.* from app_Recipe a inner join app_RecipeIngredients b on a.id = b.recipe_id and b.ingredient in ("egg", "bacon", "rice") group by a.* having count(*) >= 2') maybe replace app_ with your project name, replace a.* with list of column names. So I think I am misunderstanding which columns I need to replace, given my code gives me this error. django.db.utils.ProgrammingError: column "ingedients" does not exist LINE 1: ... on a.id = b.recipe_id and b.ingredient in (ingedients... ^ HINT: Perhaps you meant to reference the column "b.ingredient". My app is named whattocook, and the models are as follows class RecipeIngredients(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True) ingredient = models.TextField(null=True, … -
Stuck on Django poll tutorial (trying to connect the polls app to the server.)
i've been trying to connect to polls application but it still only shows the default page in django :( main app: First site url from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')) ] urls.py in polls app from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ] -
Passing Extra context to ListViews in Django
Can anyone please tell me how I can pass the "query" on my ListView as a context while at the same time keeping "search_results" as a context_object_name? I just can't get my head around it: class SearchResulView(ListView): model = Product template_name = 'shop/product/search_results.html' context_object_name = 'search_results' def get_queryset(self): query = self.request.GET.get("q") search_results = Product.objects.filter( Q(name__icontains=query) ) return search_results Am trying to render the values passed to "query" on my template but I just can't figure out how... -
can't edit Boolean field on django model when it is link with another field from the same model within this logic scoop?
I am working on django v4.* and I came cross a point where I need to make field publish_date to be auto populated when is_published is ticked import datetime class Article(models.Model): ....... is_published = models.BooleanField(default=False) publish_date = models.DateTimeField(blank=True, null=True) ....... def save(self, *args, **kwargs): if self.is_published: self.publish_date = datetime.datetime.now() super().save(*args, **kwargs) this did the trick but the problem that I can not edit the is_published field anymore, when I tick it (make it true) it stay true even if I try to change it to untick -
How to access object data from 'self' in get_context_data?
I'm creating some charts using ChartJS and Django, so I have the view below: class ChartView(TemplateView): template_name = 'app/chart.html' def get_context_data(self, **kwargs): context = super(ChartView, self).get_context_data(**kwargs) print('\n') print('****************** I NEED TO SEE ALL THE FIELDS AND VALUES THAT ARE BEING PASSED THROUGH SELF ******************') print(self) print('\n') return context I'm informing some values to my charts from context... but I need to do some calculations and I need to see what is exactly comming from "self"... how to access this data? For example, if would be necessary I do something like that: context['obj'] = Obj.objects.get(pk=pk_from_self) -
Can I serve a react app (with react router) from a specific endpoint?
I have a Django app. Most of the endpoints for this app will serve up a template. However, I would like one endpoint, lets say example.com/xyz, to serve a React app. This react app uses routes, so it would manipulate the url path. My question comes in two parts: If it is possible to do this, how can I ensure React router keeps the original /xyz endpoint in the path before adding whatever else to it? How can I configure Django to return the react app for ANY endpoint that begins with /xyz? -
Django: I want to track from which url a request was made?
in the TestQuestionList class, the get function must receive an id to return id, I thought that I could do this with the help of request.get_full_path()example on the bottom class TestQuestionList(APIView): def get(self, request): obj = Test.objects.get(id = request.get_full_path()) romms = TestQuestionBlok.objects.filter(id__in=obj.questions) serializer = TestQuestionSerializers(romms, many=True) return Response(serializer.data) but request.get_full_path() instead of /tests/api/ (where the request was made from) returned /api/question/ why? This is part of the code from where the request was made useEffect(() => { axios({ method: 'GET', url: 'http://127.0.0.1:8000/api/questions/', }).then(response => { setAllQuestions(response.data) }) }, []) Thanks in advance for your replies -
Django modifying login view has no effect
Long story short: No matter what I do with the login view, it won't change the behavior of the login form, I can delete my views altogether (and urls) and it still works, so it must be picking it up from somewhere else. From where and how do I change that? Long version: I was following a tutorial to implement login, logout and registration with django built in features, it is actually working fine but when I was trying to modify the login view I just realized that no matter what I tried to do in the view, it wouldn't change the behaviour (I was trying to redirect to a different page if the user was already logged, for instance). I started playing around to see what I could change and how it would reflect, even adding prints, but nothing happened, until I decided to try replacing all the code inside the login view function with pass, AND IT STILL WORKED! It happens the same with the logout view, but it doesn't with the register view. I don't understand what's going on. I tried to find something online, but I couldn't find anything related to this exact issue. This is … -
Accept URL as parameter in path (special characters)
I have a view and a path where I'd like to accept a str parameter and pass it to my make_request view. The problem I'm having is the strings I'd like to accept are URLs. When I pass a string like 'https://example.com/' I get an error saying Page not found (404) as there are special characters. urls.py from django.urls import path from . import views urlpatterns = [ path('<str:url>', views.make_request, name='make_request'), ] views.py def make_request(url): print(url) -
Django ORM filtering using expression against multiple fields
I am trying to use Django ORM filter to retrieve Announcement records with announcement_dates that are later than the current date - "expire_in_days" field - i.e., retrieve announcements that have not yet expired. Here is the SQL representation of what I am trying to do with ORM: select * from announcement where message_date > current_date - expire_in_days; I should be able to retrieve all records and filter them externally, but I am trying to learn how to do this with Django. Here is my model class Announcement(models.Model): message = models.TextField("announcement message") message_date = models.DateField("Announcement date") expire_in_days = models.PositiveIntegerField("Number of days before announcement expires") def __str__(self) -> str: return '(message: %s, message_date: %s, expire_in_days: %s)' % (self.message, self.message_date, self.expire_in_days) Here is what I tried but it did not work: In [1]: from events.models import Announcement In [2]: from datetime import date, timedelta In [3]: from django.db.models import F In [4]: date.today() Out[4]: datetime.date(2022, 5, 29) In [5]: date.today() - timedelta(days=2) Out[5]: datetime.date(2022, 5, 27) In [6]: Announcement.objects.all() Out[6]: <QuerySet [<Announcement: (message: There is a surprise coming up!, message_date: 2022-05-27, expire_in_days: 1)>]>" In [7]: Announcement.objects.filter(message_date__gt = (date.today() - timedelta(days = F('expire_in_days')))) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [7], in …