Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        Can't change the src of un image in javascript in djangoSo I have a javascript file that I try change the src of a image with in django. However, it keeps adding a subdirectory called the directory my image is in (the directory being in the static folder). It looks like this: Root/ Project/ Templates/ games/ game-one.html static/ pre-dev/ behav.js seven.png in my javascript file because i cant use django tags I wrote it like this: document.getElementById('img_eight').src = "static/pre-dev/seven.png" and the image adress then looks like this: https://website.com/pre-dev/static/pre-dev/seven.png I would like to keep it as a js file, and I want to keep my images where they are I have tried moving my behav.js a directory down. but it gives me the same output. no matter what I change the src in my javascript file to I always get /pre-dev/. Any help would be great.
- 
        google cloud kubernetes ingress not redirecting to httpsi deployed a django application in google cloud kubernetes, its all working i can access my site from https and use it. but when i type in the url the domain it opens with http, if i write https i can access too, i searched a lot and tried a lot of stuff in the internet still no success. there is a annotation kubernetes.io/ingress.allowHTTP: "false" # <-- this one this works disableing the http access, but i want to redirect to https not blocking, if i write in the browser url my domain it goes to http first. its all working the ssl and nginx ingress, i just can't redirect the access from http to https. here is my nginx ingress apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: django-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / kubernetes.io/ingress.global-static-ip-name: django-ip spec.ingressClassName: "nginx" nginx.ingress.kubernetes.io/force-ssl-redirect: "true" # <--- this one is not working nginx.ingress.kubernetes.io/backend-protocol: "HTTPS" nginx.ingress.kubernetes.io/use-forwarded-headers: "true" spec: tls: - hosts: - example-django.com secretName: django-certs defaultBackend: service: name: django-svc port: name: django-core-http rules: - host: example-django.com http: paths: - path: / pathType: Prefix backend: service: name: django-svc port: name: django-core-http tried annotations kubernetes.io/ingress.allowHTTP: "false" nginx.ingress.kubernetes.io/force-ssl-redirect: "true" nginx.ingress.kubernetes.io/ssl-redirect: "true"
- 
        Django: create an object with m2m fields using class based viewsI'm completely stuck, I want to know the right way to save an object that has m2m fields. It works with the admin site (not quite right: a field that should be chosen randomly is chosen through a multiplechoicefield but at least the instance is created ) but not the CreateView (nothing happens no object is created) models.py class Foo(models.Model): #this field is chosen with CheckboxSelectMultiple bar = models.ManyToManyField(Bar) #this field is supposed to be calculated according to the previous choices baz = models.ManyToManyField(Baz) I tried overriding save method but it did not work . forms.py class FooForm(forms.ModelForm): bar = forms.ModelChoiceField(Bar.objects.all()) def save(self, *args, **kwargs): adding = self.instance._state.adding instance = super().save(*args, **kwargs) super().save(*args, **kwargs) if adding: instance.baz.add( *Baz.objects.filter(bar=instance.bar) .values_list('id', flat=True) .order_by('?') ) return instance I also tried (commit = False ) and save_m2m().
- 
        Django query: transform two for loops into a querysetI have 3 simple models: from django_better_admin_arrayfield.models.fields import ArrayField class BuildItem(models.Model): base = models.ForeignKey(Item, on_delete=models.CASCADE) level = models.IntegerField(default=1) mandatory_skills = ArrayField(models.IntegerField(null=True, blank=True), default=list) class Item(BaseModel): name = models.CharField(max_length=100) class Skill(BaseModel): item = models.ForeignKey(Item, on_delete=models.CASCADE, blank=True, null=True, related_name="skills") effect = models.IntegerField(null=True, blank=True) value = models.IntegerField(null=True, blank=True) I would like to retrieve the sum of the value fields of the skills multiply by the level field of builditem, where the pk fields of the skills are in the mandatory_field list, if the effect field of skill is equal to 1. I wrote some code that works with for loop: array_life = [] for builditem in BuildItem.objects.all(): for skill in builditem.base.skills.all(): if skill.pk in builditem.mandatory_skills: if skill.effect == 1 and skill.value < 2: array_life.append(skill.value * builditem.level) sum_life = sum(array_life) I would like to transform this code into a queryset. (I tried many things but without success) Can anyone help me ?
