Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SMTPRecipientsRefused at /accounts/signup/ (550)
I have run into a problem with email verification during signup. The problem is: if I register with an existing email, everything works as it should, however, if I try to register with a nonexistent email, I will get an error and the website crashes with the status code 500. I use Django allauth and mail.ru for sending the verification emails. Here is my email configuration in settings.py: EMAIL_HOST = 'smtp.mail.ru' EMAIL_USE_TLS = True EMAIL_PORT = 2525 EMAIL_HOST_USER = os.environ.get('email_address') EMAIL_HOST_PASSWORD = os.environ.get('email_password') DEFAULT_FROM_EMAIL = os.environ.get('email_address') The error message: Exception Type: SMTPRecipientsRefused at /accounts/signup/ Exception Value: {'asd@asd.asd': (550, b'non-local recipient verification failed')} How do I catch that error and avoid 500? Python version: 3.8.6 Django version: 3.1.1 -
Ignore form.is_valid() with multiple submit buttons
Following this thread on how to implement multiple submit buttons for the same form here, I implement a form with two buttons, Confirm and Cancel as following: <form id="item-form" class="item-form-container" method="post"> {{ item_form.as_p }} {% csrf_token %} <button type="submit" class="button-item-order" name="confirm-order">Confirm</button> <button type="submit" class="button-item-order-cancel" name="cancel-order">Cancel</button> </form> In my view, if the button confirm-order is clicked, the view proceeds with validating the form, and process its data. However, if button cancel-order is clicked, I would like for the view to ignore the form validation, since I am not processing any of its data. def item_order_view(request): if request.method == 'POST': item_form = ItemOrderForm(request.POST) if 'confirm-order' in request.POST: if item_form.is_valid(): ... return redirect(reverse(...xxx...)) else: return redirect(reverse(...yyy...)) else: ... return render(request, ...) While the appropriate action is executed based on which button is clicked, the view always validates the form. It means, if I click the cancel-order button without filling the form appropriately, I get the usual validation error. This action return redirect(reverse(...yyy...)) won't execute unless the form is filled properly. How do I bypass / ignore the validation when cancel-order is clicked? -
Best way to speed up Django post requests?
I'm running a local Django server on a virtual machine that is remote interpreted onto a Raspberry Pi. The purpose of the remote connection is to have the Raspberry Pi upload a bunch of data from various sensors to the local server every minute. I'm running into an issue now where the Post request speed is far too slow for the amount of data that will be coming in (Post speed is about one, sometimes two posts a second). I'm assuming this is due to the remote connection and the fact that it is running on a virtual machine as the post speed is exceptional if I run the local server on my physical laptop and post data from a local csv file, not remote interpreted. I'm currently experimenting with the django bulk-create method to post data in bulk instead of hitting the database with every post, but I'm not sure if this will actually speed up the post requests. I'm worried it might just bottleneck the local server. Does anybody know of a good way to speed up these requests? I'm using SQLite3, would switching to POSTGRE or a different database help? -
Automating Django database changes
I'm new to Django, and relatively new to programming in Python. The first project I'm planning to make in Django is going to be a dashboard for monitoring network hosts (access points, switches, routers). I already have classes in Python that can pull the data that I need from the API of the various hosts that I'm intending to monitor. Right now I'm using this data to generate email reports of hosts that are offline. The way I envision this working in Django is building classes in models.py for the various components (our paying clients, routers, access point controllers, access points, switches, etc). These classes will build the database tables and their relationships. From there I planned on running cron jobs with scripts that would manually update these databases with psycopg2. I'd be doing things like adding new entries, deleting old entries, and updating existing ones. This would happen completely separate from the tools that Django provides for database management. Now to the questions: Is there anything outlined above that would not work the way I envision it working? Is there a better way to accomplish what I'm trying to accomplish? I want to have a lot of control regarding … -
Django Heroku, This site can’t be reached, Took too long to respond
I created a Django website around 1 month ago, it was working perfectly fine, but on 8-11-2020 it stopped working (It won't load). I tried things that I could find on the internet but nothing worked as there isn't much about my problem. I tried restarting all dynos and redeploying my website but it didn't work. Can someone tell me how to fix this? -
django models save two auto calculated field
I have this logic in my models, i just want that the result will automatic save in the database class Product(models.Model): unitquantity = models.FloatField(null=True, blank=True) price = models.FloatField(null=True, blank=True, verbose_name="Unit Price") discount_percentage = models.FloatField(max_length=500, null=True, blank=True) discount_price = models.FloatField(null=True, blank=True) Other_discount_percentage = models.FloatField(null=True, blank=True) Other_discount_price = models.FloatField(null=True, blank=True, default=0.0) discount_price_formula = models.FloatField(null=True, blank=True) other_discount_price_formula = models.FloatField(null=True, blank=True) def save(self, *args, **kwargs): self.discount_price_formula = self.price - (self.price * self.discount_percentage) self.other_discount_price_formula = self.discount_price_formula * self.Other_discount_percentage return super(Product, self).save(*args, **kwargs) -
How to access django request using graphene mutation info
I get this error 'WSGIRequest' object has no attribute 'request' PS: snippet is a truncated. Error is coming from info.context.request class Arguments: input = ForgotPasswordInput() ok = graphene.Boolean() message = graphene.String() @staticmethod def mutate(root, info, input=None): try: user = User.objects.get(email=input.get('email')) current_site = get_current_site(info.context.request)``` -
Double forward slash in Django URL causes 404 error
Can someone please advise why I keep getting a forward double slash in my Django URL? Please see the error message below. Please note the forward double slash after polls that causes the page to throw errors Page not found (404) Request Method: GET Request URL: http://157.230.7.149:8000/polls/owner/owner Using the URLconf defined in tutorial2.urls, Django tried these URL patterns, in this order: polls/ [name='index'] polls/ owner [name='owner'] polls/ <int:pk>/ [name='detail'] polls/ <int:pk>/results/ [name='results'] polls/ <int:question_id>/vote/ [name='vote'] admin/ The current path, polls/owner/owner, didn't match any of these. Please see the urlpattern in the urls.py file as well as the function in the views.py file urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('owner', views.owner, name='owner'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] views.py def owner(request): return HttpResponse("Hello, world. 80e4c546 is the polls owner.") Would greatly appreciate any assistance. Thank you -
Flask cannot redirect after receiving post request from Ajax in templates
I want to create a chatroom, in which, if people enter "!exit", then they will get out of the chatroom. The way I implement this idea is that whenever people send "!exit" message, Ajax will send a post request back to the view function. After receiving the request, the view function redirects the user to the homepage. However, right now, I think I can send a post request, since the console prints "success", but the code still does not redirect. This is my code: In chat.html: <head> <title> Chat room </title> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> </head> <body> <script type="text/javascript"> $(document).ready(function() { var socket = io.connect('http://127.0.0.1:5000'); socket.on('message', function(msg) { if (msg=="!exit") { $.ajax({ type : "POST", url : "http://127.0.0.1:5000/chat", data: {data: "Unmatched"}, contentType: 'application/json;charset=UTF-8', success: function() { window.location.href = '/chat' } }); } else { $("#message-display").append('<div>'+ "person: " + msg+'</div>'); } }); $('#sendbutt').on('click', function() { socket.send($('#message-input').val()); $('#message-input').val(''); }); }); </script> <div> Welcome to the chat room. You are chatting with a user. </div> <div> Type "!exit" if you want to stop chatting and return to the homepage. </div> <l id="message-display"> </l> <input type="text" id="message-input"> <button id="sendbutt"> Send </button> </body> </html> In main.py: socketio=SocketIO(app) @app.route('/', methods = ["GET", "POST"]) def homepage(): … -
Django template language query database
I have a list of cities,In the city list, I also need to query the hotels in each city,this's my code,use ‘city.hote_set.all’,But the list is all hotels,How to use filter query? For example:city.hotel_set.filter This's my code {% for city in city_list %} <a>{{ city.name }}</a> {% for hotel in city.hote_set.all %} <a>{{hote.name}}</a> {% endfor %} {% endfor %} -
Connect to a Django postgres database remotely
I am using Postgres for a production system, and I would like to be able to connect to this database remotely to integrate the information with other systems. My configuration looks classic like follows : ALLOWED_HOSTS = ['myipgoeshere', 'mydomainnamegoeshere'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dbname', 'USER': 'dbuser', 'PASSWORD': 'dbpassword', 'HOST': 'localhost' } } Now, if I want to connect to this database from another machine what should I use as hostname on that machine ? I need to provide information about Host Database Port User Password In my config, host is localhost, but I cannot use this as remote hostname, should we use the IP address instead ? Also will the port be the default postgres one ? Any hint would be much appreciated -
Adding Parameters to Existing Django Model Fields
I was trying to create a custom Django model field, where the new field will essentially be the same as a CharField but has an additional boolean attribute -- for now, just call it "public." I have looked up this article on adding custom attributes, but I don't like the method described as it required me to construct a brand-new model from scratch. It is a hassle considering the number of functions I must implement just to add a parameter, which is all listed in the docs. To clarify my objectives, I will like to declare this field as such: somefield = BoolCharField(public=True, max_length=100, blank=True) # Note that public is NOT a default CharField attribute The documentation stated that I am allowed to extend new fields from existing fields, but the section isn't elaborated. Can anyone please provide me with an example of how I should implement my field? Thank you very much. -
how to import django admin inlines to CreateView?
this is my CreateView class PizzaCreateView(PermissionRequiredMixin,SuccessMessageMixin,CreateView,): model = Pizza fields = ['name','price','pizza_description','toppings','Admin.PizzaImageInline'] action = 'Add pizza' success_url = reverse_lazy('pages:home') permission_required = 'pizzas.add_pizza' success_message = '"%(name)s" was created successfully' this is my admin.py class PizzaImageInline(admin.TabularInline): model = PizzaImage extra = 3 class PizzaAdmin(admin.ModelAdmin): inlines = [ PizzaImageInline, ] admin.site.register(Pizza, PizzaAdmin) how do i can transfer PizzaAdmin to my view form -
Creating a Pizzeria program in python and postgresql
I am new to python and would like to create a Pizzeria Program using python and PostgreSQL that looks something like this. Output: Welcome to Jeff's Pizzeria Here's our Pizza menu: Pizza Types(cost per sale): A) Pizza A (has Topping A, B, and C): $ 30.50 B) Pizza B (has Topping A only): $ 24.50 C) Pizza C (has Topping B and C only): $ 28.50 Toppings Type(cost per pizza): Topping A: $ 5.99 Topping B: $ 11.99 Topping C: $ 8.99 Please input a letter and number and press enter to select a pizza item. Input 'add' to finish your order. Input 'another' to add another pizza order. Input 'report' to view all of the pizza orders made today. A You selected Pizza A. That would cost $30.50. 1 You selected Topping B! That would cost $11.59. Add Your pizza order is added and your total bill is $42.09. Do you want to order pizza again? Y/N N Thank you for buying Jeff's Pizzeria Press 'another' to order pizza again or type 'report' to view all of the pizza orders made today report Pizzas sold today: 5 Pizzas per type sold: 5 Total of money spent: $204.85 Money earned … -
Django - Static file, image, wont appear
I'm learning django. It was working in the beginning of my project, but now imgs from static just dont appear. I've try to run collecstatic and work with STATIC_ROOT. Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/upload/' MEDIA_ROOT = os.path.join(BASE_DIR, 'upload') Home.html {% load static %} <img scr="{% static 'img/cart-icon.png' %}"> Files dir -
product_list() got an unexpected keyword argument 'product_id'
I'm getting the message in the title for product_id, but I think I've used it correctly on both product_form() and on its path. Can someone help please? I was gonna name the variable id, but before I could even test it pylint was having trouble with it, so I changed to product_id. views.py def product_form(request, product_id=0): """Formulário de Cadastro de Produtos""" if request.method == "GET": if product_id==0: form = ProductForm() else: product = Product.objects.get(pk=product_id) form = ProductForm(instance=product) return render(request, "product_register/product_form.html", {'form': form}) else: form = ProductForm(request.POST) if form.is_valid(): form.save() return redirect('/product') urls.py urlpatterns = [ path('', views.product_list, name='product_list'), path('product-form/', views.product_form, name='product_insert'), path('product-form/<int:product_id>/', views.product_list, name='product_update'), path('category-form/', views.category_form, name='category_insert') ] html {% extends "product_register/base.html" %} {% block content %} <table class="table table-borderless"> <thead class="border-bottom font-weight-bold"> <tr> <td> Nome </td> <td> Descrição </td> <td> Preço </td> <td> Categoria </td> <td></td> </tr> </thead> <tbody> {% for product in product_list %} <tr> <td> {{product.name}} </td> <td> {{product.description}} </td> <td> {{product.price}} </td> <td> {% for category in product.category.all %} {{category.name}}, {% endfor %} </td> <td> <a href="{% url 'product_update' product.id %}" class="btn text-secondary px-0"> <i class="far fa-edit fa-lg"></i> </a> </td> </tr> {% endfor %} </tbody> </table> {% endblock content %} -
'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I am working on project using Django and React using Rest Framework. I have set CORS_ALLOW_ALL_ORIGINS=True in settings.py still i am getting error Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/encrypt/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I am using axios to post and get request. Suprisingly even after error post request is made but get request fails. This is react file using axios sendImage =()=> { this.activateSpinner() let formData = new FormData() formData.append('to_be_hidden', this.state.files[0], this.state.files[0].name) formData.append('used_to_hide', this.state.files[1], this.state.files[1].name) axios.post('http://127.0.0.1:8000/api/encrypt/', formData, { headers: { 'accept': 'application/json', 'content-type': 'multipart/form-data' } }) .then(resp=>{ this.getImageClass(resp) console.log(resp.data.id) }) .catch(err=>{ console.log("Code broke at send image") console.log(err) }) } getImageClass =(obj)=> { axios.get(`http://127.0.0.1:8000/api/encrypt/${obj.data.id}/`, { headers: { 'accept': 'application/json', } }) .then(resp=>{ this.setState({recentImage:resp}) console.log(resp) }) .catch(err=>{ console.log("Code broke at get image") console.log(err) }) this.deactivateSpinner() } -
Decoding problem with files and serializers
In my API using Django Rest Framework I have a function based view for part of a sign up process for using Stripe. The view succefully sends everything to stripe and updates my sites database with the proper information, but when trying to return the serializer data I get this error: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Assuming it has to do with the files needed for personal identification Here is the view: @api_view(['POST']) def StripePersonalOnboard(request): serializer = StripePersonalSerializer(data=request.data) profile = get_object_or_404(Profile, user=request.user) if serializer.is_valid(): phone_number = serializer.validated_data.get('phone_number') ss_number = serializer.validated_data.get('ss_number') id_front = serializer.validated_data.get('id_front') id_back = serializer.validated_data.get('id_back') try: stripe.api_key = settings.STRIPE_TEST_SEC_KEY id_front_file = stripe.File.create( purpose='identity_document', file=id_front ) id_back_file = stripe.File.create( purpose='identity_document', file=id_back ) stripe.Account.modify( profile.stripe_acc_id, individual= { 'phone': phone_number, 'id_number': ss_number, 'verification': { 'document': { 'back': id_back_file, 'front': id_front_file } } } ) profile.stripe_id_front_tkn = id_front_file.id profile.stripe_id_back_tkn = id_back_file.id profile.save(update_fields=['stripe_id_front_tkn', 'stripe_id_back_tkn']) return Response(serializer.validated_data) except stripe.error.InvalidRequestError as e: #invalid parameters were provided return Response(e.error.message) else: return Response(serializer.errors) -
'NoneType' object is not subscriptable I've have been studying this one all morning
Trying to get a list of products from my database def bad_view(request, *args, **kwargs): print(dict(request.GET)) my_request_data = dict(request.GET) new_products = my_request_data.get("new_products") print(my_request_data, new_products) if new_products[0].lower() == "true": print("new product") Products.objects.create(title=my_request_data.get('title')[0], content=my_request_data.get('content')[0]) return HttpResponse("Dont do this") I keep getting : if new_products[0].lower() == "true": TypeError: 'NoneType' object is not subscriptable [08/Nov/2020 17:25:38] "GET /bad-view-dont-use/ HTTP/1.1" 500 67144 -
select data returned from a for loop in django template
I was able to get data from our flights API which get flights data from Amadeus . i was able to display this data on django template using a for loop: <form action="#" method="post" > {% if ctx.flight_details_error %} {{ctx.flight_details_error}} {% else %} {% for obj in ctx.flight_details %} <div class="w-layout-grid add-flight-result" style="width: 70em;margin-left: 10px;"> <!-- --> <div class="airline-logo-wrapper"> <!-- <p>{% if obj.atob_flight.indirect_flights %} {{obj.atob_flight.indirect_flights.0.airline_code}} {{obj.atob_flight.indirect_flights.0.flight_number}} {% else %}{{obj.atob_flight.airline_code}} {{obj.atob_flight.flight_number}}{% endif %}</p> --> {% if obj.atob_flight.indirect_flights %}<img src="/static/images/airline/{{obj.atob_flight.indirect_flights.0.marketing_code}}.png" alt="" class="airline-logo">{% else %}<img src="/static/images/airline/{{obj.atob_flight.marketing_code}}.png" alt="" class="airline-logo">{% endif %} </div> <div class="depart-date-time-wrapper"> <div class="depart-time">{% if obj.atob_flight.indirect_flights %} {{obj.atob_flight.indirect_flights.0.time_of_departure}}{{forloop.counter}}{% else %}{{obj.atob_flight.time_of_departure}} {% endif %}</div> <div class="depart-date">{% if obj.atob_flight.indirect_flights %}{{obj.atob_flight.indirect_flights.0.date_of_departure}}{% else %}{{obj.atob_flight.date_of_departure}}{% endif %}</div> <div class="airport">{% if obj.atob_flight.indirect_flights %}{{obj.atob_flight.indirect_flights.0.source_airport.city}} ({{obj.atob_flight.indirect_flights.0.source_airport.airportName}}){% else %}{{obj.atob_flight.source_airport.city}} ({{obj.atob_flight.source_airport.airportName}}) {% endif %}</div> </div> <div class="stops-fliter-wrapper"> <div class="flight-duration">{{obj.atob_flight.elapsed_flying_time}}</div> <img src="/static/images/direct-arrow.png" alt=""> {% if obj.atob_flight.indirect_flights %} <div class="stop-fliter-flight">({{ obj.atob_flight.indirect_flights|length }}-Stop)</div> {% else %} <div class="stop-fliter-flight">(Non-Stop)</div> {% endif %} </div> <div id="w-node-5fcf7c85721e-18943613" class="arrival-date-time-wrapper"> <div class="arrival-time">{% if obj.atob_flight.indirect_flights %}{% if obj.atob_flight.indirect_flights|length == 4 %}{{obj.atob_flight.indirect_flights.3.time_of_arrival}}{% elif obj.atob_flight.indirect_flights|length == 3 %}{{obj.atob_flight.indirect_flights.2.time_of_arrival}}{% else %}{{obj.atob_flight.indirect_flights.1.time_of_arrival}}{% endif %}{% else %}{{obj.atob_flight.time_of_arrival}}{% endif %}</div> <div class="arrival-date">{% if obj.atob_flight.indirect_flights %}{% if obj.atob_flight.indirect_flights|length == 4 %}{{obj.atob_flight.indirect_flights.3.date_of_arrival}}{% elif obj.atob_flight.indirect_flights|length == 3 %}{{obj.atob_flight.indirect_flights.2.date_of_arrival}}{% else %}{{obj.atob_flight.indirect_flights.1.date_of_arrival}}{% endif %}{% else %}{{obj.atob_flight.date_of_arrival}}{% endif %}</div> <div class="airport">{% if obj.atob_flight.indirect_flights … -
django get previous url
i am using request.META.get('HTTP_REFERER') to get the previous url , it works fine when the url is inside my website but when the url is outside my website (facebook) it returns none and the template tag for HTTP_REFERER return the current url with a facebook parameter : http://127.0.0.1:8000/order_analytics/?fbclid=IwAR2nLUSZAAmJOdjS7UPw_jol14ZpOEW7QjxrUqrisFk1msWa_L9nZPWqyDg what i want to get is https://www.facebook.com/ -
Django show multiple pictures of an item in HTML
I can add pictures to my admin page but I want to figure out how to display them all on my main html page. Below code shows only the first image that I uploaded to the admin page and ignores the rest. models.py class Product(models.Model): PN = models.CharField(max_length=100, image = models.FileField(blank=True) def __str__(self): return self.name class PostImage(models.Model): post = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) images = models.FileField(upload_to = 'products/') def __str__(self): return self.post.name views.py from .models import Product, PostImage def product_detail(request, PN): product = get_object_or_404(Product, PN=PN, available=True) photos = PostImage.objects.filter(product=product) return render(request, 'product/product_detail.html', {'product':product, 'photos':photos}) product_detail.html {% block content %} {% for obj in object %} <div id="item"> {% for image in obj.postimage_set.all %} <img src="{{ MEDIA_URL }} {{ obj.image.url }}" /> {% endfor %} </div> {% endfor %} {% endblock %} -
Make AM/PM Lowercase System-wide in Django Settings
I've seen this post, but it's not quite what I'm after. What I'm looking to do instead is change the way AM and PM are displayed system-wide, by configuring this in Django settings. Something like this (which doesn't work): USE_L10N = False DATETIME_FORMAT = 'Y-m-d, f {0}'.format('A'.lower()) I'd like the Django admin timestamps to look like this, for example: 2020-10-20, 9:15 pm I see that by default these are formatted how I want if the locale was de_DE. Can I set this for only the date time, without affecting other language settings? I also noticed that if it weren't for adhering to AP style, using 'a' would get me what I want. I also tried an answer give here (@mrts), but this yields the same as what I already have. This is somewhat academic, as I would be satisfied with 2020-10-20, 9:15 PM (achieved by setting USE_L10N=False and DATETIME_FORMAT = 'Y-m-d, f A'), but I'm still curious what is the best way to do this. -
How to create a relation from one table entry to other table entries?
I am creating a small Django app which has a model of exercise like in sports/fitness. class Exercise(models.Model): name = models.CharField(max_length=200, null=True) description = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) muscles = models.ManyToManyField(Muscle, blank=True) equipment = models.ManyToManyField(Equipment, blank=True) There are different entries in the exercise table. Something like a Push-Up, Knee-Push Up, Wall Push-Up, Diamant Pust-Up and others. I want to somehow have a relation between some exercises. For example, when you can not perform a single Push Up what exercise could be an easier progression (Knee Push-Up). If you can not do Knee Push-Ups, then check out the next easier one. But also the reverse is possible. Your think regular Push-Ups are easy, checkout the harder ones. Would using a column like "easier_progression" and saving the easier exercise or exercises with the foreign key a good choice? What about the reverse case: A progression which is harder. Should I implement this as well or just use "is easier" and abstract that in code when adding a harder progression since it is just the reverse case but from the other entry? -
Django Filter using multiple Foreign Keys
I am trying to make a django filter to filter values based on multiple models connected using foreign keys. My models looks like: model test1(models.Model): name=models.CharField() ..........some more fields models test2(models.Model): name = models.CharField() code = models.CharField() models test3(models.Model): name = models.CharField() code = models.CharField() model test4(models.Model): first = models.ForeignKey(test1, on_delete=models.CASCADE) second = models.ForeignKey(test2, on_delete=models.CASCADE, blank=True, null=True) third = models.ForeignKey(test3, on_delete=models.CASCADE, blank=True, null=True) I want to make a filter from test1 to filter test2 and test3 values. Also, one and only one of the second or third field in model test4 will be null each time. Currently I was trying to use django_filters but not able to lookup these fields. How can I approach