Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selenium "ERR_CONNECTION_RESET" using headless on Heroku
I have a Django + Selenium app I'm trying to deploy to Heroku. I have a management command I call that activates a Selenium Webdriver to use. Whenever I run it locally it's totally fine (without headless) however upon deploying to Heroku no matter what I try I just get: Message: unknown error: net::ERR_CONNECTION_RESET (Session info: headless chrome=116.0.5845.140) I instantiate my webdriver as follows: ... logger.info("Starting selenium webdriver...") options = Options() options.add_argument("--headless") options.add_argument("--disable-dev-shm-usage") options.add_argument("--no-sandbox") options.add_argument("--disable-gpu") options.add_argument("--enable-logging") options.add_argument("--incognito") options.add_argument("--ignore-certificate-errors") options.add_argument("--disable-extensions") options.add_argument("--dns-prefetch-disable") self.webdriver = webdriver.Chrome( service=Service(ChromeDriverManager().install()), options=options ) I think the issue is the headless argument - adding it locally at least is what breaks things, however. This is running on Heroku so I need the headless to work. I'm really stumped. Any help/advice is appreciated - thank you! -
drf-spectacular produce array of dict instead of dict
This is my GET request with drf-spectacular for swagger generation: @extend_schema(request=None,response=RespondentResponseTransactionalWithQuestionGetSerializer(many=False) ) def get(self, request, *args, **kwargs): This is Serializer itself: class RespondentResponseTransactionalWithQuestionGetSerializer(serializers.Serializer): answers = RespondentResponseTransactionalGetSerializer(many=True) general_question = GeneralQuestionResultTransactionalPostSerializer(required=False) which I expect to produce an object similar to this: { "general_question": { "id": 0, "value": "string", "employee": 0, "general_question": 0 }, "answers": [ { "employee": 0, "activity": 0, "fte": 99999, "values": [ { "value": 2147483647, "subdimension": 0 } ], "custom_fields": [ { "value": "string", "custom_field": 0 } ] } ] } But instead of this I getting an array of similar objects according to swagger documentation: [ { "general_question": { "id": 0, "value": "string", "employee": 0, "general_question": 0 }, "answers": [ { "employee": 0, "activity": 0, "fte": 99999, "values": [ { "value": 2147483647, "subdimension": 0 } ], "custom_fields": [ { "value": "string", "custom_field": 0 } ] } ] }] Any ideas on how to make it looks properly? I tried many=False, without many but nothing of that seems to work for me. -
Browser not saving cookies but Set-Cookie headers present
I am using React frontend and Django backend and have been struggling for days with authentication. I have boiled down the issue I am having to the browser not setting the cookies it receives from the backend. When in inspect, I can verify that the Set-Cookie headers are present in the response. They are not appearing in storage though... (the cookies are a csrf token and session id). Other functionalities dependant on these cookies like logout fail. However, when using the Django rest framework interfaces (connecting to the backend urls, e.g., localhost:8000/users/login/), I can perform the login and over there, the cookies appear in storage. I have tried both fetch and axios, I have included credentials: 'include' and withCredentials: true respectively. As a final note, when using fetch, I grab the response fetch(url, { ... }) .then(res => console.log(res.headers.get('Set-Cookie'))) When this prints null, when looping over all present headers I only see two (like application json). For reference some screenshots. These are all the cookies present, I am expecting to see csrftoken and session. The next image shows the headers, there are two Set-Cookie headers with both sessionid and csrftoken. And finally the cookies from the response I have enabled … -
Forms with HTMX, how to choose where to post?
I have a page '/ask-tagname' with an html form <form hx-post="/set-tagname"> <label for="tagName">Tag Name:</label> <input type="text" id="tagName" name="tagName" required /> <button >Submit</button> </form> I am serving this by Django and the views file serving both endpoints is the following from django.shortcuts import render, redirect from django.core.handlers.wsgi import WSGIRequest from lobby.models import Users from django.http import HttpResponse def ask_tagname(request: WSGIRequest): return render(request, "tag_name_entry.html", {}) def set_tagname(request: WSGIRequest): tagName = request.POST["tagName"] defaults = {"tag_name": tagName} print(defaults) Users.objects.update_or_create(id=user_id, defaults=defaults) response = HttpResponse() response["HX-Redirect"] = "/" return response when I click on the submit button I get a GET request to '/ask-tagname' with the tagname as url parameter followed by an empty POST to '/set-tagname'. What I expected is no more calls to '/ask-tagname' and instead a post request to '/set-tagname' with tagname as parameter. -
Book an appointment in Django
I 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 book at the same time How I can Do This in Models Django I could not find a solution to this problem -
make prestashop store in a django subdomain
good afternoon everyone, I have my website made with django (python app), hosted in the domain www.cannareis.com.ar. but I want to add a virtual store using prestashop. Thanks to my hosting provider, I can download prestashop directly from the Cpanel of my website. Since I already have my page made with django, I don't want or can't put my page made with prestashop in the same domain, so I created a subdomain called www.tienda.cannareis.com.ar. but when I want my prestashop to be hosted there, it doesn't let me and the first thing that appears when I enter is the django error message, asking me to put the domain in allowed hosts. I don't understand why the django message appears if I'm on a subdomain, I'm not on the original domain where I put my django app. I tried to register the subdomain in allowed hosts (settings.py) but when I do that, when I enter the subdomain www.tienda.cannareis.com.ar , the main template of my web page appears, that is, the "home". and to access the prestashop page I have to add /es to the url. that is to say, it remains www.tienda.cannareis.com.ar/es/ or putting anything after the / takes me to … -
How can I use a Django template variable inside a HTML tag attribute?
Im trying to make a wikipedia clone for studying purposes, 'encyclopedia' is my django app name and {{entry}} its a wiki page. My code line looks like this : <a href="{% url 'encyclopedia:{{entry}}'%}">, I searched in google but cant find anyone talking about django variables inside HTML tag atributtes. When I run my code i see this error: `NoReverseMatch at / Reverse for '{{entry}}' not found. '{{entry}}' is not a valid view function or pattern name. ` -
Why does my Django view return a download of a file path instead of the actual file?
I am making a website that takes a user's file, translates the text in the file and returns it when they click the download button. However my website is returning an HTML file containing the file path instead of the actual file. I tried changing the response to a FileResponse but the result didn't change. I am using Django as the backend. Here is my code: HTML: <button id="download-btn" class="upload" type="submit" name="download_file"> <svg width="25" height="25" viewBox="0 0 24 24"> <circle cx="12" cy="12" r="11.5" fill="transparent" stroke="white" stroke-width="1"/> <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z" fill="grey" /> </svg> <a id="response_text_anchor" href="" download><p id="response_text"></p></a> </button> JS: xhr.open('POST', form.getAttribute('action'), true); xhr.onreadystatechange = function () { console.log("Ready state: ", xhr.readyState); console.log("Status: ", xhr.status); if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { loaderDiv.style.display = 'none'; const downloadArrowDiv = document.querySelector('#download-btn'); downloadArrowDiv.style.display = 'flex'; const responseTextAnchor = document.querySelector('#response_text_anchor'); responseTextAnchor.href = URL.createObjectURL(xhr.response); // Set href to the translated file link const responseText = document.querySelector('#response_text'); responseText.textContent = 'Click to download'; // File was successfully translated, you can update UI here } else { // Handle error case console.error('Error translating file'); } } }; xhr.responseType = 'blob'; xhr.send(formData); }); views.py: The user uploads a file and clicks submit. When they … -
why the django choice field wont set the inital value?
i have a choice field like below def status_field(): return forms.ChoiceField( choices=[ (len(contract_status := Contract.Status.choices), 'all'), *contract_status ], widget=forms.Select(CUSTOM_SELECT_ATTRS), label='status', initial=Contract.Status.ACCEPTED ) Which is for Conract model and uses its Status Choice list which is like below class Status(models.IntegerChoices): PENDING = 1, 'pending' ACCEPTED = 2, 'active' REJECTED = 3, '...' TERMINATED = 4, '...' ON_HOLD = 5, '...' FINISHED = 6, '...' my form looks like this : class FilterForm(BaseFilterForm): __fields = ( 'contract_status', ...) contract_status = contract_status_field() i want the inital value to be active but it does not change i have tried to set it as 2 or {2 ,'active'} and Contrac.Status.ACCEPTED also i have tried to change it's value inside init . but it did not work ! Why ? how to do this? -
How to optimize Django view for performance?
I am wondering what the best practices are for optimizing view performance. I have this view that takes over 90 seconds to load (with 5 queries, 2 of which take the bulk of time). It has some complex queries, which a few Subqueries and a bunch of calculations. Should I try to split all these calculations in different views, use async for the calculations or use caching (I am fairly new to programming and Django)? def dispatchers_list(request): tenant = get_tenant(request) print("CURRENT_WEEK_CUSTOM: ", CURRENT_WEEK_CUSTOM) if request.method == 'GET': if request.GET.get('date_range') is not None: date_range = request.GET.get('date_range') date_start = datetime.datetime.strptime(date_range.split('-')[0].strip(), '%m/%d/%Y') print("date_start: ", date_start) date_end = datetime.datetime.strptime(date_range.split('-')[1].strip(), '%m/%d/%Y') custom_week_nr = get_week_number(date_end.date()) year = int(date_end.strftime("%Y")) date_start_string = date_start.strftime('%m/%d/%Y') date_end_string = date_end.strftime('%m/%d/%Y') else: date_start = start_week_nr(CURRENT_YEAR, CURRENT_WEEK_CUSTOM-1) date_start = datetime.datetime.combine(date_start, datetime.datetime.min.time()) date_end = date_start + datetime.timedelta(days=7) custom_week_nr = get_week_number(date_end.date()) year = int(date_end.strftime("%Y")) date_start_string = date_start.strftime('%m/%d/%Y') date_end_string = date_end.strftime('%m/%d/%Y') date_range = f"{date_start_string} - {date_end_string}" date_start_miles = datetime.datetime.combine(date_start - datetime.timedelta(days=7), datetime.datetime.min.time()) date_end_miles = date_start_miles + datetime.timedelta(days=14) # Calculate company rate per mile for last 2 weeks company_loads_last_2_weeks = Load.objects.filter(drop_date__gte=date_start_miles, drop_date__lt=date_end_miles).exclude(load_status='Cancelled').aggregate(billable_amount=Sum('billable_amount'), total_miles=Sum('total_miles')) if company_loads_last_2_weeks['billable_amount'] is not None and company_loads_last_2_weeks['total_miles'] is not None: company_rate_per_mile = company_loads_last_2_weeks['billable_amount'] / company_loads_last_2_weeks['total_miles'] else: company_rate_per_mile = 0 loads_subquery = Load.objects.filter( customer=OuterRef('customer'), # Reference … -
next-auth: Axios raises connect ECONNREFUSED ::1:8000 when sign-in to django
Stack Backend: django (dj_rest_auth for authentication) Frontend: nextjs (next-auth for authentication, environment variables are set correctly.) OS: Debian 12 - bookworm Dependencies: redis, memcached, rabbitmq running inside LXD - Ubuntu 22.04 container Summary i have a nextjs(13+)+django(4.2+) application up and running on my localhost, now i am at the stage of adding authentication. i am using next-auth(4.22+) to handle the authentication part. When i try to sign in, i get this error AxiosError: connect ECONNREFUSED ::1:8000, every other request made by axios go through except the login one. i have read other answers but none worked for me... Error { error: AxiosError: connect ECONNREFUSED ::1:8000 at AxiosError.from (file:///home/yuri/Coding/pos/frontend/node_modules/axios/lib/core/AxiosError.js:89:14) at RedirectableRequest.handleRequestError (file:///home/yuri/Coding/pos/frontend/node_modules/axios/lib/adapters/http.js:591:25) at RedirectableRequest.emit (node:events:514:28) at eventHandlers.<computed> (/home/yuri/Coding/pos/frontend/node_modules/follow-redirects/index.js:14:24) at ClientRequest.emit (node:events:514:28) at Socket.socketErrorListener (node:_http_client:501:9) at Socket.emit (node:events:514:28) at emitErrorNT (node:internal/streams/destroy:151:8) at emitErrorCloseNT (node:internal/streams/destroy:116:3) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) { port: 8000, address: '::1', syscall: 'connect', code: 'ECONNREFUSED', errno: -111, config: { transitional: [Object], adapter: [Array], transformRequest: [Array], transformResponse: [Array], timeout: 0, xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFToken', maxContentLength: -1, maxBodyLength: -1, env: [Object], validateStatus: [Function: validateStatus], headers: [AxiosHeaders], baseURL: 'http://localhost:8000', withCredentials: true, paramsSerializer: [Object], method: 'post', url: '/api/auth/login/', data: '{"username":"yuri","password":"yuri","redirect":"false","csrfToken":"80d0b198ee09f1abc790d722d42e6fa48a0e38c78a77d4e7c4bd340c9cbb9636","callbackUrl":"http://localhost:3000/auth/sign-in?from=%2Fprofile","json":"true"}' }, request: Writable { _writableState: [WritableState], _events: [Object: null prototype], _eventsCount: 3, _maxListeners: undefined, _options: … -
Limit number of query to show in a table using django
i have a query in django and want to show only 15 entries by page in my table but i want to avoid datatables if i can, if anyone can tip me a solution will be thanks. here is my table it work fine but i want to limit the number of clientes show to 15 and if posible add pagination i i dont know how to do it. <table class="table"> <thead> <tr class="text-center"> <th scope="col">#</th> <th scope="col">R.U.N</th> <th scope="col">Nombre y Apellidos</th> <th scope="col">Edad</th> <th scope="col" colspan="6">Acciones</th> </tr> </thead> <tbody> {% for cliente in clientes %} <tr class="text-center"> <td scope="row">{{forloop.counter}}</td> <td>{{cliente.runCliente}}</td> <td>{{cliente.nombreCliente}}</td> <td>{{cliente.edadCliente}}</td> <td>{{cliente.cargoCliente}}</td> <td> {% for empresa in empresas %} {% if cliente.empresa_id == empresa.id %} {{empresa.nombreEmpresa}} {% endif %} {% endfor %} </td> <td><a href="{% url 'edit_cliente' cliente.id %}" class="btn btn-success btn-md"><i class="bi bi-pencil-square"></i></a></td> <td><a href="{% url 'delete_cliente' cliente.id %}" class="btn btn-danger btn-md"><i class="bi bi-trash"></i></a></td> <td><a href="{% url 'add_registro' cliente.id %}" class="btn btn-info btn-md"> <i class="bi bi-plus-square"></i></a></td> <td><a href="{% url 'get_registrosCliente' cliente.id %}" class="btn btn-primary btn-md"> <i class="bi bi-search"></i></a></td> </tr> {% endfor %} {% endif %} </tbody> </table> my view.py function is very simple i only pass the cliente to list them all def manage_cliente(request): clientes = Cliente.objects.all() … -
ModuleNotFoundError: No module named 'littlelemonApi'
``your tPerforming system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self.kwargs) File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site- packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\urls\resolvers.py", line 494, in check for pattern in self.url_patterns: ^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\utils\functional.py", line 57, in get res = instance.dict[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\utils\functional.py", line 57, in get res = instance.dict[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\importlib_init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "", line 1204, in _gcd_import File "", line 1176, in _find_and_load File "", line 1147, in _find_and_load_unlocked File "", line 690, in _load_unlocked File "", line 940, in exec_module File "", line 241, in call_with_frames_removed File "C:\Users\USER\LittleLemon\littlelemon\littlelemon\urls.py", line 23, in path('api/',include('littlelemonApi.urls')), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\urls\conf.py", line 38, in include urlconf_module … -
Django Ajax to trigger a view not working
I'm trying to trigger a view by clicking a html button in a template. template (test.html) <div id="test_count"></div> <input type="button" value="Get number of records in DB" onclick="numberec()" /> <script> function numberec() { $.ajaxSetup( {data: {csrfmiddlewaretoken: '{{ csrf_token }}'}, }); $.ajax({ type: "POST", url: "../number_of_rec/", success: function (data) { $("#test_count").html({{number_of_rec}}); } }) } </script> View.py def number_of_rec(request): number_of_rec = Record.objects.count() data2 = render(request, 'test.html', {'number_of_rec': number_of_rec}) return (data2) def test(request): return render(request, 'test.html') urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('number_of_rec/', views.number_of_rec, name='number_of_rec'), path('test/', views.test,name='test'), ] When I go to https://my_web_app.com/test in the web browser, the button doesn't trigger the number_of_rec view and the div is not filled with the result. BUT if I trigger the view by going to https://my_web_app.com/number_of_rec in web browser, the button is working and fill the div with the expected result. What should I do for my Ajax to trigger the number_of_rec view from the test.html page or any other page ? I'm a bit lost ... Thanks -
Rotation of the sphere in the photo with CSS
I want this hemisphere in the photo related to Wikipedia to rotate inward with only HTML and CSS codes (like the movement of the earth). The code that I sent below rotates the entire image, and it is also a 360-degree rotation, not an inward rotation. <img src="{% static "wiki.jpg"%}" alt="wiki.jpg"> img{ border-radius: 100px; margin-top: 400px; } @keyframes img { 0%{ transform: rotate(0deg); } 100%{ transform: rotate(360deg); } } img{ animation: img 20s ease-in-out infinite; } IMAGE If it is not possible to do this with this image, how can I design a similar image? -
PermissionError: [Errno 13] Permission denied: '/app/core/migrations/0005_recipe_image.py'
when i am trying makemigrations on dockerised django application, got this permissionError Here is Dockerfile: FROM python:3.9-alpine ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt requirements.txt RUN pip install --upgrade pip && \ apk add --update --no-cache jpeg-dev && \ apk add --update --no-cache --virtual musl-dev zlib zlib-dev && \ pip install -r requirements.txt &&\ adduser \ --disabled-password \ --no-create-home \ django-user && \ mkdir -p /vol/web/media && \ mkdir -p /vol/web/static && \ chown -R django-user:django-user /vol && \ chmod -R 755 /vol USER django-user COPY . . Here is docker-compose.yml: version: "3.9" services: app: build: . volumes: - ./app:/app - dev_static_data:/vol/web ports: - 8000:8000 image: app:django container_name: django_container command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" depends_on: - db environment: - DB_HOST=db - DB_NAME=postgres - DB_USER=postgres - DB_PASS=postgres db: image: postgres volumes: - postgres_db:/var/lib/postgresql/data/ environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: postgres_db volumes: postgres_db: dev_static_data: When i run: docker-compose run --rm app sh -c "python manage.py makemigrations", the error message is: [+] Creating 1/0 ✔ Container postgres_db Running 0.0s Migrations for 'core': core/migrations/0005_recipe_image.py - Add field image to recipe Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() … -
How to add inline form to Inline form in django admin?
how do i make 2 nesting levels with default django admin methods (i want include C fields to form) models.py example Example: class A(models.Model): title=models.CharField(max_length=100) class B(models.Model): title=models.CharField(max_length=100) block_a=models.OneToOneField(A,on_delete=models.CASCADE,related_name="block_b") class C(models.Model): title=models.CharField(max_length=100) block_b=models.ForeignKey(B,on_delete=models.CASCADE,related_name="block_c") page example how i can create django admin model with inline form in inline form form example: title(class A) other_fields B: title(class B) other_fields C: title(class C) other_fields C: title(class C) other_fields C: title(class C) other_fields admin.py #its work class AInline(admin.StackedInline): model = A form = AForm class B(admin.ModelAdmin): model = B form = BForm but how do i make 2 nesting levels with default django admin methods (i want include C fields to form) -
I was trying to implement SOLID Principles. this time Dependency inversion in Python - Django
TypeError: SignInView.init() missing 1 required positional argument: 'api_response_factory' I try to use abstract methods but it failed. I'm new about SOLID implementation and new in python too, can someone give me an advice or idea about how to deal with this kind of erros? I have to add that this is my first time asking in stackoverflow from abc import ABC, abstractmethod from rest_framework.views import APIView from django.http import JsonResponse from rest_framework import status class ApiResponseFactoryAbstract(ABC): @abstractmethod def success(self) -> str: pass class ApiResponseFactory(ApiResponseFactoryAbstract): def success(self) -> str: print("Testing") return "Testing" class SignInView(APIView): def __init__(self, api_response_factory: ApiResponseFactoryAbstract): self.api_response_factory = api_response_factory def post(self, request): data = self.api_response_factory.success() return JsonResponse(data=data, status=status.HTTP_200_OK) This is app/urls.py: from django.urls import path from . import views router_auth = [ path("sign-in/", views.SignInView.as_view(), name="sign-in"), ] -
Saving a image with blob type on mysql using django and ReactJS
I would like to save a blob in mysql using django , but I have the following problem sometimes the image is saved as none and sometimes it gives a bad request problem, how can I solve this? Here my view.py: class RegiaoAPIView(APIView): serializer_class = RegiaoSerializer def get(self, request, pk=None, format=None): try: if pk is None: regioes = Regiao.objects.all() serializer = self.serializer_class(regioes, many=True) return Response(serializer.data) else: regiao = Regiao.objects.get(pk=pk) childs = Regiao.objects.filter(id_regiao_superior=regiao) serializer = self.serializer_class(regiao) serializer_apontando = self.serializer_class(childs, many=True) response_data = { "regiao": serializer.data, "childs": serializer_apontando.data if pk else None } return Response(response_data) except Regiao.DoesNotExist: return Response({"detail": "No Regioes found"}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({"detail": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def post(self, request): try: # print("Dados binários da imagem:", request.data.get('imagem')) print("Entrou na view de criação") imagem_base64 = request.data.get('imagem', None) new_data = request.data.copy() if imagem_base64: print("Entrou no tratamento de imagem") imagem_bytes = base64.b64decode(imagem_base64) new_data['imagem'] = imagem_bytes poligono_valor = request.data.get('poligono', None) extend_valor = request.data.get('extend', None) poligono_resultante = createPolygon(poligono_valor) if extend_valor is not None: new_data['extend'] = json.dumps(extend_valor) new_data['poligono'] = poligono_resultante print("Dados antes da serialização:", new_data) serializer = self.serializer_class(data=new_data) if serializer.is_valid(): print("Dados válidos, criando objeto...") serializer.save() print("Objeto criado com sucesso") return Response(serializer.data, status=status.HTTP_201_CREATED) else: print("Erros de validação:", serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as e: … -
Django/CSS static files not loading
I am using a template to make a customized website. However some static files are loading and some are not. I get a red underline in my text editor in these locations: <section class="dento-service-area section-padding-100-0 bg-img bg-gradient-overlay jarallax clearfix" style="background-image: url({% static 'website/img/bg-img/13.jpg' %});"> <div class="container"> Any help in CSS formatting is appreciated. -
How to do mobile notifications with Django backend and flutter frontend? [closed]
I have a Flutter front-end mobile (iOS) app with a Django backend. I have a feature where I create posts and tag people. So when a creator publishes the post, the data is stored in the backend, Django. And also reflects on the tagged people's homepages when they reopen or refresh their app. Now I am planning to add a notification system in the app, where the post publishing should also alert the tagged people with a notification that they have been tagged. With a quick google seems like there are 2 ways to do it and I am confused about which one is feasible: Approach 1: When the creator publishes the post, have a concurrent command to send FCM notifications to the invited mobiles. Here, I won't be dealing with the backend at all. This ‘frontend-originating’ notifications seem easy as I don't have to deal with backend Django at all. Approach 2: Once the data is stored in the backend, send a django-fcm notification to alert the devices. This seems like a robust solution, as I think, in the future, IF I add backend computations and want to alert the user, I will have a ‘backend-originating’ notification already set … -
Django ManyToMany get error 'Object of type QuerySet is not JSON serializable'
i have this issue on my application. Object of type QuerySet is not JSON serializable In fact, i creating an application in which we have a relationship of the type several Products inone or more Orders. Here is my code : models.py # model Product class Products(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=500) class Meta: db_table ="products" # model Order class Orders(models.Model): order_id = models.AutoField(primary_key=True) order_number = models.CharField(max_length=500) supply = models.ForeignKey(Supplies, on_delete = models.CASCADE) statut = models.CharField(max_length=500, default="validé") date_of_order = models.DateField() products = models.ManyToManyField(Products, through='OrderProduct') class Meta: db_table ="orders" # model OrderProduct class OrderProduct(models.Model): Order = models.ForeignKey(Orders, on_delete=models.CASCADE) product = models.ForeignKey(Products, on_delete=models.CASCADE) product_quantity = models.PositiveIntegerField(default=1) class Meta: db_table ="ordersproducts" views.py # OrderGetAllApi @csrf_exempt def order_list(request): orders = Orders.objects.select_related('supply').all # orders = Orders.objects.select_related('products').all() order_list = [] for order in orders: order_list.append({ 'order_id': order.order_id, 'order_number': order.order_number, 'date_of_order': order.date_of_order, 'supply_id': order.supply.supply_id, 'supply_name': order.supply.supply_name, 'supply_address': order.supply.supply_address, 'products': order.products.all() }) return JsonResponse(order_list, safe=False) serializers.py class OrderProductSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = OrderProduct fields = ['product_id', 'product_name', 'product_quantity'] # fields = '_all_' class OrderSerializer(serializers.ModelSerializer): supply = SupplySerializer() products = OrderProductSerializer(many=True) class Meta: model=Orders fields=('order_id', 'order_number', 'date_of_order', 'statut', 'supply', 'products') I want to get the list of order with their respective products. when i enter … -
I got this error while making migration . module got error and for frozen importlib
I like to get file in postgreSQL . so i want to do migration so i got these error. there is more than model error like frozen importlib like error so help me to clear the error. I Expect the code and migrate successfully. File "J:\good\mainone\manage.py", line 22, in <module> main() File "J:\good\mainone\manage.py", line 18, in main execute_from_command_line(sys.argv) File "J:\good\test\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "J:\good\test\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "J:\good\test\Lib\site-packages\django\core\management\base.py", line 425, in run_from_argv connections.close_all() File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 84, in close_all for conn in self.all(initialized_only=True): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 76, in all return [ ^ File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 73, in __iter__ return iter(self.settings) ^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 45, in settings self._settings = self.configure_settings(self._settings) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\db\utils.py", line 148, in configure_settings databases = super().configure_settings(databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 50, in configure_settings settings = getattr(django_settings, self.settings_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "J:\good\test\Lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 128, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", … -
Django Heroku /GET Favicon.Ico when running heroku logs --tail
My Heroku build is complete, but the application is not booting for some reason. When I run heroku logs --tail, 2023-09-04T13:32:07.484629+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=journallove-e9a7a6e26520.herokuapp.com request_id=3515dc4d-fb0c-4ccb-bbdc-cb81a1ae5a31 fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:07.768182+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=journallove-e9a7a6e26520.herokuapp.com request_id=8c703a21-5109-4f0a-af7a-22c0e2687c8a fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:14.000000+00:00 app[api]: Build succeeded 2023-09-04T13:32:35.613845+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=journallove-e9a7a6e26520.herokuapp.com request_id=6c9caf84-4fb9-4a08-96ea-ee41bae09184 fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:35.808771+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=journallove-e9a7a6e26520.herokuapp.com request_id=cd6e61e2-ee17-4f5e-abb4-c2ca33636d17 fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:45.705631+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=journallove-e9a7a6e26520.herokuapp.com request_id=5d813e56-e116-4432-86f5-1ba43ba9227b fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:45.899516+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=journallove-e9a7a6e26520.herokuapp.com request_id=14f662de-7547-40d0-bee9-522e847922c4 fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https`` these are the issues that pop up. This is my Procfile and req.txt. web gunicorn journallove.wsgi:application --log-file - ` asgiref==3.6.0 blind==0.0.1 blinker==1.6.2 certifi==2023.5.7 charset-normalizer==3.1.0 click==8.1.3 cloudpickle==2.2.1 Cython==0.29.35 distlib==0.3.6 dj-database-url==2.1.0 Django==4.2.1 entrypoints==0.4 filelock==3.12.2 Flask==2.3.2 gitdb==4.0.10 GitPython==3.1.31 greenlet==2.0.2 gunicorn==20.1.0 django-heroku==0.3.1 idna==3.4 itsdangerous==2.1.2 Jinja2==3.1.2 joblib==1.3.1 MarkupSafe==2.1.2 mysql-connector-python==8.0.33 mysqlclient==2.1.1 nltk==3.8.1 numpy==1.24.3 package-json==0.0.0 pandas==2.0.1 platformdirs==3.8.1 protobuf==3.20.3 psycopg2-binary==2.9.7 PyMySQL==1.0.3 pytz==2023.3 PyYAML==6.0 querystring-parser==1.2.4 regex==2023.6.3 requests==2.31.0 six==1.16.0 smmap==5.0.0 SQLAlchemy==2.0.15 sqlparse==0.4.4 templates==0.0.5 tqdm==4.65.0 typing_extensions==4.6.2 tzdata==2023.3 urllib3==2.0.2 views-py==2.0.0 virtualenv==20.23.1 Werkzeug==2.3.4` I tried to move … -
Connecting Django Application in One Docker Container to MySQL in Another Container
Title: "Connecting Django Application in One Docker Container to MySQL in Another Container" I have a setup with two Docker containers: mysql-container: This container runs a MySQL image. my-django-container: It hosts a functional Django application. My objective is to establish a connection between the Django application running in my-django-container and the MySQL server in mysql-container. However, I'm encountering a database connection error: django.db.utils.OperationalError: (2002, "Can't connect to server on '36.253.8.13' (115)") Here are my Django settings for the database: "default": { "ENGINE": "django.db.backends.mysql", "NAME": "name", "USER": "username", "PASSWORD": "password", "HOST": "172.18.0.2", # What should I put here? The actual IP of the server `36.253.8.13` or the IP of the SQL container `172.18.0.2`? "PORT": "3306", # Is this the default port for SQL? } I've also placed both containers in the same Docker network, and I can confirm that both containers are visible when I inspect the network using the docker network inspect command. As a Docker novice, I would greatly appreciate any assistance in resolving this issue.