- 
        Using Celery tasks in Django to update aggregated dataIn my Django project, I have a use case where I have some complex Python functions which are computationally expensive: they involve numerous calculations based on a recurrence relation. They are already well optimized but still take a few seconds to run in some cases. In this context, I'm thinking about using Celery tasks to carry out the calculations and to update aggregated data in dedicated tables of my PostgreSQL database. However, I have a feeling it's not going to be easy to ensure the integrity of the data and to avoid unnecessary calculations. Race conditions and unreliable error handling / retry mechanisms are some of the pitfalls I have in mind. What are the best practices in this case? What do I need to pay particular attention to? Are you aware of open source Django projects doing something similar? I'm using Django 4.2, PostgreSQL 15, Redis 7.2 (as a cache), Celery 5.3, RabbitMQ 3.12 (as a broker).
- 
        Running ChannelsLiveServerTestCase does not create database for browserI tried using pytest to test my frontend Django code with Selenium. In order to do that, a server has to be mocked which is when I stumbled upon this StackOverflow question, asking for the ChannelsLiveServerTestCase equivalent for pytest. Since the code didn't work when browsing to the server, showing the yellow Django error page (connection to server at "127.0.0.1", port 5432 failed: FATAL: database "test" does not exist), I tried isolating the issue by removing complexity and using unittest's ChannelsLiveServerTestCase instead, following channels official tutorial. It however yielded the same results. It seems like the database is not being created properly for the frontend. What's weird is, that within the function, database calls can be made normally and the test database exists (checked with pdb). But as soon as the web server is browsed to using Selenium, the yellow error page shows up again – almost as if the asgi server is running in a completely different thread, unable to access the database? I trimmed down the issue to the minimum and created a small repository for easily reproducing the issue: https://github.com/alfonsrv/django-asgitest Any idea where I'm going wrong? Thanks
- 
        Django widget won't change input to dateIt should be so simple. I'm following all the rules and all the answers from previous questions but it still won't happen. I have a Bottle model, that has it's own inline formset form to it's parent Wine. The date on which I bought the bottle, should show up as a standard date picker. I cannot for the life of my figure out where it goes wrong. The input type should change from "text" to "date", but it won't. I'm using crispy forms and bootstrap 5, but disabling those also does nothing. My models (only relevant models shown): from django.db import models from django.conf import settings from django.utils import timezone from django.contrib import admin from django.forms import ModelForm class Wine(models.Model): producer = models.ForeignKey(Producer, null=True, blank=True, on_delete=models.CASCADE, default=0) name = models.CharField(max_length=200) year = models.IntegerField(blank=True, null=True) alcohol = models.FloatField(blank=True, null=True) grape = models.ManyToManyField(Grape) colour = models.ForeignKey(Colour, null=True, blank=True, on_delete=models.CASCADE, default=0) wine_type = models.ForeignKey(WineType, null=True, blank=True, on_delete=models.CASCADE, default=0) notes = models.TextField(max_length=2000, blank=True, null=True) wishlist = models.BooleanField(default=False) def __str__(self): return self.name def get_bottles(self): a = [] for bottle in self.Bottle.all(): a.append((bottle.date_bought)) return a def available_bottle(self): number = self.Bottle.filter(available=True).count() return number class Bottle(models.Model): wine = models.ForeignKey(Wine, related_name='Bottle', on_delete=models.CASCADE) date_bought = models.DateField(null=True) bottleprice = models.CharField(max_length=200, blank=True,) …
