Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i am get all users list and then include which users complete kyc verified using foreign key
user list = user.objects.filter().values('username', 'user id', 'email', 'phone') Query set [{'username': 'muthu12', 'user id': 25, 'email': 'muthu12@gmail.com', 'phone': '9047885819'}, {'username': 'muthu123', 'user id': 26, 'email': 'muthu123@gmail.com', 'phone': '9047885819'}, I'm expect this type of Query set, KYC is Foreign key, query set : [{'username': 'muthu12', 'user id': 25, 'email': 'muthu12@gmail.com', 'phone': '9047885819', 'KYC' : True}, {'username': 'muthu123', 'user id': 26, 'email': 'muthu123@gmail.com', 'phone': '9047885819', 'KYC' : False}, -
How to delete objects in db only one time in for loop
I have json with few for loop iterations in each other and i want to know how to delete objects in db only one time on first iteration? I mean objects.all().delete and then ill create everthing from json task.py for i in json: for j in i.Information: MyModel.objects.filter(date=j.Date).delete() MyModel.objects.create(a=j.A, b=j.B, date=j.Date() #something like that In this for loop its deleting everytime objects in my db -
Use email request for signing in django
How can I use the docusign codes like the code in this link in the Django app? https://developers.docusign.com/docs/esign-rest-api/how-to/request-signature-email-remote/ I want to be able to use these codes in my views in django app. -
Is it possible to pass views parameters without using URLs in Django?
In product_detail in views.py, I use slug and pk (which is passed through the url in urls.py) to look up for Product. I'd like to use pk or id along with slug. But, the case is, I don't want to pass id or pk parameter to url. What I have: views.py def product_detail(request, slug, pk): product = get_object_or_404(Product, slug=slug, pk=pk) return render(request, "store/product_detail.html", {"product": product}) urls.py urlpatterns = [ # ... path("<int:pk>/<slug:slug>/", views.product_detail, name="product_detail"), ] Expected: views.py def product_detail(request, slug): pk = some_way_to_get_pk product = get_object_or_404(Product, slug=slug, pk=pk) return render(request, "store/product_detail.html", {"product": product}) urls.py urlpatterns = [ # ... path("<slug:slug>/", views.product_detail, name="product_detail"), ] Is it possible to do it with HttpRequests or some other way and how? Is it bad design? I'd like to know for educational purpose. Thanks in advance. -
Optimal approach for displaying big data tables in a template
Django is used as backend. There is data to display in the template of the client part, that's the question itself. What is the best way to display a table with 5000 rows and 50 columns in a template? which approach would be correct. I'm thinking of implementing it through DataTables, in which case how will the template behave with large data, or are there alternatives and a more suitable pattern for my task? Further in the table I will implement real-time filtering and export to Excel. I'm thinking of trying htmx, I don't know if it will solve my problem with long loading? Or caching can speed up page loading? Please tell me the correct approach, newbie on the fronte Thank you! Попробовал DataTAbles, очень долго грузится. -
docker-compose postgres container creates database locally but not on github actions
I have a project with three containers: python, nodejs, and postgres. The python container is for django and the nodejs container is for react. I'm using docker compose to run all of these containers together. Locally, everything runs properly. When running docker-compose in github actions the postgres container fails to create a database with the specified name. Here is the compose file: services: django: hostname: django container_name: django build: context: ./backend dockerfile: dev.Dockerfile ports: - 8000:8000 volumes: - ./backend:/backend environment: - SECRET_KEY=development_secret - DEBUG=1 - DB_HOST=${DB_HOST} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} depends_on: db: condition: service_healthy networks: - backend command: > bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" nodejs: build: context: ./frontend dockerfile: dev.Dockerfile ports: - 3000:3000 volumes: - ./frontend:/app depends_on: db: condition: service_healthy networks: - backend command: > npm install npm run start db: image: postgres ports: - 5432:5432 environment: - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} networks: - backend healthcheck: test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"] interval: 5s timeout: 5s retries: 5 networks: backend: name: network driver: bridge The error on github actions is: db_1 | 2023-03-16 04:40:00.177 UTC [75] FATAL: *** "***" does not exist db_1 | 2023-03-16 04:40:05.305 UTC [83] FATAL: *** "***" does not … -
List data print in another for loop in Django template
{% for i in packages %} {% endfor %}` i use this for loop in djnago template, in his loop i need to print another list. package_main_prices_list=[340, 180, 170, 95, 500] problem is i need to print one data from "package_main_prices_list" list in one "Packages" loop in Django template like this: {% for i in packages %} [340] #one data from "package_main_prices_list" {% endfor %} outpur will be: package name 340 date package name 180 date Thanks in advance. Regards Hamid. -
I have entered a value for my volumes field yet I am getting the error. services.inventory_app.volumes.0 type is required
version: "3" services: inventory_app: container_name: inventory_app image: postgres environment: POSTGRES_USER: "inventory_user" POSTGRES_PASSWORD: "inventory123" PGDATA: /data/inventory_app volumes: - inventory_app: /data/inventory_app ports: - "5434:5432" networks: - inventory_app_net restart: unless-stopped networks: inventory_app_net: driver: bridge volumes: inventory_app: I tried to build a successful connection through docker-compose to pgsql -
Can I make the class name to be a variable in python?
Can I make the class name to be a variable in the newer python release? I mean can I short the following instructions to be briefer? if target == "course": return Course.objects.all()[start:end]` elif target == "Subject": return Subject.objects.all()[start:end] elif target == "Teacher": return Teacher.objects.all()[start:end] to be briefer: return VARIABLE.objects.all()[start:end] -
How do I connect to MySQL Workbench on the host Windows from Ubuntu 22.04 using Django?
First, these answers didn't solve my problem: How to connect to WSL mysql from Host Windows, Connecting to MySQL database in django using workbench, and Unable to connect to MySQL on Ubuntu from MySQL Workbench on Windows. I have Ubuntu 22.04 installed on my Windows 11 and want to connect to MySQL Server (installed on the host Windows 11) from Ubuntu using Django but I keep getting Django Runserver Error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1:3306' (111)") and when I changed my database setting (host) from 127.0.0.1 to the IP I found when I ran nslookup "$(hostname).local", I get django.db.utils.OperationalError: (1130, "Host 'Mkw' is not allowed to connect to this MySQL server"). On my old laptop, everything works fine using HOST: 127.0.0.1, PORT: 3306. I don't want to install the MySQL server on Ubuntu since I already have it installed on the host Windows. -
docker exec django tests causing memory issue in github actions
I have three docker containers, python for django, node for react, and postgres as the database. I'm running all of these using docker-compose for local development. When I push changes to github I want github actions to build my containers and run the django tests. The code that I wrote works locally but when running it using github actions, the docker exec command is causing Error: Process completed with exit code 137.. Any help with fixing this would be appreciated. Here is the code for the compose file: services: django: hostname: django container_name: django build: context: ./backend dockerfile: dev.Dockerfile ports: - 8000:8000 volumes: - ./backend:/backend environment: - SECRET_KEY=development_secret - DEBUG=1 - DB_HOST=${DB_HOST} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} depends_on: db: condition: service_healthy networks: - backend command: > bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" nodejs: build: context: ./frontend dockerfile: Dockerfile ports: - 3000:3000 volumes: - ./frontend:/app depends_on: db: condition: service_healthy networks: - backend db: image: postgres ports: - 5432:5432 environment: - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} networks: - backend healthcheck: test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"] interval: 5s timeout: 5s retries: 5 networks: backend: name: colgate_network driver: bridge For the github actions file: name: Django CI on: push: … -
Trying to Run Celery Tasks on Remote Server
I have been scouring the Internet for some sort of guide for setting up django, celery, and redis so the celery task runs on a remote server, and I cannot seem to find out how to do this. I have three machines - tsunami (development), trout (production), and t-rex (Nvidia card). I am running some image manipulation algorithms using celery and redis. I have the same django/celery code base on all three computers. When I run the algorithms on tsunami or trout without CUDA support, it takes hours to complete. When I run the same algorithms on t-rex with CUDA support, they complete in minutes. What I would like to do is offload the celery tasks from trout and tsunami to t-rex, and return the results to the either trout or tsunami. By results, I mean a file to save on the local file system or data added to the local mysql (8.0.32) database. Is this even possible? Can someone point me to a guide on how to set this up? I am running django 4.1.7, celery 5.2.7 and redis server 6.0.16. Trout and tsunami are running Ubuntu 20.04, and t-rex is Ubuntu 22.04. All are running Python 3.8. I … -
How to interact with heroku connect Salesforce data in a Django app
I'm new to heroku connect with Django, although I've used heroku connect with other stacks. Are models that inherit from hc_models.HerokuConnectModel supposed to create database tables? I have a django project set up like so (abbreviated for readability) ├── app │ ├── __init__.py │ ├── common │ │ ├── __init__.py │ │ ├── apps.py │ │ ├── favicon_urls.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── urls.py │ │ └── views.py │ ├── core │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── factories.py │ │ ├── forms.py │ │ ├── management │ │ │ ├── __init__.py │ │ │ └── commands │ │ │ ├── __init__.py │ │ │ └── create_test_data.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ └── __init__.py │ │ ├── models.py ....... │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt ├── runserver.sh ├── salesforce_company │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py I have all mappings set up with heroku connect on the heroku web GUI. I have … -
React component NOT updating by itself after change in data without refreshing the entire page
I am using ReactJS on the front-end to make a POST request to my Djando API. After I make the POST request, I expect for my React component to update itself without me having to refresh the entire page. I'm using a useEffect hook to call the my endpoint(GET) to retrieve the data I just updated. import React from 'react' import CampaignList from '../components/CampaignList' import {useState, useEffect} from 'react' const campaignRequest = () => { fetch('http://localhost:8000/api/v1/campaigns/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email_address: "zztop1111122233344556677889910101010@gmail.com", first_name: "i", last_name: "k", stage: "1" }) }) .then(res => res.json()) .then(data => console.log(data)) .catch(error => console.log(error)) } let Campaigns = () => { const [recipients, setRecipients] = useState([]); const [isLoading, setIsLoading] = useState(true); console.log("Campaign is re-mounted") useEffect(() => { setIsLoading(true); fetch('http://localhost:8000/api/v1/campaigns/') .then((res) => res.json()) .then((data) => { setRecipients(data); setIsLoading(false); }) .catch(error => console.log(error)); // fetchData() } ,[]); if (isLoading) { return <p>Loading...</p>; } return ( <div> <div>Campaigns</div> <CampaignList recipientss={recipients}/> {/* <div> {recipients.map((recipient, index) => ( <h3 key={index}>{recipient.email_address} </h3> ))} </div> */} <button onClick={campaignRequest}>Click Me</button> </div> ) } export default Campaigns -
as_crispy_field filter does not render the model's validation errors
views.py: class LoadRequestView(BSModalFormView): template_name = 'sales_portal/activation_request.html' body_template_name = 'sales_portal/activation_request_body.html' form_class = ActivationRequestForm #model = ActivationRecord def form_valid(self, form, **kwargs): form_instance = form.instance invoice_id = self.kwargs.get("invoice_id") invoice = get_object_or_404(InvoiceRecord, pk=invoice_id) # add the host information to the invoice host_information, created = HostInformation.objects.get_or_create( host_id = form_instance.host_id, host_method = form_instance.host_method, host_ref = form_instance.host_ref ) host_information.save() invoice.hosts.add(host_information) # update the activation record with the host information for activation_record_id in form.cleaned_data.get("activations", []): activation = get_object_or_404(ActivationRecord, pk=activation_record_id) activation.host_method = host_information.host_method activation.host_id = host_information.host_id activation.host_ref = host_information.host_ref activation.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form): id = self.request.POST.get('id') data = { 'request_form':form, 'id':id, 'submit_url':reverse_lazy('load_request', kwargs={'id':id}) } activations = ActivationRecord.objects.filter(purchase_order=id, host_id=None) # check for host_id null too table = RequestActivationsTable(activations) RequestConfig(self.request).configure(table) data['table'] = table print(f"the form errors are {form.errors}") return HttpResponse(render(self.request, self.body_template_name, data),status=400) forms.py: class ActivationRequestForm(BSModalModelForm): encoded_activation_request = forms.CharField(required=True, label="Activation Request", widget=TextInput(attrs={"onkeydown":"return false;"}) ) def __init__(self, *args, **kwargs): if 'request' in kwargs : request = kwargs.pop('request') super(ActivationRequestForm, self).__init__(*args, **kwargs) #self.helper = FormHelper() #self.helper.error_text_inline = False #self.helper.form_method = 'post' self.fields.update({ 'activations': RequestedProductChoiceField( widget=HiddenInput(), required=False, label='Products' ), }) self.fields["host_ref"].label = "Customer Reference" self.fields["host_method"].label = "Host Verification Method" class Meta: model = ActivationRecord #fields = '__all__' fields = ("encoded_activation_request","host_id", "host_method", "host_ref", "feature_name") widgets = { "host_id": TextInput(attrs={"readonly": "readonly"}), "host_method": TextInput(attrs={"readonly": "readonly"}), "host_ref": TextInput(attrs={"readonly": … -
Getting images to display correctly in a django view
I have a view inside my django app called flashcard_view which displays some images. There is a small problem with how the images are displayed. The problem is that the overlay images are slightly offset or running of the edges of the images underneath them. This is what I see: Here is the code for this template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {% load static %} <link rel="stylesheet" href="{% static 'am_flashcard_template.css' %}"> </head> <body> <h1>Flashcard Display</h1> {{ flashcard }} {#BEGINNING OF ANKIMASTER TEMPLATE#} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" referrerpolicy="no-referrer"></script> <div class="card"> <div class='top'> </div> <div id='sentence-example'>{{flashcard.sentence}}</div> <div class='dictionary-form'>{{flashcard.word_dict_form}}</div> <div class='brown mid-text'>{{flashcard.ipa}}</div> <div class='images-container'> <div> <img src='{{flashcard.image_1_url}}'/> <img class='overlay' src='{{flashcard.image_1_overlay}}'/> </div> <div> <img src='{{flashcard.image_2_url}}'/> <img class='overlay1' src='{{flashcard.image_2_overlay}}'/> </div> <div> <img src='{{flashcard.image_3_url}}'/> <img class='overlay2' src='{{flashcard.image_3_overlay}}'/> </div> <div> <img src='{{flashcard.image_4_url}}'/> <img class='overlay3' src='{{flashcard.image_4_overlay}}'/> </div> <div> <img src='{{flashcard.image_5_url}}'/> <img class='overlay4' src='{{flashcard.image_5_overlay}}'/> </div> </div> <div class='part-of-speech mid-text'>{{flashcard.pos}}</div> <!-- Class mid-text setting font-size on 30 px --> {#<div id='definition'>{{Definition}}</div>#} <div id='word-translation'>{{flashcard.word_trans}}</div> <button class='btn-translation' id='wordtrans'>WORD TRANSLATION</button> </div> <script> /* * We can select element by tag $('tagname'), by class name $('.classname') or by id $('#id'). * If an error occurs while loading an image, such as a broken link, we hide that image with = $(this).hide(). * … -
About join 2 modules and show all in Django
I try to join 2 modules and show parts data of them on homepage, yes, I have data already, and below is my files. class Products(models.Model): products_id = models.AutoField(primary_key=True) products_type = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'wdb_products' class ProductsDescription(models.Model): products_id = models.ForeignKey(Products, null=True, on_delete=models.SET_NULL, related_name='pdtion', db_constraint=False) class Meta: managed = False db_table = 'wdb_products_description' # view.py from django.shortcuts import render # from .models import WdbProducts, WdbProductsDescription from .models import ProductsDescription, Products def index(request): products = Products.objects.select_related('pdtion').filter(products_type=1) return render(request, 'product/MainProduct.html', {'products': products}) but those don't work, the data of WdbProductsDescription is empty, actually I can got all of them data thru sql script. can you tell me what's wrong on it? -
Trouble connecting django (container on ec2) to a postgresql database (container) running on a remote server
So here is the setup: 1. I have a django container, postgresql container, and an nginx proxy running on an ec2 instance 2. I have another postgresql container running on locally on an ubuntu server 3. I am trying to connect the django server to the local postgresql server just to read data Configuration: 1. for django I have the configuration for the remote database 2. Here is the config. All variables are set in a .env file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS') }, 'nlp_data': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('NLP_DB_HOST'), 'NAME': os.environ.get('NLP_DB_NAME'), 'USER': os.environ.get('NLP_DB_USER'), 'PASSWORD': os.environ.get('NLP_DB_PASS') } } Problems: 1. The postgresql container on my local server... What would be the host of this database? Is it the public IP of the ubuntu server? Not sure 2. Is there a better way to debug these network issues? I have been getting timeout errors (assuming this is because my django container is unable to reach my local db server) I have tried using the public IP of my local ubuntu server but that did not solve anything or tell me anything new. -
Djoser /jwt/verify/ is getting a 500 error even when I'm getting a local access token
In my react/redux django application, I am using JWT authorization. In my function to check whether the user is authorized, I am successfully consoling a Local Storage Token - however, the API Response is outputting a 500 error. In redux dev tools, Im only able to ever see AUTHENTICATED_FAIL, never success. I am getting a 500 error in postman as well when I post what is a correct Local Storage token. If it is relevant to this issue, whenever I refresh the page the user is forcibly logged out. Please help me / let me know what else is needed to best support. " `export const checkAuthenticated = () =\> async (dispatch) =\> { if (localStorage.getItem("access")) { console.log("Local Storage Token:", localStorage.getItem("access")); const config = { headers: { "Content-Type": "application/json", Accept: "application/json", }, }; const body = JSON.stringify({ token: localStorage.getItem("access") }); try { const res = await axios.post( `${process.env.REACT_APP_API_URL}/auth/jwt/verify/`, body, config ); console.log("API Response:", res); if (res.data.code !== "token_not_valid") { dispatch({ type: AUTHENTICATED_SUCCESS, }); } else { dispatch({ type: AUTHENTICATED_FAIL, }); } } catch (err) { dispatch({ type: AUTHENTICATED_FAIL, }); } } else { dispatch({ type: AUTHENTICATED_FAIL, }); } };` ```" Here is part of the error message from the server … -
How is Django typically used with Angular?
I started learning Django and it confuses me a little bit. Because I’m an Angular dev, I am confused about the Angular’s role. Angular is known for its flexible HTML, but it’s done by django, also I need to use state management, which I won’t be able to use if the data is already used by django and has generated HTML from it. Plus, page refreshes. Every url has its html, and switching urls will cause page refreshes, which we don’t want obviously. Also, frontend and backend are mixed in each other which is also confusing, seen as a Node/expressJs dev. I’m curious about how most of the people use them together, what is the ‘standart’ for building Django apps with frontend frameworks. -
Django not detecting Postgres version correctly
I had Postgres version 10.3. When I ran makemigrations, I got the error: django.db.utils.NotSupportedError: PostgreSQL 11 or later is required (found 10.23). So, I actualized Postgres, and created a new database. Now I have postgres 15.2 psql --version psql (PostgreSQL) 15.2 (Ubuntu 15.2-1.pgdg18.04+1) Still, Django thinks I have the old version of Postgres and gives me the same error. django.db.utils.NotSupportedError: PostgreSQL 11 or later is required (found 10.23). How can solve this? -
How to render html page via mail?
I tried to have main own password reset confirmation mail template and it doesn't work in sense cause is rendering in .txt and not .html I've tried with this view : class CustomPasswordResetView(PasswordResetView): @staticmethod def send_mail(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): subject = render_to_string(subject_template_name, context) subject = ''.join(subject.splitlines()) body_text = render_to_string(email_template_name, context) body_html = render_to_string(html_email_template_name, context) email_message = EmailMultiAlternatives(subject, body_text, from_email, [to_email]) email_message.attach_alternative(body_html, 'text/html') email_message.send() and also the urls.py path('password_reset/', auth_views.PasswordResetView.as_view( html_email_template_name='registration/password_reset_email.html' ), name='password_reset_confirm'), and i've created a password_reset_email.html file in the registration folder in templates But when i receive the mail is showing me the whole content in text, i can see the html tags... -
Django Rest Framework: How can I automatically set a value for Creation in generics API classes?
I want that my API that my api automatically assign the value user to the logged in user during the creation Process, but I can't figure how. Model: class Template(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='templates') name = models.CharField(max_length=200) base_attribute_points = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(10000)]) base_skill_points = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(10000)]) base_advantage_points = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(10000)]) min_attribute_value = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(100)]) max_attribute_value = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(1000)]) replace_attributes_derived_values = models.BooleanField() replace_attributes_skills = models.BooleanField() def save(self, *args, **kwargs): super().save(*args, **kwargs) def __str__(self): return f'{self.user}: {self.name}' Serializer: class TemplateSerializer(serializers.ModelSerializer): characteristics = CharacteristicSerializer(many=True, read_only=False) attributes = AttributeSerializer(many=True, read_only=False) skill_categories = SkillCategorySerializer(many=True, read_only=False) derived_values = DerivedValueSerializer(many=True, read_only=False) levels = LevelSerializer(many=True, read_only=False) class Meta: model = Template fields = ['id', 'user', 'name', 'base_attribute_points', 'base_skill_points', 'base_advantage_points', 'min_attribute_value', 'max_attribute_value', 'replace_attributes_derived_values', 'replace_attributes_skills', 'characteristics', 'attributes', 'skill_categories', 'derived_values', 'levels'] View: class TemplateList(generics.ListCreateAPIView): serializer_class = TemplateSerializer queryset = Template.objects.all() permission_classes = [permissions.IsAuthenticated] def get_queryset(self): user = self.request.user return user.templates.all() #def perform_create(self, serializer): # print(serializer.validated_data) # serializer.save() Like I said, I want to set the user to the logged-in user. Also It would be nice, if the user field isn't required. I already tried out many things, but all i get are errors. I tried to configure the perform_create method to change the value there, … -
Django admin panel makes unnecessary queries when memoizing related object in model __init__ method
Django = 2.2 Python = 3.6 I have two models named Pl and Exam in Django: class Pl(models.Model): name = models.CharField() class Exam(models.Model): name = models.CharField() pl = models.ForeignKey("Pl") def __init__(self, *args, **kwargs): super(Exam, self).__init__(*args, **kwargs) self._pl = self.pl As shown in the code, the Exam model's __init__ method makes a query to the Pl model to memoize it. This is causing problems on the admin panel, where if I want to display 100 Exam objects on the list page, it makes 100 queries for each object. I have tried using list_select_related = ("pl", ), but it didn't work. I have also tried to override the get_queryset method in the admin panel and use select_related("pl"), but it still makes those queries. To debug the issue, I updated the __init__ method as follows: def __init__(self, *args, **kwargs): super(Exam, self).__init__(*args, **kwargs) print(self._state.fields_cache) # name this print statement as "A" self._pl = self.pl And then I tried the following query: exams = Exam.objects.all().select_related("pl") exam = exams.last() print(exam._state.fields_cache) # name this print statement as "B" "B" always shows the cached field and returns {'pl': <Pl: 1>}, but "A" always returns an empty dictionary {} indicating that the self object doesn't have the cached object. … -
why is there an error while rendering django files
I did or tried, like here https://github.com/kottenator/django-compressor-toolkit and https://gist.github.com/brizandrew/685a588fbefbd64cd95ed9ec4db84848 But after the command "python manage.py compress" comes out this "CommandError: An error occurred during rendering accounts\profile.html: 'utf-8' codec can't decode byte 0xad in position 9: invalid start byte", at the same time, after each command, the name "profile.html" of the html file is different my settings.py COMPRESS_ENABLED = True COMPRESS_CSS_HASHING_METHOD = 'content' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) COMPRESS_FILTERS = { 'css': [ 'compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter', 'compressor.filters.template.TemplateFilter' ], 'js': [ 'compressor.filters.jsmin.JSMinFilter', ] } COMPRESS_PRECOMPILERS = ( ('module', 'compressor_toolkit.precompilers.ES6Compiler'), ('text/x-scss', 'compressor_toolkit.precompilers.SCSSCompiler'), ) HTML_MINIFY = True KEEP_COMMENTS_ON_MINIFYING = True COMPRESS_OFFLINE = True my template {% extends 'base-page.html' %} {# Django template #} {% load compress %} {% load static %} {% load pages %} {% compress css %} <link rel="stylesheet" type="text/x-scss" href="{% static 'accounts/css/base-profile.css' %}"> {% endcompress %} {% compress js %} <script type="module" src="{% static 'accounts/js/base-profile.js' %}"></script> {% endcompress %} my package.json { "name": "mysite", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "type": "module", "author": "", "license": "ISC", "devDependencies": { "autoprefixer": "^10.4.14", "babel-preset-es2015": "^6.24.1", "babelify": "^10.0.0", "browserify": "^17.0.0", "node-sass": "^8.0.0", "postcss-cli": "^10.1.0", "sass": "^1.59.3" }, "dependencies": { "jquery": "^3.6.4" } …