Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error "database couldn't be flushed" in pytest-django when adding live_server
When I run pytest with live_server, I see error: E django.core.management.base.CommandError: Database file:memorydb_default?mode=memory&cache=shared couldn't be flushed. Possible reasons: E * The database isn't running or isn't configured correctly. E * At least one of the expected database tables doesn't exist. E * The SQL was invalid. E Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run. test_settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } pytest.ini [pytest] DJANGO_SETTINGS_MODULE = n3auto.settings.test_settings python_files = tests/**/*.py tests/*.py tests.py addopts = --create-db -p no:warnings --no-migrations conftest.py import pytest @pytest.fixture(autouse=True) def grant_db_access_to_all_tests(db): pass tests.py from app.models import MModel def test1(live_server): pass def test2(): assert MModel.objects.count() == 0 When I remove test1 with live_server, tests running without errors. -
mysqlclient failed on vercel
I am unable to deploy my because of this Error 1: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: mysql_config: command not found /bin/sh: mariadb_config: command not found /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-hwcmhfay/mysqlclient_c0e246e016eb466f916ce14b69432b1e/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-hwcmhfay/mysqlclient_c0e246e016eb466f916ce14b69432b1e/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-hwcmhfay/mysqlclient_c0e246e016eb466f916ce14b69432b1e/setup_posix.py", line 31, in mysql_config raise OSError("{} no I am expecting a clear explaination about problem and a clear solution Similar to this error but on vercel -
Error running WSGI application AttributeError: module 'juzgado10_pythonanywhere_com_wsgi' has no attribute 'application', how do i fix this?
I'm trying to deploy a web app I've made in wagtail on pythonanywhere and i keep bumping into errors and issues and its a nightmare honestly, apparently its a wsgi issue but i have no clue how to solve it. Here's my WSGI configuration file. # +++++++++++ DJANGO +++++++++++ # To use your own django app use code like this: """ WSGI config for juzgado10 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ """ import os import sys # ## assuming your django settings file is at '/home/juzgado10/mysite/mysite/settings.py' ## and your manage.py is is at '/home/juzgado10/mysite/manage.py' path = '/home/juzgado10/pagina-juzgado/juzgado10' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'juzgado10.settings.prod' # ## then: from django.core.wsgi import get_wsgi_application app = get_wsgi_application() And here's the error I get. 2023-04-17 10:06:11,483: Error running WSGI application 2023-04-17 10:06:11,484: AttributeError: module 'juzgado10_pythonanywhere_com_wsgi' has no attribute 'application' 2023-04-17 10:06:11,484: *************************************************** 2023-04-17 10:06:11,485: If you're seeing an import error and don't know why, 2023-04-17 10:06:11,485: we have a dedicated help page to help you debug: 2023-04-17 10:06:11,485: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2023-04-17 10:06:11,485: *************************************************** 2023-04-17 10:06:12,005: Error running WSGI application 2023-04-17 10:06:12,005: AttributeError: module 'juzgado10_pythonanywhere_com_wsgi' has no attribute 'application' -
django.db.utils.IntegrityError and sqlite3.IntegrityError
I'm following a Django tutorial to train and make a simple poll site. At a certain point, when I need to get the server running and add questions to the polls, I come across the error codes below: django.db.utils.IntegrityError: NOT NULL constraint failed: polls_question.question_text sqlite3.IntegrityError: NOT NULL constraint failed: polls_question.question_text I expected to be able to add questions in the questions field created in the database, but I came across this mistakes. What do I do? -
Can't connect Django with MySQL
I'm facing an issue trying to connect Django with MySQL, I'm on MacOS with Monterey, I have already installed Python and MySQL with brew, additionally I have installed mysqlclient with pip3, also, I have already change the DATABASE conf in settings.py in my django project, but the error is always the same when I try to make migrations or migrate: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.mysql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'oracle', 'postgresql', 'sqlite3' Here is my database configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangodatabase', 'USER': 'dbadmin', 'PASSWORD': '12345', 'HOST': 'localhost', 'PORT': '3306', } } Any idea about how to solve this? Thanks to all... change DATABASE configurations, and many others. -
How to stream local video using django
I"m using python-ffmpeg-video-streaming in my django project. I can able to generate mpd and m3u8 file successfully , but i didnt know how to serve these file using django views. I tried this approach but this is not working def stream_multi_quality_video(request): video_path = "./dashpath/dash.mpd" with open(video_path, "rb") as mpd_file: mpd_contents = mpd_file.read() # Set the response headers response = HttpResponse(mpd_contents, content_type="application/dash+xml") response["Content-Length"] = len(mpd_contents) return response after this I got chunk file not found error in browser console. Here is my frontend code for videojs <div class="video-container"> <video id="my-video" class="video-js" controls preload="auto" width="640" height="264" data-setup="{}"> <source src="{% url 'stream_video' %}" type="application/dash+xml"> </video> </div> <script> var player = videojs('my-video'); </script> -
use node modules in django
I want to build a qr-code scanner to my django web app. For that I currently am using jsQR. For some reason Django is not able to allocate the jsQR module needed for the script to run. snippet for html file: (on click on the button, webcam opens and it should scan for qr codes) <button id="qr-code-scanner">Scan QR Code</button> <video id="video" width="640" height="480" autoplay></video> <canvas id="qr-canvas" width="640" height="480"></canvas> ... <script type="module" src="{% static 'business_page/js/qr_scanner_fin_2.js' %}"></script> qr_scanner_fin_2.js file: import jsQR from './jsqr'; const constraints = { video: true }; const canvas = document.getElementById('qr-canvas'); const ctx = canvas.getContext('2d'); function startCamera() { navigator.mediaDevices.getUserMedia({ video: true }) .then((stream) => { const video = document.querySelector('video'); video.srcObject = stream; video.play(); video.addEventListener('loadedmetadata', () => { canvas.width = video.videoWidth; canvas.height = video.videoHeight; const scan = () => { ctx.drawImage(video, 0, 0, canvas.width, canvas.height); const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const code = jsQR(imageData.data, imageData.width, imageData.height, { inversionAttempts: false, }); if (code) { console.log('QR code detected:', code.data); video.pause(); stream.getTracks().forEach(track => track.stop()); return; } requestAnimationFrame(scan); }; requestAnimationFrame(scan); }); }) .catch((error) => { console.error('Error accessing media devices.', error); }); } document.addEventListener('DOMContentLoaded', () => { console.log('DOMContentLoaded'); }); const scanButton = document.getElementById('qr-code-scanner'); scanButton.addEventListener('click', () => { console.log('scanButton click'); startCamera(); }); for some … -
'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST'
So I have created a django-react E-commerce website. I have used rest framework to create api for making get and post request to the backend. Both get and rest requests are working fine when made with rest framework in built forms. But I am unable to make the same through my react frontend. Its giving me the 403 forbidden error. I am able to perform get request using the api through frontend facing issues just with post request. console error msg xhr.js:247 POST http://127.0.0.1:8000/api/create/ 403 (Forbidden) I have tried using axios as well as fetch to make those requests through react. I have tried all existing solution on stackoverflow. Here's how my react code looks like adduom.js import React from 'react' import { useState } from "react"; // import { useForm } from "react-hook-form"; import '../../App.css'; import Navbar from '../Navbar'; import axios from 'axios'; export default function AddUom() { const [obj, setobj] = useState({ uom: '' }) const addUom = async () => { console.log("hiii") const response = await fetch(`http://127.0.0.1:8000/api/customer/`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(obj) }); const data = await response.json(); console.log("add UOM called : \n"+data); } const handleSubmit = (e) => { e.preventDefault(); var … -
DRF serializer for questions that depend on multiple objects
I am trying to write a serializer which allows users to submit the answers to a quiz. However, the questions that should be answered depend on two separate things in the database. So, let's say we have these models:- class Day(models.Model): name = models.CharField() class Quiz(models.Model): name = models.CharField() class QuizQuestion(models.Model): quiz = models.ForeignKey(Quiz, related_name="questions") days = models.ManyToManyField(Day, related_name="questions") question = models.CharField() class QuizCompletion(models.Model): completed_by = models.ForeignKey(User) quiz = models.ForeignKey(Quiz) class QuizAnswer(models.Model): quizquestion = models.ForeignKey(QuizQuestion) quizcompletion = models.ForeignKey(related_name="answers", QuizCompletion) answer = models.CharField() So, to find the questions that the user has to answer for a particular quiz for a particular day, you'd need to do something like:- questions = quiz.questions.filter(days__id=day.id) I'm trying to create the serializer for submitting the answers to such a quiz so that it will check whether all of the questions have been answered. What is the best way to write this serializer? The days thing is the thing that's confusing me. Do I need a URL that includes BOTH the quiz ID and the day ID, so that I can get the right questions? class QuizCompletionSerializer(serializers.ModelSerializer): quiz = QuizSerializer() answers = QuizAnswerSerializer(many=True) class Meta: model = QuizCompletion fields = ["completed_by", "quiz", "answers"] def validate_answers(self, answers): # … -
Why my django-filter filters don't work. There is no error, the GET request arrives
Created filtering of Users objects. It worked for a while, but then it stopped. I can't understand what the problem is. Get request is sent( http://127.0.0.1:8000/staff/manager/user-list/?gender=M ). But the data on the page is not updated. There are no errors. What to do? class UserFilters(django_filters.FilterSet): class Meta: model = User fields = ('gender',) class ManagerUsersListView(ListView): template_name = 'manager/list_users_manager.html' model = User paginate_by = 7 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['users'] = User.objects.all() context['filter'] = UserFilters(self.request.GET, queryset=self.get_queryset()) return context def get_queryset(self, **kwargs): search_results = UserFilters(self.request.GET, self.queryset) self.no_search_result = True if not search_results.qs else False return search_results.qs Simplified version of HTML <form method="get"> {{ filter.form }} <input type="submit" class="btn btn-default add-to-cart" value="Filer"></input> </form> {% for u in users %} {{u.pk}} {{u.first_name}} {{u.gender}} {% endfor %} I broke my head...... -
how to resolve django : ImportError: cannot import name 'parse_header' from 'django.http.multipartparser'
My application was running fine till few days back, but now all of a sudden i'm seeing this error and not sure what it means, please help. Error: File "/myproj/myapp/urls.py", line 8, in <module> from rest_framework import routers File "/usr/local/lib/python3.8/site-packages/rest_framework/routers.py", line 22, in <module> from rest_framework import views File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 15, in <module> from rest_framework.request import Request File "/usr/local/lib/python3.8/site-packages/rest_framework/request.py", line 17, in <module> from django.http.multipartparser import parse_header ImportError: cannot import name 'parse_header' from 'django.http.multipartparser' (/usr/local/lib/python3.8/site-packages/django/http/multipartparser.py) my line 8 of urls.py is: from rest_framework import routers and i could see the parse_header method in the multipartparser.py file PFA multipartparser file -
Google file picker API giving error Javascript
I am trying to implement a google file picker in my Django Project. Currently when I try to create an HTML page with Google file picker integrated I am facing 500 Something went wrong error. This happens after I authorize my app and create access token. First I was thinking that access token generation must be having some issues, but I tried listing files using the access token generated and I was able to successfully list down files in my Google drive as can be seen in the browser console. Help will be greatly appreciated. Below is my HTML code. <!DOCTYPE html> <html> <head> <title>Picker API Quickstart</title> <meta charset="utf-8" /> </head> <body> <p>Picker API API Quickstart</p> <!--Add buttons to initiate auth sequence and sign out--> <button id="authorize_button" onclick="handleAuthClick()">Authorize</button> <button id="signout_button" onclick="handleSignoutClick()">Sign Out</button> <pre id="content" style="white-space: pre-wrap;"></pre> <script type="text/javascript"> /* exported gapiLoaded */ /* exported gisLoaded */ /* exported handleAuthClick */ /* exported handleSignoutClick */ // Authorization scopes required by the API; multiple scopes can be // included, separated by spaces. const SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'; // TODO(developer): Set to client ID and API key from the Developer Console const CLIENT_ID = '<YOUR_CLIENT_ID>'; const API_KEY = '<YOUR_API_KEY>'; // TODO(developer): Replace with your … -
Django 3.2 CITEXT and unique_together
I'm using Django 3.2 and postgreSql 12. I've added a new text field that should be case-insensitive, i.e if the value 'ab' exists, I want the DB to fail the request if someone is inserting 'Ab'. But this field shouldn't be unique all over the table, but unique with another field (unique_together). I've tried creating the field as 'CITEXT' and since it's deprecated in Django 4.2 I've used the Collation migration as recommended. The migrations passed, and when testing it I see that I can create two objects with the same letters, and different cases. Am I doing something wrong or this implementation of case-insensitive shouldn't work with 'unique_together'? The collation migration: operations = [ CreateCollation( "case_insensitive", provider="icu", locale="und-u-ks-level2-kn-true", deterministic=True, ), ] The model changes: class MyItem(models.Model): identifier = models.CharField(db_collation="case_insensitive", db_index=True, max_length=100, null=True) container = models.ForeignKey(Container, related_name='my_items', on_delete=models.CASCADE, null=True) class Meta: unique_together = ('identifier', 'container_id') After running the migrations, I've successfully created two MyItems with the same container and identifier='ab' and 'Ab' -
I am Facing issue in mysql
while using this command - pip install mysql I am facing issue in code error: subprocess-exited-with-error note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. I try pip3 install mysql -
"'xml.etree.ElementTree.Element' object has no attribute 'getiterator'" when I try to make markdown filter for my blog
Thanks for any of your answers! My question is: I learn Django with book "Django By Example". Now I'm learning "Custom template filters" chapter. And I do everything what author is telling to do. But there is a problem. I get error, witch look like this: "'xml.etree.ElementTree.Element' object has no attribute 'getiterator'" I tried to write function in this way: @register.filter(name='markdown') def markdown_format(text): return mark_safe(markdown.markdown(text)) and my list.html file looks like this: {% extends "blog/base.html" %} {% load blog_tags %} {% block title %}My Blog{% endblock %} {% block content %} <h1>My Blog</h1> {% if tag %} <h2>Posts tagged with "{{ tag.name }}"</h2> {% endif %} {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="tags"> Tags: {% for tag in post.tags.all %} <a href="{% url "blog:post_list_by_tag" tag.slug %}"> {{ tag.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} </p> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|markdown|truncatewords_html:30 }} {% endfor %} {% include "pagination.html" with page=posts %} {% endblock %} Full version of the previous code you can find here: https://github.com/PacktPublishing/Django-3-by-Example/tree/master/Chapter03/mysite -
Django create create GET url in template
I want to make get request on the django site page, {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="{{ url 'clothes:designer' }}?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="{{ url 'clothes:designer' }}?page={{ page_obj.next_page_number }}">next</a> {% endif %} </span> </div> {% endif %} i dont want to hardcode href url can i create GET request url like {{ url 'page' method='get' **kwargs }}? i tried to find in django docs, but i have not found -
django.db.utils.OperationalError [Microsoft][ODBC Driver 17 for SQL Server]Client unable to establish connection
I am using mssql server as my database in Django, hosted on Heroku. I am having trouble connecting to that database with ODBC Driver 17 for SQL Server. #requirements.txt asgiref Django==4.0 pytz sqlparse djangorestframework gunicorn python-dotenv django-mssql-backend whitenoise pyodbc Config Vars . . . ENGINE: sql_server.pyodbc MSSQL version: Microsoft SQL Server 2014 settings.py 'default': { 'ENGINE': os.getenv('ENGINE'), 'NAME': os.getenv('NAME'), 'USER': os.getenv('USER'), 'PASSWORD': os.getenv('PASSWORD'), 'HOST': os.getenv('DATABASE_HOST'), "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", } }, Aptfile: unixodbc unixodbc-dev As for the compatibility check, the SQL server is in-fact compatible with Driver 17. https://learn.microsoft.com/en-us/sql/connect/odbc/windows/system-requirements-installation-and-driver-files?view=sql-server-ver16 Complete error: File "/app/.heroku/python/lib/python3.11/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.11/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.11/site-packages/django/db/backends/base/base.py", line 211, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.11/site-packages/sql_server/pyodbc/base.py", line 312, in get_new_connection conn = Database.connect(connstr, ^^^^^^^^^^^^^^^^^^^^^^^^^ pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Client unable to establish connection (0) (SQLDriverConnect)') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/app/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/app/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 1354, in _fetch_all self._result_cache = list(self._iterable_class(self)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.11/site-packages/django/db/models/sql/compiler.py", … -
How to auto update data in react
Using react, I want to update chart data every 2 seconds from Django database but each 2 seconds charts component keeps recreating. how to prevent that from happening? In zoneActions.js : export const getZonesList = (cname) => async (dispatch, getState) => { try { dispatch({ type: ZONE_LIST_REQUEST }); const { userLogin: { userInfo }, } = getState(); const config = { headers: { "Content-Type": "application/json", Authorization: `Bearer ${userInfo.token}`, }, }; const { data } = await axios.get( `http://127.0.0.1:8000/zones/get/${cname}/`, config ); dispatch({ type: ZONE_LIST_SUCCESS, payload: data, }); } catch (error) { dispatch({ type: ZONE_LIST_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }); } }; dashboard.js : const { cname } = useParams(); const zoneList = useSelector((state) => state.zoneList); const { zones } = zoneList; useEffect(() => { dispatch(getZonesList(cname)); const interval = setInterval(() => { dispatch(getZonesList(cname)); }, 2000); return () => clearInterval(interval); }, [dispatch]); -
UserSignupForm.custom_signup() takes 2 positional arguments but 3 were given
I extended django-allauth's UserSignUpForm for a custom form upon signup but I got an error when I signed up in my local development server. UserSignupForm.custom_signup() takes 2 positional arguments but 3 were given Here's my form class UserSignupForm(SignupForm): type = forms.ChoiceField(choices=[("RECRUITER", "Recruiter"), ("SEEKER", "Seeker")]) def custom_signup(self, user): user.type = self.cleaned_data['type'] user.save() I expect it to be working since this isnt the first time I implemented this kind of signup form but I got lost in the rabbit hole. -
how can i extend barcode image to write caption and text?
I need to generate a barcode image like that one enter image description here like this I generated this one enter image description here -
Model has no attribute '_meta'
We're creating a API Documentation generation using drf_yasg. We Encountered a problem that says Model has no attribute '_meta'. I'm thinking of it as a model problem has anyone encountered similar error? Error Message Models.pu class TermsAndCondition(TimeStampedModel): company = models.ForeignKey(Company, related_name='terms_and_conditions', on_delete=models.CASCADE, blank=True, null=True) pdfUpload = models.FileField(upload_to=pdf_path, max_length=None, blank=True, null=True) def __str__(self): return self.company.name class Meta: app_label = "applicationname" The API Documentation supposed to be running at localhost/docs/ but since because of the problem it won't show -
Google App Engine deployment error 502: Bad Gateway with Django and Gunicorn
I am trying to deploy a Django application on Google App Engine using Gunicorn as the WSGI server. The application works well locally, but when deployed to App Engine, I encounter a 502: Bad Gateway error. I have checked the logs in Google Cloud Console and can't find any relevant errors. Here is my app.yaml configuration file: runtime: python311 entrypoint: gunicorn -b :$PORT --timeout 120 LyAnt.wsgi:application env_variables: DJANGO_SETTINGS_MODULE: "LyAnt.settings" ENV: "PRODUCTION" handlers: - url: /static static_dir: static/ - url: /.* script: auto automatic_scaling: min_idle_instances: 1 max_idle_instances: 2 min_pending_latency: 30ms max_pending_latency: automatic I tried running Gunicorn locally, but it does not work due to the "ModuleNotFoundError: No module named 'fcntl'" error. I understand that Gunicorn is not recommended for Windows environments, so I tested my application locally using Waitress, and it works fine. I expected my application to work on Google App Engine after deployment, but I am encountering a 502 error instead. -
How to convert Django Queryset into a list in template?
Here is my model : class Building(models.Model): Building_code = models.CharField(primary_key=True, max_length=255) Building_name = models.CharField(max_length=255) @property def BuildingFullName(self): fullname = '{} | {}'.format(self.Building_code, self.Building_name) return fullname def __str__(self): return self.Building_code What i do in my template : <tbody> {% for hira in hiras %} <tr> <td>{{ hira.Activity }}</td> <td>{{ hira.Hazard.Hazard }}</td> <td>{{ hira.PBS.Code }}</td> {% with allbuilding=hira.Building.all %} <td>{{ allbuilding }}</td> {% endwith %} <td>{{ hira.Building.Function_Mode }}</td> {% endfor %} </tbody> This is what I am getting : here But I would like the building list to be displayed without this "<Queryset". For the first row, it would be "13, 14". -
Local gulp not found inside docker container
I am trying to rebuild a past project regarding Django and gulp.js. Gulp is used to build the static assets from Django. I am now dockerizing this project. In order to do it, I am using a python and node combo image from this hub. I install the necessary packages both from Django and node. I copy the source code into the container. Run gulp and ./manage.py runserver. When I run gulp, I get an error that the local gulp cannot be found in the directory. app | [06:49:46] Local gulp not found in /usr/src/app app | [06:49:46] Try running: yarn add gulp I have this directory tree. The src/ holds the source codes and I copy this to the container. It holds the gulpfile.js and manage.py. . └── project/ ├── dockerfiles/ │ └── app.Dockerfile ├── src/ │ ├── apps/ │ ├── entrypoints/ │ │ └── entrypoint-local.sh │ ├── gulpfile.js │ ├── manage.py │ ├── package.json │ └── package-lock.json ├── .local.env └── docker-compose.yml Here is my docker-compose file. version: "3.9" app: container_name: app build: dockerfile: ./dockerfiles/app.Dockerfile entrypoint: ./entrypoints/entrypoint-local.sh volumes: - ./src:/usr/src/app - static:/static ports: - "8000:8000" env_file: - .local.env Here is how I build the app container. # syntax=docker/dockerfile:1 FROM … -
DRF Query optimization for nested_serializer with select_related queryset
This is My Model class PropertyBasic(Model): pass class ManagementProperty(Model): propertybasic = models.ForeignKey(PropertyBasic) class PropertyUnit(Model): management_property = models.ForeignKey(ManagementProperty) This is My queryset in view class PropertyUnitListView(ListAPIView): def get_queryset(self): return PropertyUnit.objects.all().select_related('management_property__propertybasic') This is My Serializer class PropertyUnitSerializer(serializers.ModelSerializer): property_basic = PropertyBasicSerializer(source='management_property.propertybasic') ... But why does similar query occur? The strangest part is that even if I don't load property_basic from serializer, the similar query is not lost. What can I do to remove these similar queries...?