Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to get the specific reviews from a different model Django
I am making a review section for my record company, but I have a hard time figuring out how I can get the specific reviews for the specific album, I pass in an id to a template called "Albumin" to get the exact album, but how do I get the reviews? models: class albums(models.Model): title = models.CharField(max_length=100) description = models.TextField() release_date = models.CharField(max_length=10) artist = models.CharField(max_length=100) genre = models.CharField(choices=GENRE_CHOICES, max_length=20) image = models.ImageField(default='default2.jpg', upload_to='album_pics') slug = models.SlugField() def __str__(self): return self.title class ReviewRating(models.Model): album = models.ForeignKey(albums, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=100, blank=True) review = models.TextField(max_length=500, blank=True) rating = models.FloatField() ip = models.CharField(max_length=20, blank=True) status = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subject or f"ReviewRating #{self.pk}" views: def albuminfo(request, id): album = albums.objects.get(id = id) reviews = ReviewRating.objects.all() return render(request, "home/AlbumInfo.html", {'album' : album, 'reviews' : reviews}) def submit_review(request, album_id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': try: reviews = ReviewRating.objects.get(user__id=request.user.id, album__id=album_id) form = ReviewForm(request.POST, instance=reviews) form.save() messages.success(request,'Your review has been updated') return redirect(url) except ReviewRating.DoesNotExist: form = ReviewForm(request.POST) if form.is_valid(): data = ReviewRating() data.subject = form.cleaned_data['subject'] data.review = form.cleaned_data['review'] data.rating = form.cleaned_data['rating'] data.ip = request.META.get('REMOTE_ADDR') data.album_id = album_id data.user_id = request.user.id data.save() messages.success(request, 'Your review has … -
Safe to use django ORM from gevent greenlets or threads under WSGI?
I think the answer is “yes” but is there some official documentation I can point to? I try to inspect what is happening under the hood but have trouble convincing myself -- see this code snippet, which compares thread locals and DB connection objects between gevent greenlets and gevent threads: import time from django import db import gevent from gevent.pool import Pool from gevent.threadpool import ThreadPool def my_view(request): pool = Pool(4) start = time.time() for _ in range(4): def foo(x): time.sleep(x) print(db.connections['default']) print(threading.local()) pool.spawn(foo, 1) pool.join() delay = time.time() - start print('Running "time.sleep(1)" 4 times with 4 greenlets. %.3fs' % delay) threadpool = ThreadPool(4) start = time.time() for _ in range(4): def bar(x): time.sleep(x) print(db.connections['default']) print(threading.local()) threadpool.spawn(bar, 1) threadpool.join() delay = time.time() - start print('Running "time.sleep(1)" 4 times with 4 threads. %.3fs' % delay) I guess the django ORM is thread-safe, but I also want to make sure that each thread is getting its own DB connection. This appears to be the case from the output: <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f92aef538b0> <gevent._gevent_clocal.local object at 0x7f92809a2be0> <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f92810fefd0> <gevent._gevent_clocal.local object at 0x7f92809a2c40> <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f92810f1af0> <gevent._gevent_clocal.local object at 0x7f92809a2ca0> <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f9281068190> <gevent._gevent_clocal.local object at 0x7f92809a2d00> Running "time.sleep(1)" … -
Django interface buttons no longer work after connecting to IP 0.0.0.0:8000
I am trying to access Django website from a secondary device using python manage.py runserver 0.0.0.0:8000 The primary device that my laptop is connected to the same network as my secondary device, and I have turned off all firewalls. Also, I have configured the Allowed Host in settings.py file in Django by adding the IP address of the common connected data (192.168.61.130). However, when I access the website, the buttons on the website does not direct me to any page that I have linked in urls.py file. ALLOWED_HOSTS = ['192.168.61.130', '127.0.0.1', 'localhost'] From the example below, I have pressed the log in button and the POST request does show on the terminal. However, it does not direct me to the next page when I connect to the IP: 0.0.0.0:8000. The website works completely fine when I run on local host. Not sure why this is so and really need help on this. Hope to get any advice. -
Redis Broker getting OOM as "*.reply.celery.pidbox" keys count increased
Recently I have pushed around 10-15k tasks into celery by iterating in a for loop. Attaching below code for reference. for index, htl_urls_chunk in enumerate(iteration_grouper(htl_urls, n=10, chunk_type=list)): update_cache_for_hotel_detail_page_chunk.apply_async(kwargs={'htl_urls_chunk': htl_urls_chunk}) the length of htl_urls is around: 10-15k. Total tasks pushed ~ 1500 at given point of time. This lead to creation of below keys in redis: 01f6ebdb-361b-32ec-afe9-2eb7c8511288.reply.celery.pidbox 6292044c-a816-349a-a159-682536ea9bfa.reply.celery.pidbox Each key is of 150MB and total 29 keys created (4.24GB) This lead to OOM issue of my redis cluster. Can anyone suggest why this is happening ? I have tried to explored why these keys are being created in my redis cluster, but not able to reach any conclusion so far. -
Using MySQL CONVERT_TZ in django ORM
I am using the CONVERT_TZ MySQL function to convert datetime saved into the database into other timezone while running query. But I want to do the same thing with Django ORM due to performance issues with the next steps. Below is the code I am doing. boarding_stations = StationPoints.objects.filter(bus_id__in=bus_ids, station_id=sourceStation).annotate(coverted_timezone=Func(F('reachedTime'), '-08:00', '+05:30', function='CONVERT_TZ')) The above code returns FieldError as it says Cannot resolve keyword '-08:00' into the field. What's the correct way to use this MySQL function? -
Unable to call django view from template
Below is my urls.py code snippet for the main app urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name='home'), path('save_query',views.SaveQuery,name='SaveQuery'), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) Below is my html template snippet <form method="post" action="{% url 'save_query' %}"> {% csrf_token %} <p id="error-msg"></p> <div class="row"> <div class="col-lg-6"> <div class="mb-3"> <label class="form-label" for="name">Name</label> <input name="name" id="name" type="text" class="form-control" placeholder="Enter your name..." /> </div> </div> <div class="col-lg-6"> <div class="mb-3"> <label class="form-label" for="email">Email address</label> <input name="email" id="email" type="email" class="form-control" placeholder="Enter your email..." /> </div> </div> </div> <!-- end row --> <div class="mb-3"> <label class="form-label" for="subject">Subject</label> <input name="subject" id="subject" type="text" class="form-control" placeholder="Enter Subject..." /> </div> <div class="mb-3"> <label class="form-label" for="comments">Message</label> <textarea name="comments" id="comments" rows="3" class="form-control" placeholder="Enter your message..."></textarea> </div> <div class="text-right"> <!-- <input type="submit" id="submit" name="send" class="submitBnt btn btn-primary" value="Send message" /> --> <button type="submit" id="submit" name="send" class="submitBnt btn btn-primary" value="Send message"></button> </div> </form> Below is my view function (in the views.py file of the main app folder) def SaveQuery(request): if request.method == "POST": name = request.POST["name"] email = request.POST["email"] subject = request.POST["subject"] message = request.POST["comments"] query = Query(name=name,email=email,subject=subject,message=message) query.save() print(f"[DEBUG] New query has been saved @ {debug()}") return redirect('home') return render(request,"main.html") On running the application I get the following error Reverse for 'save_query' not found. 'save_query' is not a valid view … -
Registration during performance testing
I have an app on django, that I am writing performance tests for it using locust. I have a custom registration process (not the built-in one from django, session-based), that require you to verify your email by sending a link with token to your email. What is the best way to register and authenticate a user in locust? Generate a verification token in locust bu providing it the same secret key Make the request to some email api to get the token from there Skip the registration process and use pre-configured users Something else? -
Permission in pytest
I would like to test views with PermissionRequiredMixin where permission_required = 'can_manage_employees' Fixture below. I got error assert 403 == 302. It look like I did not grant correctly permission to user. Where is mistake? I tried give permission in different way but i did not give result `@pytest.fixture def my_permission(): permission, _ = Permission.objects.get_or_create( codename='can_manage_employees', name='can manage employees', content_type=ContentType.objects.get_for_model(User) ) return permission @pytest.fixture def user_with_permission(my_permission): u = User.objects.create_user( username='Dariusz', email='testuser@example.com', password='password' ) u.user_permissions.add(my_permission) return u ` Another ways of add permission -
Override the template of a widget and pass values to it with Django 4.0
I am creating a simple app to do product reviews. I have a Product, Manufacturer and Review models which I will now summarize (this is not my actual code, if you see some small errors it is because I am rewriting everything now to make it easier to understand) class Manufacturer(models.Model): name = models.CharField() class Product(models.Model): name = models.CharField() manufacturere = models.ForeignKey(Manufacturer) class Review(models.Model): title = CharField() product = models.ForeignKey(Product) I created a ModelForm to create the review. So far I was only able to create a custom widget with an overridden template. class CustomSelectWidget(forms.widgets.Select): option_template_name = 'widgets/select_option.html' class NewReviewForm(forms.ModelForm): review = forms.ModelMultipleChoiceField( queryset = Review.objects.none(), widget = CustomSelectWidget(), ) class Meta: model = Review fields = '__all__' The form view is a normal function based view. The review field is rendered with a list of products in a <select>.What I want to do is change the text inside <option> to make it so that the manufacturer's name is also there. IMPORTANT: I have to take the manufacturer's name from the respective Object, I can't just insert it into the Product name field. ES: what I have now Geforce RTX2080 MAXSUN AMD Radeon RX 550 Arca770 the goal NVIDIA - … -
Download files when popup is open in Django project
Hello there I need to download the file buy the in put post by the popup window in my Django project I am sharing the, the html code of popup window and function in views.py. if I don't use popup window it is working file and able to download file. HTML of Popup window <div class="modal-content"> <div class="modal-header"> {% for fil in instance %} <h5 class="modal-title">Download files for {{ fil.recorule_name|title }}</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <table class="table table-hover tablebdr"> <thead> <tr> <th>Account</th> <th>Rule name</th> <th>Date</th> </tr> </thead> <form action="{% url 'downloadlog'%}" method="POST" enctype="multipart/form-data" id="downloadlog-form"> {% csrf_token %} <tbody> <h6 id="modal_body"></h6> {% if fil.in_file1 %} <tr scope="row"> <td> <input type="text" class="form-control m-0" name="account_name" id = "account_name" value="{{ fil.account_name|title }}" readonly style="background-color: #f2f2f2; border: none;"> </td> <td> <input type="text" class="form-control m-0" name="recorule_name" id = "recorule_name" value="{{ fil.recorule_name|title }}" readonly style="background-color: #f2f2f2; border: none;"> </td> <td> <input type="date" class="form-control" name="recon_date" id= "recon_date"> </td> </tr> {% endif %} {% endfor %} </tbody> </table> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary btn-rounded btnwidth" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary btn-rounded btnwidth" id="downloadlog-submit">OK</button> </div> </div> <div class="modal-body"> <div class="alert alert-danger" style="display:none;" id="error-message"> Error message goes here. </div> <div class="alert alert-warning" … -
Django Modelformset
I have followed this link https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/ to help me in creating a modelformset. However, each time I press "submit", it creates new forms and it shows the previously submitted forms. That's not what I want, I want to specify in my view how many forms I want and it should stay that way after submitting. How can I cause no extra forms to be made after submitting? views.py: def test(request): AuthorFormSet = modelformset_factory(Author, fields=('name', 'title', 'birth_date'), extra=3) if request.method == 'POST': formset = AuthorFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() return render(request, 'voting/test.html', {'formset': formset}) # do something. else: formset = AuthorFormSet() return render(request, 'voting/test.html', {'formset': formset}) models.py: TITLE_CHOICES = [ ('MR', 'Mr.'), ('MRS', 'Mrs.'), ('MS', 'Ms.'), ] class Author(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=3, choices=TITLE_CHOICES) birth_date = models.DateField(blank=True, null=True) def __str__(self): return self.name forms.py: class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ('name', 'title', 'birth_date') test.html: <form method="post"> {{ formset.management_data }} {% csrf_token %} {{ formset }} <button type="submit" name = "voting" class="btn btn-primary save">Submit</button> </form> -
How to test @login_required view in django
I've a django view which has @login_required decorator then it renders html file with context and I'm trying test it's function whether the context is in response @login_required def my_view(request): #code goes here context={'name':name} return render(request, home.html, context) class TestEmployer(TestCase): def setUp(self): self.client = Client() self.client.login(username='1', password='Pass@123') def test_list_employer(self): url = reverse(my_view) response = self.client.post(url, follow=True) self.assertEqual(response.status_code, 200) self.assertIn('name', response.context) So @login_required decorator blocking me to test the function and asserts an error with 'name' not in signin html page -
Django Query two Models and Display Records in One HTML Table
I am working on a Django Daily Saving Project where I have Statement view and I want to display a Customer's Deposits and Withdrawals (all his deposits and withdrawals) in one HTML Table. I am looking at the Best Performance (Constant Complexity for Big O Notation if possible in this case). I don't know whether there is another way of displaying records in a table from a Model other than using a For Loop. If there is, then your kind answer is also welcome. Here are my Models: class Deposit(models.Model): customer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) transID = models.CharField(max_length=12, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' class Witdrawal(models.Model): account = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) transID = models.CharField(max_length=12, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) withdrawal_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.account}- Withdrawn - {self.withdrawal_amount}' Here is my view: def account_statement(request, id): try: customer = Account.objects.get(id=id) #Get Customer ID customerID = customer.customer.id except Account.DoesNotExist: messages.error(request, 'Something Went Wrong') return redirect('create-customer') else: deposits = Deposit.objects.filter(customer__id=customerID).order_by('-date')[:5] #Get Customer Withdrawal by ID and order by Date minimum 5 records displayed withdrawals = … -
Celery: Would increasing the number of queues speed things up?
I'm running my site on a VPS with 4 vCPUs, so by default each queue has 4 worker processes. I'm running 6 queues simultaneously now for my Celery process. The first queue, let's call it queue1, it's a very busy queue with multiple tasks/processes running all the time (mostly I/O tasks). Should I split queue1's tasks into smaller queues, e.g. queue1a, queue1b, queue1c, etc.? Will there be a performance benefit? My CPU utilization is quite high, I was just wondering if doing this will ease things up a little. -
Why does the mp3 player work correctly in FireFox, but does not work in other browsers?
The problem is rewinding the duration of the track. This works in FireFox, but doesn't work in other browsers. I even reset the cache, everything works correctly in FireFox. Why is this happening and how to fix it? JavaScript let audio = document.getElementById('audio'); let progress = document.getElementById('progress'); let progressBar = document.getElementById('progressBar') //Progress bar audio.ontimeupdate = function (){ progress.value = parseFloat(Math.floor(audio.currentTime * 100 / audio.duration) + "%") } //Set progress bar progress.addEventListener('click', function(e){ res = (e.offsetX / progress.clientWidth) * audio.duration document.getElementById("audio").currentTime = res; console.log("e.offsetX: " + e.offsetX + "\nprogress.clientWidth: " + progress.clientWidth + "\naudio.duration: " + audio.duration + "\nres:" + res + "\naudio.currentTime: " + audio.currentTime) }) HTML <a class="aTrigger" data-title="{{ beat.title }}" data-active="" data-audio="{{ beat.beat.url }}"><i class='fa fa-play'></i></a> <div class="time-control" id="progressBar"> <input id="progress" type="range" style="height: 5px; border-radius: 5px;"> </div> -
django project not loading static files for every user from different regions
I have deployed my project to server and it is not loding static files in my region but working perfect in other regions, what is the problem? Who can explane me? Thanks a lot)) I checked nginx settings but did not find anything -
How I can translate text on buttons in Django?
I try to make bilingual site on Django. Frontend wasn't written by me, and, unfortunatelly, I cannot ask this question for person who did it. const configButton = { purchases: { attr: 'data-out', default: { class: 'button_style_blue', text: '<span class="icon-plus button__icon"></span>Add to purchase list' }, active: { class: 'button_style_light-blue-outline', text: '<span class="icon-check button__icon"></span>Recipe in purchase list' } } } How I can add translation of text on the button using Django internalization tools? -
Error en python django Could not parse the remainder: '['fields']['Nombre']' from 'record['fields']['Nombre']'
hello i am new to python and django what i am trying to do is to connect to airtable through api, and i want to display that data in a table in html but at the time of displaying it i have that error, i need help pls, I already made the connection correctly to airtable. I tried to connect to another database, I checked the html tags and the names of the variables but I didn't find anything concrete. Error during template rendering <table> <thead> <tr> <th>Nombre</th> <th>Apellido</th> <th>Email</th> </tr> </thead> <tbody> {% for record in data %} <tr> <td>{{ record['fields']['Nombre'] }}</td> <td>{{ record['fields']['Apellido'] }}</td> <td>{{ record['fields']['Email'] }}</td> </tr> {% endfor %} </tbody> </table> -
How to get values from mutiple dropdown list and insert to the array list in model?
Any one know how to get values from mutiple dropdown field and then put those selected quantities into an arraylist in model? Also how to make those quantity >=1 items into a list so I can add them into another arraylist in the model? [enter image description here]enter image description here enter image description here Can anyone solove this? -
How to download and upload Django, Python App From DIgitalocan to Any server
Back in few months I hired someone to do a OTT project for me and he did it well but is has many errors and when I try to connect him he didn't respond. He don't even give me the source code which was the deal and also he was about to maintain the site for a monthly fee but heisn't responding at all even his phone is ringing and I try to contact for last 3 months each and every day, Now can you please please tell me is it possible to extract "Download" the database and website files from the Droplets in Digitalocan? and If yes how is it possible? And then what I will need to secure it and install on a vps or another droplets if needed and hire someone to fix the error. Sorry Maybe I made it massy but It will be really really helpful if someone can seve me from this. I just have time issue otherwise I may hire someone to do it from stratch. I have auto backup activated in Digitalocan, I tried to access the file via FTP and it works but don't know how to figure it out and … -
How can I add OR conditions in Django filters but with conditions
So let's say I have a interface that has a filters section (not django filters but just normal filters that we see on product listings etc). Now what I want is that: If Individual is checked, then only show Individual which is very easy. But things get messy when you choose two, let's say individuals and couples. Then I would need alot of if statements for this and changing the filters accordingly. I'm doing this currently like this: if individual and not couple and family: query = query.filter(Q(partner="individual") | Q(partner="family")) if individual and couple and not family: query = query.filter(Q(partner="individual") | Q(partner="couple")) if not individual and couple and family: query = query.filter(Q(partner="family") | Q(partner="couple")) if individual and not couple and not family: query = query.filter(partner="individual") if not individual and couple and not family: query = query.filter(partner="couple") if not individual and not couple and family: query = query.filter(partner="family") which is very messy. Basically I need something like this (PHP Code). $sql = "SELECT * FROM abc WHERE"; if($individual){ $sql .= " partner=individual"; } if($couple){ $sql .= " OR partner=couple"; } if($family){ $sql .= " OR partner=family"; } $sql .= " order by id desc"; now I know the php part above … -
How do i access the value of a table cell value rendered from python backend (HTMLcalender) in javascript front end #django_project
i want to get the value of a table cell from a Calendar rendered from python backend into html frontend, i want JavaScript to highlight the date as of today, by getting the value of the cell and match with today's date maybe by querySelector('id'); from django.shortcuts import render import calendar from ControlPanel.models import Subject, receipts, reportBook from calendar import HTMLCalendar import time def events(request, year, month, day): month = month.capitalize() month_num = list(calendar.month_name).index(month) month_num = int(month_num) year = int(year) name = "student user" cal = HTMLCalendar().formatmonth(year, month_num) return render(request, "events.html", { "name": name, "year": year, "month": month, "monthnum": month_num, "cal": cal, "day": day, }) {% extends 'header.html' %} {% block content %} <html lang="en"> <head> <meta charset="UTF-8"> <title>this is the html page to view the calendar rendered from python</title> </head> <body> <h1>Hello, {{ name }} events for {{ day }} {{ month }} {{ year }}</h1> <section class="container mt-5"> {{ cal|safe }} </section> </body> </html> bellow id the javascript code <script type="text/javascript"> const cal = document.querySelector('table'); cal.setAttribute('class', 'table table-striped'); const tds = document.querySelectorAll('td'); for (var i = 0; i < tds.length; i++){ tds[i].style.cursor="pointer"; console.log({{ day }}) console.log(tds[i].value) //this is returning undefined console.log(tds[i].innerTEXT) //this is returning undefined console.log(tds[i].innerHTML) //this is … -
Django: Remove db rows not present in JSON
As part of the Django project, I would like to mirror API data to local database. I have managed to update data on unique key, however I am struggling how to remove data from the database NOT anymore present in the API file. To illustrate this, let's have current API data like so: [ { "foo": "Lorem", "bar": "ipsum", }, { "foo": "dolor", "bar": "newvalue" }, { "foo": "adipiscing", "bar": "elit" } ] and existing database records (foo is a unique key column): | id | foo | bar | ----------------------------- | 1 | Lorem | ipsum | | 2 | dolor | sit | | 3 | amet | consectetuer | In this case the lines with id 1 & 2 will be updated (rewriting sit to newvalue in the process) and a new line for adipiscing, elit will be inserted. The question is: Is there any good practice how to determine and remove (in bulk) lines such as id 3 (e.g. unique key amet), which are no longer present in the (newly updated) input? -
AttributeError: 'NoneType' object has no attribute 'rsplit'
I'm getting AttributeError: 'NoneType' object has no attribute 'rsplit' error when trying to run this code self.client.get("/"). Test running in Docker on Windows 10 machine. Other simple model tests are running good, just like the application itself. Also tried running this test in another project, and there wasn't any problems. Feel free to ask for more information if needed. The whole error: Traceback (most recent call last): File "/usr/src/app/app/tests/test.py", line 5, in test_test resp = self.client.get("/") ^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/client.py", line 836, in get response = super().get(path, data=data, secure=secure, **extra) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/client.py", line 424, in get return self.generic( ^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/client.py", line 541, in generic return self.request(**r) ^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/client.py", line 805, in request response = self.handler(environ) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/client.py", line 140, in __call__ self.load_middleware() File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 61, in load_middleware mw_instance = middleware(adapted_handler) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/whitenoise/middleware.py", line 105, in __init__ self.add_files(self.static_root, prefix=self.static_prefix) File "/usr/local/lib/python3.11/site-packages/whitenoise/base.py", line 107, in add_files self.update_files_dictionary(root, prefix) File "/usr/local/lib/python3.11/site-packages/whitenoise/base.py", line 119, in update_files_dictionary self.add_file_to_dictionary(url, path, stat_cache=stat_cache) File "/usr/local/lib/python3.11/site-packages/whitenoise/base.py", line 130, in add_file_to_dictionary static_file = self.get_static_file(path, url, stat_cache=stat_cache) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/whitenoise/base.py", line 202, in get_static_file self.add_cache_headers(headers, path, url) File "/usr/local/lib/python3.11/site-packages/whitenoise/base.py", line 223, in add_cache_headers if self.immutable_file_test(path, url): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/whitenoise/middleware.py", line 177, in immutable_file_test static_url = self.get_static_url(name_without_hash) … -
How to implement Django QuerySet filter on Cartesian product/List of lists?
I want to implement queryset filtering in Django depending on values of nested list, e.g. titles = [ ['nike', '38', 'blue'], ['nike', '38', 'grey'], ['adidas', '38', 'blue'], ['adidas', '38', 'grey'], ['salmon', '38', 'blue'], ['salmon', '38', 'grey'] ] The queryset is: queryset = Attribute.objects.all() What are your suggestion to do something like below dynamically: # | mark means OR queryset.filter(title='nike').filter(title='38').filter(title='blue') | queryset.filter(title='nike').filter(title='38').filter(title='grey') | queryset.filter(title='adidas').filter(title='38').filter(title='blue') | ... queryset.filter(title='salmon').filter(title='38').filter(title='grey') I appreciate your help.