Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Locking out button using python
I have a django app and what i want to do is when a html button is pressed i want to have a pop up window locking out the current page saying "Assignment submitted". I want the user to be able to be able to submit again at the begining of each new day. so hence only being able to click the submit button once a day. I know i will have to use the datetime function to access the current day and lock the site out until tomorrow. Any one know any handy tutorials or things i should look up? <input type="button" value="submit" onclick="window.open('submit')"> I guess the cleanest way is to incorporate this locking out functionality in my submit python function in main.py file. -
conversion of datetime Field to string in django queryset.values_list()?
my code: from django.db.models import TextField from django.db.models import F, Func, Value, CharField qs=People.objects.annotate( formatted_date=Func( F('create_time'), Value('%Y-%m-%d %H:%M:%S'), function='to_char', output_field=TextField() ) ).values('create_time').first() print(qs) but get data is {'create_time': datetime.datetime(2021, 2, 16, 15, 58, 10, 305730, tzinfo=<UTC>)} i want to data is {'create_time': "2020-12-02 17:12:12"} my used database is mysql -
How to create an object of type rest_framework.request.Request to perform a get request?
I have a get method that is supposed to perform a GET request. I also have a put method that is supposed to perform a PUT request. For what I need to do I'm trying to call the get method inside the put method before any logic happens. Parts of the code is shown below: def get(self, request, pk, format=None): ... ... return Response(data, status=status.HTTP_200_OK) def put(self, request, pk, format=None): print(type(request)) self.get(request,pk) //This is the line that I'm having trouble with. ... ... return Response(data, status=status.HTTP_200_OK) The problem I'm facing is I'm not sure how to construct the data for the request parameter. Using postman to send a request, when I print the type of request I get <class 'rest_framework.request.Request'>. And when I print request itself I get <rest_framework.request.Request: PUT '/core/test/34500994/'>. I can't seem to find docs on rest_framework.request.Request. How do I create a rest_framework.request.Request object that is for a GET request that I can use as an arguement for the put method? -
Image in web browser not getting rendered
Image in web browser not getting rendered, showing alt attribute's message, I am using Django's lightweight server not only that but the image is not visible even in simple static html file but it is getting rendered when it's address in pasted in browser's search bar My code something looks like HTML file <!DOCTYPE html> {% load static %} <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 prod in allProds %} {{prod.name}}<br> <img src="/media/{{prod.img}}"><br> {{prod.img}} {{prod.smdesc}}<br> {{prod.bgdesc}} <br> {% endfor %} </body> </html> models.py from django.db import models import uuid from django.contrib.auth.models import User # Create your models here. class Category(models.Model): category = models.CharField(max_length=50) class SubCategory(models.Model): sub_category = models.CharField(max_length=50) class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=40) img = models.ImageField(upload_to='shop/images') smdesc = models.CharField(max_length=100) bgdesc = models.CharField(max_length=400) price = models.IntegerField() in_Stock = models.IntegerField(default=0) discount = models.IntegerField(default=0) category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE) date_added = models.DateField(auto_now=True) def __str__(self): return f"{self.name} of {self.price}" class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) cart_items = models.ManyToManyField(Product, blank=True, related_name="cart_items") views.py from django.shortcuts import render from .models import Product # Create your views here. def index(request): allProds = Product.objects.all() context = { 'allProds':allProds } return render(request, … -
Using a Subquery and OuterRef in a Django Annotation with unrelated models
I want to annotate all my price models with the normalized price in Dollars: class FxRate(models.Model): date = models.DateField() nominal_currency_code = models.CharField( max_length=3) value = models.DecimalField(max_digits=20, decimal_places=8) class Price(models.Model): currency = models.CharField(max_length=3, default="BIF") price_value = models.DecimalField((max_digits=20, decimal_places=8) date = models.DateField() So if today (date = 2021-03-23) the exchange rate of BIF against USD is 1900BIF/USD, I want to annotate all prices and add the price_value in USD. For that I have been trying this: from django.db.models import OuterRef, Subquery, F monthly_rate = FxRate.objects.filter( nominal_currency_code=OuterRef("currency"), date__year=OuterRef("date__year"), date__month=OuterRef("date__month") ) it assumes that currency, date in the above code refer to the values from the Price model bellow that I will be passing to the SubQUery pp = Price.objects.all().annotate(dollars_prices=Subquery(monthly_rate.values("value")[0])*F("price_value")) But whenever I run that code I'm faced with an error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. Does OuterRef uses objects with ForeignKeys only? What am I not getting well in the SubQueries ? -
Foreign key assignment in Class based views
Basically I have a "node" detail page, from where I need to assign a new drive (for this given node - they need to be linked). The issue is to link "node" for DriveModelForm, which need to be assigned in the view. Whats wrong? All the details are below. Urls: urlpatterns = [ path('<int:pk>/drivecreate/', DriveCreateView.as_view(), name='drive-create') ] View: class DriveCreateView(CreateView): template_name = 'create_drive.html' form_class = DriveModelForm def get_success_url(self): return reverse('nodes:node-detail') def form_valid(self, form): drive = form.save(commit=False) drive.node = ?? drive.save() return super(DriveCreateView, self).form_valid(form) Model: class Drive(models.Model): manufacture = models.CharField(max_length=32) model = models.CharField(max_length=32) drive_type = models.CharField(max_length=32) capacity = models.IntegerField(default=0) node = models.ForeignKey(Node, on_delete=models.CASCADE) class Node(models.Model): name = models.CharField(max_length=32) ... many more ... Form: class DriveModelForm(forms.ModelForm): class Meta: model = Drive fields = ( 'manufacture', 'model', 'drive_type', 'capacity', ) -
How to lazy load objects in django pagination?
Is it possible to load objects on scroll in Django pagination? I want to display certain amount of posts per page and make it so that they are loaded when user scrolls down and when this "certain amount of posts per page" is reached, link to next page pops up. Is it possible? -
Gunicorn cant find the static files
By using gunicorn without nginx from digitalcloud tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04#create-and-configure-a-new-django-project my server is runing and on the console is not found: /static/style.css settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') I already tried to collectstatic do urlpatterns += staticfiles_urlpatterns() in urls.py file makemigrations + migrate -
Django models, how to create model which looks like json
I have problem with creating model. I don't know how to make my model looks like json file I made earlier which looks like like below. Is there way in which I can create model based on MongoDB document, or any other that will help me creating this model? { "id": 1, "zestaw": { "pytanie1": { "tresc": "Wartość\\:wyrażenia \\:x^2-5x + 90:dla \\:x= ZMIENNA1\\:", "warianty": ["1-2\\sqrt{3}", "3", "1+2\\sqrt{3}", "1-2\\sqrt{3}"], "odpowiedzi": ["3", "1", "1+2 sqrt{3}", "1-2 sqrt{3}"], "poziom trudności": 1 }, "pytanie2": { "tresc": "Liczba\\:ZMIENNA1\\:jest\\:równa", "warianty": ["\\frac{2^{25}*3^{40}}{30^{10}}", "\\frac{2^{60}*3^{40}}{36^{10}}", "\\frac{2^{50}*3^{60}}{36^{12}}", "\\frac{2^{50}*3^{40}}{36^{10}}"], "odpowiedzi": ["2^{30} * 3^{20}", "6^{45}", "6^{70}", "2^{10} * 3^{20}"], "poziom trudności": 1 } } -
How to access first made website in Django
Hi I'm new to Django so just wanted to ask if we create a website and then create another so how can we access the first website created -
Exclude fields with the same value - queryset, Django
In my project, I have Articles and User Responses that have the same value "title". I only want to find the first Articles, becouse other object have the same "title", these are the users' answers. How can I exclude objects from queryset have the same "title" parameter. I try this: q1 = Article.objects.order_by().values('title').distinct() *work good but it returns something like a list Well I try convert it to query q2 = Article.objects.filter(title__in=q1).distinct() *But it causes it to return all Repeat-Topic Articles again How to exclude objects from queryset that have the same title without changing them to a list. -
How to automatically add weekend dates when a user clicks on a page of a website?
I am making a swimming pool website where the user can check if the weekend days are available for booking a party/event. For that, there is a web page called Organize Party. Here is what I want to achieve: When the user clicks on the 'Organize Party' web page, the site queries the database for the weekend dates from 2 weeks ahead (because the booking for the party must be done 2 weeks in advance at least) to up to 8 weeks ahead. If the date does not exist beforehand, it adds those dates, and if it exists, it simply checks whether a boolean isBooked is true or not. How do I do this? I know I would have to add some python code to class index(request) in views.py , but I am not sure about what to add. -
How can I prevent a Django model that is to be deleted to access a related many-to-many object?
I have a problem with overriding a delete method for a class in Django. I have two models, which are in two separate databases. Yes, I know, Django has a problem with that. Still, except for the deletion it works so far. I have DB_A with Table_A and in it Class_A. And Class_A has a field m2m, which has a many-to-many relationship with Class_B in Table_B on DB_B. Now, when I want to delete an object (Class_B) from Table_B, Django complains that there is no intermediary (through) table on DB_B. At least to some degree I can understand this. Therefore I wanted to override that model's delete method and somehow tell Django how to manually delete the corresponding entries in the through table and otherwise just to stick to the deletion of that object in this table (B) and database (B). But I don't know how. Can you help me? -
Can't display icon in HTML <i class="{{ icon_class }}"> with Django
I'm trying to dynamically load desired icons in HTML doc. What it should look like is shown on the third div (with text ORGANISED ROUTE) result on the page To test what causes the problem I've tried three different things in each of the three div. The first one (picto_1 and text PRE-BOOKED VOUCHERS) is the actual code I expect to work and it should look like the third one with icon displayed and text under it. In seccond div (with picto_2 and AUDIO GUIDE AND MAP) I've just displayed the text from the picto_2 = models.CharField(max_length=30, default=0) field in the Model to be sure that I'll get the correct text for the icon class I want to display. As already said the third div (picto_3) is what I expect to see in the picto_1 div also. I can't figure it out why if it shows in the third div it doesen't show in the firs when it should be the same code. I'm pretty much a total noob so sorry if my first post is not written very clear. <div class="row feature_home_2"> <div class="col-md-4 text-center"> <i class="{{ discover.picto_1|default:"" }}"></i> <h3>{{ discover.icon_1_text|default:""|safe }}</h3> </div> <div class="col-md-4 text-center"> {{ discover.picto_2|default:"" }} … -
API Discord just get messages of a
I am currently working on an application in django. I have a community on Discord and I would like to get the messages of a channel on my platform. To do this, I have created the discord application. So I have my CLIENT ID, SECRET CLIENT and PUBLIC KEY. Then I developed the generation of the token, everything works it is well returned: def discord_get_token(): data = { 'grant_type': 'client_credentials', 'scope': 'identify connections messages.read' } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } r = requests.post('%s/oauth2/token' % DISCORD_BASE_URI, data=data, headers=headers, auth=(DISCORD_CLIENT_ID, DISCORD_PRIVATE_KEY)) r.raise_for_status() #Token print(r.json()['access_token']) return r.json()['access_token'] And now I'm stuck, I don't want to use a bot to retrieve messages, I just want to use this route: GET /channels/{channel.id}/messages so I do my tests on postman liks this : https://discord.com/api/channels/ID_CHANNEL/messages In headers : Authorization : Bearer MY_TOKEN content-type : application/json But the message returns the error 401 Unauthorized. There is certainly some information missing but I really don't see which one if anyone can help me out thank you very much ! -
Django trying to paginated list view throws unhashable error
My view class CatListView(ListView): template_name = 'recepti/category.html' context_object_name = 'catlist' paginate_by = 4 def get_queryset(self): content = { # sendamo na template category name 'cat': self.kwargs['category'], # vse recepti tiste categorije 'posts': Recept.newmanager.filter(category__name=self.kwargs['category']) } return content And my template {% extends "recepti/base.html"%} {% block content %} <h2>{{catlist.cat|title}}</h2> {% for recept in catlist.posts%} <article class="media content-section"> <img class="rounded-circle article-img" src="{{recept.avtor.profile.image.url}}" > <div class="media-body"> <div class="article-metadata"> {% if recept.avtor.is_staff %} <a class="mr-2" href="{% url 'user-recepti' recept.avtor.username%}">{{ recept.avtor }}</a><i class="fas fa-check-circle"style="color:#7CFC00;"></i> {% else %} <a class="mr-2" href="{% url 'user-recepti' recept.avtor.username%}">{{ recept.avtor }}</a> {% endif %} <small class="text-muted">{{ recept.datum|date:"d F, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'recept-detail' recept.id %}">{{ recept.naslov }}</a></h2> <p class="article-content">{{recept.sestavine }}</p> <p class="article-content">{{ recept.priprava}}</p> </div> </article> {% endfor %} {% if is_paginated %} {%if page_obj.has_previous %} <a class ="btn btn-outline-info mb-4" href="?page=1">First</a> <a class ="btn btn-outline-info mb-4" href="?page={{page_obj.previous_page_number}}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class ="btn btn-info mb-4"btn-info mb-4 href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {%if page_obj.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{page_obj.next_page_number}}">Next</a> <a class ="btn … -
Prevent Django's Unittest to overwrite Variable on model clone
i have some Unit-Tests for a Project in Django and want to Test the Model with Unit-Test. At the Test for cloning an Model my variable get overwritten: Here an example: Django Unittest testevent = Event.objects.create(state=STATE_LIVE, name="Testname") cloned_event = testevent.clone_event() # it should be 1,2 but it is 2,2 self.assertNotEqual(testevent.pk, cloned_event.pk) The Django-Model looks like this: def clone_event(self): current_pk = self.pk self.pk = None self.id = None self.save() # in between i copy some stuff i also need return self The Django-Version is 2.2.4 Thanks for help -
i am getting error while installing mysqlclient on windows 10 no library is supproted
Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\uaahacker\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\uaahacker\AppData\Local\Temp\pip-install-icjkjmap\mysqlclient_8b5f49f509624395ab7dd2c4d4a21457\setup.py'"'"'; file='"'"'C:\Users\uaahacker\AppData\Local\Temp\pip-install-icjkjmap\mysqlclient_8b5f49f509624395ab7dd2c4d4a21457\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\uaahacker\AppData\Local\Temp\pip-record-62876lx5\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\uaahacker\appdata\local\programs\python\python38-32\Include\mysqlclient' cwd: C:\Users\uaahacker\AppData\Local\Temp\pip-install-icjkjmap\mysqlclient_8b5f49f509624395ab7dd2c4d4a21457 Complete output (23 lines): running install running build running build_py creating build creating build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb_init_.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\uaahacker\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\uaahacker\AppData\Local\Temp\pip-install-icjkjmap\mysqlclient_8b5f49f509624395ab7dd2c4d4a21457\setup.py'"'"'; file='"'"'C:\Users\uaahacker\AppData\Local\Temp\pip-install-icjkjmap\mysqlclient_8b5f49f509624395ab7dd2c4d4a21457\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\uaahacker\AppData\Local\Temp\pip-record-62876lx5\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\uaahacker\appdata\local\programs\python\python38-32\Include\mysqlclient' Check the logs for full command output. -
Django extra_views - UpdateWithInlinesView: field doesn't exist
I have two models: UserPost and Image - they are in one-to-many relationship. I want to be able to update both of the models in one template so I followed the docs and tried to implement UpdateWithInlinesView from extra_views but I got an error: Unknown field(s) (image) specified for UserPost Anyone knows what's happening? models.py class UserPost(models.Model): user_id=models.ForeignKey(User,on_delete=models.CASCADE) title=models.CharField(max_length=255) ...and some other fields class Image(models.Model): id = models.AutoField(primary_key=True) user_post=models.ForeignKey(UserPost,default=None, on_delete=models.CASCADE) image=models.ImageField(null=True,blank=True,upload_to='images/') def __str__(self): return self.user_post.title def get_absolute_url(self): return reverse('home') forms.py class ImageInline(InlineFormSetFactory): model = myModels.Image fields = ['user_post','image'] views.py class PostUpdate(UpdateWithInlinesView): model=shopModels.UserPost form=myForms.UploadPostForm inlines = [myForms.ImageInline] template_name = 'update_post.html' fields=['image'] def get_success_url(self): return redirect('home') update_post.html {% extends './base.html' %} {% block content %} {% csrf_token %} {{ form }} {% for formset in inlines %} {{ formset }} {% endfor %} {% endblock %} -
Django - CSRF cookie not set when logging in from Axios
I'm trying to use the standard Django authentication system with a separated Vue/Django app, so Vue handles entirely the entire frontend, Django will work as an API on the backend. Both backend and frontend will be deployed on the same server and on the same port, in order to keep Session auth. Right now my backend uses django-allauth (which uses the built-in Django auth under the hood, i think) for everything authentication related and it supports Session authentication from AJAX. I'm trying to login from the Vue SPA app using Axios, but i keep getting the following error: Forbidden (CSRF cookie not set.): /accounts/login/ Here is my frontend code: get_csrf() { axios.get('http://127.0.0.1:8000/get_csrf/') .then(response => { this.csrf_token = response['data']; }); }, authenticate() { this.get_csrf() axios.post('http://127.0.0.1:8000/accounts/login/', { username: 'test', password: 'test123', }, { headers: { 'X-CSRFTOKEN': this.csrf_token }, }) .then(function (response) { console.log(response) }.bind(this)) }, So get_csrf() is used to connect to an API endpoint on the Django backend that will generate the csrf token, i know that security wise this is not the best practice but i still have to find a safer way to use this, and i can also use samesite=Lax and disable the CSRF protection, but i don't … -
Multiple Django apps using django-tailwind
So, I have been trying out a way to use TailwindCSS with django and I luckily found the package that does the right job for me which is django-tailwind. In the docs, the author has specified how to use all the utlity classes of Tailwind in an app. But hasn't mentioned how to use Tailwind in other Django apps. TAILWIND_APP_NAME = <the app name> is the way to specify the Tailwind app So do I specify a list of the other apps I have like TAILWIND_APP_NAME = [<app1>, <app2>] Or some other way? Thanks. -
Update a field of a Django Object
I'm trying to update an object field in django. Usually I would do something like this: # MODEL --- class MyObj(models.model): name: models.CharField(max_length=10) surname: models.CharField(max_length=10) # VIEW --- # [...] myObj = MyObj.objects.get(pk=1) myObj.name = 'John' myObj.save() The problem is that the field to modify (in the example above: "name") is not known and passed as an argument to the post request. So I would have something like this: # VIEW --- # [...] field = self.request.query_params['field_to_modify'] myObj = MyObj.objects.get(pk=1) myObj[field] = 'John' myObj.save() now this triggers the error: myObj[field] = 'John' TypeError: 'MyObj' object does not support item assignment What is the correct way to update an "unknown" field of a django object? -
Different authentications and permissions in ModelViewSet - Django REST framework
This question is similar to this one: Using different authentication for different operations in ModelViewSet in Django REST framework, but it didn't work for me. I've got the following viewset: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = UserProfile.objects.none() permission_classes = [SpecialPermission] SpecialPermission looks like this: class SpecialPermission(IsAuthenticated): def has_permission(self, request, view): if request.method == 'POST': return True return super().has_permission(request, view) REST framework settings: "DEFAULT_AUTHENTICATION_CLASSES": ["backend.api.authentication.ExpiringTokenAuthentication"], "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"], I want to everybody to be able to post to UserViewSet but every other method should require Authentication. However, with the code above I get an Unauthorized Response on post. What do I need to change? -
Django not displaying image with correct settings
I'm trying to make a video/thumbnail model for displaying some videos. It shows the video and I can access the video file (FileField) in the browser, however, I get a 404 error for the thumbnail (ImageField). Since I can access the videos, I assume the media settings are working just fine. def get_video_upload_path(instance, filename): name, ext = filename.split('.') return os.path.join(f'videos/{instance.slug}.{ext}') def get_video_thumbnail_upload_path(instance, filename): name, ext = filename.split('.') return os.path.join(f'videos/thumbnail/{instance.slug}.{ext}') class Video(base_model): thumbnail = models.ImageField( blank=True, upload_to=get_video_thumbnail_upload_path) video = models.FileField( upload_to=get_video_upload_path) -
dynamic passing fields and look up types and values in Q objects
this is to filter a competition start date and end date in a the range provided by the user, below is the code that is working for the same but I want to supply field names (here:deadlines__start_date) and look_up types (here: __lte, __gte). and the user supplied range fields self.start_date and self.end_date. return qs.filter((Q(deadlines__start_date__gte=self.start_date) & Q(deadlines__end_date__lte=self.end_date)) |Q(deadlines__start_date__lte=self.start_date) & Q(deadlines__end_date__lte=self.end_date) & Q(deadlines__end_date__gte=self.start_date)) | (Q(deadlines__start_date__lte=self.start_date) & Q(deadlines__end_date__gte=self.end_date)) | (Q(deadlines__start_date__gte=self.start_date) & Q(deadlines__end_date__gte=self.end_date) & Q(deadlines__start_date__lte=self.end_date)) ) this was working fine but now I want to send field names and look_up types and values to be compared dynamically, but not finding any solution. ``` I tried doing it like below: kwargs0 = {str('%s__gte' % (start_field)) : str('%s' % self.start_date)} kwargs1 = {str('%s__lte' % (end_field)) : str('%s' % self.end_date)} kwargs2 = {str('%s__lte' % (start_field)) : str('%s' % self.start_date)} kwargs3 = {str('%s__lte' % (end_field)) : str('%s' % self.end_date)} kwargs4 = {str('%s__gte' % (end_field)) : str('%s' % self.start_date)} kwargs5 = {str('%s__lte' % (start_field)) : str('%s' % self.start_date)} kwargs6 = {str('%s__gte' % (end_field)) : str('%s' % self.end_date)} kwargs7 = {str('%s__gte' % (start_field)) : str('%s' % self.start_date)} kwargs8 = {str('%s__gte' % (end_field)) : str('%s' % self.end_date)} kwargs9 = {str('%s__lte' % (start_field)) : str('%s' % self.end_date)} q_object= Q() q_object.add(Q(**kwargs0), Q.AND) q_object.add(Q(**kwargs1), …