- 
        dj_rest_auth password reset serializer is not workingI have followed this guide and also tried this stackoverflow post but for some reason none of them seem to pick up anything from my custom serializer for password reset. I have implemented the custom serializer like this: accounts/urls.py from django.urls import include, path from .views import check_user_email from dj_rest_auth.views import PasswordResetConfirmView, PasswordResetView from django.views.generic import TemplateView urlpatterns = [ path( "password/reset/confirm/<slug:uidb64>/<slug:token>/", PasswordResetConfirmView.as_view(), name="password_reset_confirm", ), path("", include("dj_rest_auth.urls")), # path("registration/", include("dj_rest_auth.registration.urls")), path("check-user-email/", check_user_email), ] accounts/serializer.py from allauth.account.utils import ( filter_users_by_email, user_pk_to_url_str, user_username, ) from allauth.utils import build_absolute_uri from django.contrib.sites.shortcuts import get_current_site from allauth.account.adapter import get_adapter from allauth.account.forms import default_token_generator from allauth.account import app_settings from dj_rest_auth.forms import AllAuthPasswordResetForm from dj_rest_auth.serializers import PasswordResetSerializer from rest_framework import serializers class CustomAllAuthPasswordResetForm(AllAuthPasswordResetForm): def clean_email(self): """ Invalid email should not raise error, as this would leak users for unit test: test_password_reset_with_invalid_email """ email = self.cleaned_data["email"] email = get_adapter().clean_email(email) self.users = filter_users_by_email(email, is_active=True) return self.cleaned_data["email"] def save(self, request, **kwargs): current_site = get_current_site(request) email = self.cleaned_data["email"] token_generator = kwargs.get("token_generator", default_token_generator) for user in self.users: temp_key = token_generator.make_token(user) path = f"I basically want to add frontend url here/{user_pk_to_url_str(user)}/{temp_key}/" url = build_absolute_uri(request, path) # Values which are passed to password_reset_key_message.txt context = { "current_site": current_site, "user": user, "password_reset_url": url, "request": request, …
- 
        How to edit data in crud operations in djangoI am trying to make CRUD app in django I am trying to collect data from form and trying to display the data in form of tables So the user can read, delete, update or delete the data I completed other 3 operation but I am not able to find the error in update table operation I am attaching my code below please help me thankyou I am trying to use bootstrap models to edit the data, however on clicking the edit button the popup is not showing, I am expecting to edit the data once is displayed in form of tables INDEX.HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="../static/assets/css/all.min.css"> <link rel="stylesheet" href="../static/assets/css/main-style.css"> <link rel="stylesheet" href="../static/assets/css/responsive.css"> </head> <body> {% if messages %} {% for message in messages %} <div class="alert " role="alert"> <strong>{{ message }}</strong> </div> {% endfor %} {% endif %} <div class="main-wrapper"> <div class="container"> <div class="main-inner-wrapper"> <h1>Please List The Task with title,description and Duedate</h1> <div class="task-table"> <form class="row g-3" action="/" method="post"> {% csrf_token %} <div class="col-md-12"> <label for="title" class="form-label">Title</label><br> <input type="text" class="form-control" id="title" aria-describedby="title" name="title"> </div> <div class="col-md-12"> <label for="description" class="form-label">Description</label> <br> <textarea class="form-control" aria-label="With textarea" name="description"></textarea> </div> <div class="col-md-12"> …
- 
        I'm getting "Not Found The requested resource was not found on this server." while dynamic URL routingI have just started learning django and I'm following "Traversy Media's" django course, I am facing issues with Dynamic URL routing. Below is my urlpatterns: urlpatterns = [ path("", views.home, name="home"), path('room/<str:pk>/', views.room, name="room"), ] And the views for room: def room(request, pk): return render(request, 'base/room.html') When I'm following "http://127.0.0.1:8000/room/1/" I am getting server error 505. I was getting few other issues before, I tried to search and changed in "DEBUG = True" and "ALLOWED_HOSTS = ['*']" I am stuck here please help out.
- 
        Django translate input field placeholderI have a placeholder in the search bar form. I want to translate it to the user's selected language. I tried to use the {% translate 'message to translate' %} but only get the first word shown in the bar (maybe a problem with the quoatation marks?). The html file: <form class="form_search"> {% csrf_token %} <div class="form-group input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-search" style="color:black"></i></span> <input type="search" class="form-control home_search rounded-end" placeholder= {% translate "placeholder text here nicely..." %} name='keyword' id='inputsearch'> </div> </form> The views.py file: def search_home(request): return render(request, 'search_home.html',context) Passing it from context does not work either. from django.utils.translation import gettext_lazy as lazy_ def search_home(request): context = {'placeholder_search':lazy_('some placeholder here to be translated...')} return render(request, 'search_home.html',context) <form class="form_search"> {% csrf_token %} <div class="form-group input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-search" style="color:black"></i></span> <input type="search" class="form-control home_search rounded-end" placeholder={{context.placeholder_search}} name={{context.placeholder_search}} id='inputsearch'> </div> </form> Anyone knows how to translate a placeholder?
- 
        ProgrammingError: more than one row returned by a subquery used as an expressionI have this function def with_items_photos(self): photos_subquery = Photo.objects.filter( object_id=OuterRef('pk'), content_type=ContentType.objects.get_for_model(DeliveryItem) ).values('pk') return self.annotate( photos=Subquery( photos_subquery.annotate( photo_ids=ArrayAgg('pk') ).values('photo_ids') ) ) I would like to get array of photo_ids for each item but get an error
- 
        Problem to load the Css on a Django application deployed in VercelI've created an application in django, but when I deployed it in Vercel, the HTML works just fine, but the CSS don't load. I pasted some of my project below, please ask me if you need any other files to make the necessary changes. Project Structure C:. │ .gitignore │ db.sqlite3 │ manage.py │ README.md │ requirements.txt │ vercel.json │ ├───.mypy_cache │ │ .gitignore │ │ CACHEDIR.TAG │ │ │ └───3.11 │ │ @plugins_snapshot.json │ │ abc.data.json │ │ abc.meta.json │ │ builtins.data.json │ │ builtins.meta.json │ │ codecs.data.json │ │ codecs.meta.json │ │ contextlib.data.json │ │ contextlib.meta.json │ │ dataclasses.data.json │ │ dataclasses.meta.json │ │ enum.data.json │ │ enum.meta.json │ │ genericpath.data.json │ │ genericpath.meta.json │ │ io.data.json │ │ io.meta.json │ │ manage.data.json │ │ manage.meta.json │ │ ntpath.data.json │ │ ntpath.meta.json │ │ pathlib.data.json │ │ pathlib.meta.json │ │ posixpath.data.json │ │ posixpath.meta.json │ │ re.data.json │ │ re.meta.json │ │ sre_compile.data.json │ │ sre_compile.meta.json │ │ sre_constants.data.json │ │ sre_constants.meta.json │ │ sre_parse.data.json │ │ sre_parse.meta.json │ │ subprocess.data.json │ │ subprocess.meta.json │ │ sys.data.json │ │ sys.meta.json │ │ types.data.json │ │ types.meta.json │ │ typing.data.json │ │ typing.meta.json │ │ typing_extensions.data.json │ │ typing_extensions.meta.json …
- 
        Need to add fields of another serializer to the serializer. I pass only id and amount, and json should return in responseThere is a recipe serializer that needs to receive ingredients, which is also handled by another serializer. The recipe and ingredient models are connected through a Many-to-Many relationship. Only the ingredient's ID and quantity need to be passed, and that's what I receive in response. { "ingredients": [ "Invalid type. The primary key value was expected, dict was received." ] } I need to somehow override the create method differently. # serializers.py class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = ('id', 'name', 'measurement_unit') class RecipeCreateSerializer(serializers.ModelSerializer): tags = serializers.PrimaryKeyRelatedField( many=True, queryset=Tag.objects.all() ) author = UserSerializer ingredients = serializers.PrimaryKeyRelatedField( many=True, queryset=Ingredient.objects.all() ) image = Base64ImageField() class Meta: model = Recipe fields = '__all__' read_only_fields = ('author',) def create(self, validated_data): tags = validated_data.pop('tags') ingredients = validated_data.pop('ingredients') recipe = Recipe.objects.create(**validated_data) for tag in tags: current_tag, status = Tag.objects.get_or_create(**tag) TagsInRecipe.objects.create(tag=current_tag, recipe=recipe) for ingredient in ingredients: current_ingredient, status = Ingredient.objects.get_or_create(**ingredient) IngredientsInRecipe.objects.create( ingredient=current_ingredient, recipe=recipe, amount=ingredient['amount'] ) return recipe expected { "id": 0, "tags": [ {} ], "author": { "email": "user@example.com", "id": 0, "username": "string", "first_name": "Name", "last_name": "Last Name", "is_subscribed": false }, "ingredients": [ { "id": 0, "name": "potato", "measurement_unit": "g", "amount": 1 } ], "is_favorited": true, "is_in_shopping_cart": true, "name": "string", "image": "http://example.org/media/recipes/images/image.jpeg", "text": "string", "cooking_time": …
- 
        Python Protocols and Django ModelsSuppose I have a simple protocol A and a class B which fails to implement that protocol: from typing import Protocol class A(Protocol): def foo(self) -> str: ... class B: pass Mypy will correctly complain when the code below is type checked x: A = B() mypy . error: Incompatible types in assignment (expression has type "B", variable has type "A") If however I have it so that B inherits from django.db.models.Model as follows class A(Protocol): def foo(self) -> str: ... class B(models.Model): pass x: A = B() mypy no longer throws an error when checking the line x: A = B(). I would have expected it to throw an error since B does not (seemingly) implement the A protocol. I assume this must have something to do with some inherited properties of models.Model which makes mypy think that the foo method is there. Does anyone know what's going on here and have advice on how to have mypy check whether or not a Django model implements a protocol? Note that I would prefer that the model did not need to explicitly subclass the protocol.
- 
        CSS styling not displayed when deployed to VercelIm making a Django app that displays a users top tracks and artists, when i deploy this app to vercel i lose all my css styling. Im new to django and developing apps any help would be appreciated! This is my repo: https://github.com/KevinL0206/spotify_stats_project Vercel Site:https://spotify-stats-project.vercel.app/
- 
        Adding fields to a form and a model dynamically in djangoLets say we have a model called SimpleModel and it has an attr connected_field which is ForeignKey of NotSimpleModel i.e. class SimpleModel(models.Model): connected_field = models.ForeignKey('NotSimpleModel', on_delete=models.CASCADE, related_name='connected') class NotSimpleModel(models.Model): ... and we have a form called NotSimpleForm class NotSimpleForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ... class Meta: model = NotSimpleModel fields = '__all__' Well, actually i wanna do a thing where user can dynamically add "connected_field" in the form which is ModelForm of NotSimpleModel, then all the fields, which user added dynamically should be sent to the view and saved to the db (i doesnt insist on ForeignKey, but i guess it gotta be the easiest way to solve it tho)
- 
        changes to my github contributions not showing on my graphInitial repositories count as contributions on my graph but follow up changes do not reflect on my graph however they indicate on my code that modification has been done on GitHub. I have enabled both private and public repository viewing and I ensure I make changes to the same branch in which I committed but still the problem persists. any help would be very much appreciated . Thank you in Advance. i tried creating a new branch and comiting to it but still the changes would not reflect on the graph
- 
        TypeError at /admin/accounts/order/add/ (__str__ returned non-string (type Customer))I wanted to use many to many and many to one with Django. Then I write this codes but when I try to add an Order from Admin Panel I got this error and I cannot find the solution. I hope someone can help me. In the below I share my models.py file I hope it will enough. from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.IntegerField(null=True) email = models.EmailField(null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Tag(models.Model): name=models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): STATUS = ( ('Indoor','Indoor'), ('Out Door', 'Out Door') ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, null=True,choices=STATUS) description = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Pending','Pending'), ('Out for deliver', 'Out for delivery'), ('Delivered', 'Delivered') ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return self.customer I'm watching Dennis Ivy's Django Crash Course Tutorials and I did exactly what he did but he didn't get this error and I wonder what's the problem more than the solution. I …
- 
        Share Docker image via Container Registry - DRF APII prepared API with Django Rest Framework. I am using docker to run my API, everything works fine on my machine. So I just run docker-compose up and I can test API with Swagger in my browser. Now I want my friend to test it locally on his machine. I want to do this by sharing my docker image with Container Registry (GitLab service) and docker-compose file. So his scenario will be: Pulling repo from Registry Container by: docker pull registry.[...] Run: docker-compose up And after that, he can test it. The main goal is to run this API without downloading repo with code - just using docker-compose and Docker image. We then want to run it on VPS. I have already tried to do this but to no avail. Here are the steps I followed: docker login registry.gitlab.com docker build -t registry.gitlab.com/[...]:latest . docker push registry.gitlab.com/[...]:latest . Remove all images and containers related to project. Create new directory and paste there docker-compose file. docker pull registry.gitlab.com/[...]:latest . docker-compose up And then I'm getting error: python: can't open file '/app/manage.py': [Errno 2] No such file or directory What can I do in that situation? Is it even possible to work? …
- 
        Django template dynamically add rows and colums does not workI'm displaying blog list looping through the list in django and the blogs are displayed 3 columns in a row and the rows and columns are dynamically added but it doesn't work yet. <div class="container"> {% for post in post_list %} {% if forloop.counter0|divisibleby:3 %} <div class="row py-5"> {% endif %} <div class="col-md-4 mb-5 pb-5"> <div class="card blog-card my-5"> {% if post.image %} <img src="{{ post.image.url }}" class="card-img-top" alt="Blog Post Image"> {% endif %} <div class="blog-card-text"> <div> <img src="{% static 'blog/images/logo.png' %}" alt="MMDT logo" class="blog-created-img"> <small>{{ post.created_on }}</small> </div> <div class="card-title mb-0"> <h6 class="font-weight-bold">{{ post.title}}</h6> </div> <div class="card-text"> <small>{{ post.author }} | {{ post.view_count }}</small> </div> <div class="card-text"> {{ post.content|slice:":120" | striptags }} <span>...</span> <a href="{% url 'post_detail' post.slug %}" class="mt-0 mb-3"> Read More </a> </div> </div> </div> </div> {% if forloop.counter|divisibleby:3 or forloop.last %} </div> {% endif %} {% endfor %} </div> Any idea to fix this and thanks in advance.
- 
        How to setup azure communication services (email) with djangoI'm working on a django project where I want to send emails for account creation. Particularly, I am using djoser. I want to integrate azure communication services and their email service to send emails but I don't know how to do that. Can someone tell me how to use azure communication services in django and djoser. I tried using the endpoint connection string and access keys as password but it did not work.
- 
        How do depoy a Django Project on a Webgo serverim new to Django i did made a tutorial from w3school, now im at the point to deploy the project but i dont want to deploy the project on my own webhost at Webgo. On the Server there is python and modWSGI. But all tutorial i had read they there realy complicated to deploy a project. Can somebody help me to deploy my project on that webserver its running with apache. I tried to upload the Project but that was not enought im not sure what to do. The docs are a bit to complicated for me. Thats why i hope sombody can descripe me the approach so a newbie can understand that. I uploaded my project but its not working
- 
        Book a specific appointment on a specific dayI want to book a specific time for the user (start hour and end hour ) and no one else can book at the same time Example Like : John made an appointment on the 5th day of the month at 7 to 8 o'clock i want no one else can booking at the same time and day and i want to check the Period because if someone like john booking start time 5pm to 8pm no one can booking like stat 6pm to 7 pm at the same day How I can Do This in Models Django I could not find a solution to this problem enter image description here im using timing to know how long the booking take and i dont know what can i should do enter the link tow show the image of code
- 
        How can I make the queryset filter `or` conditions dynamically from the array?I have array and try to use this as filter key for database I want to make this dynamically from the array = [AC" ,"BC"] queryset = queryset.filter(Q(username__icontains="AC")| Q(username__icontains="BC")) For example, I try like this below but it is obviously wrong. array = ["AC","BC"] qs = [] for k in array: qs.append(Q(username__icontains=k)) queryset = queryset.filter(qs.join('|')) How can I do this ?