Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS Instance EC2 - Ubuntu stops after sometime
i am new to AWS. I had my Python Django project setup to host on AWS using EC2 INSTANCE WITH UBUNTU. It works when i run the project. After a while, may be 5 minutes later, when the site or console is not in use, the site seems to be unreachable. It show 502 Bad Gateway nginx/1.24.0 (Ubuntu) . How can i solve this issue? I want my site to be reachable once all time once when i run the project. -
Error 500 - Internal Server Error on Django on Production server
I’m facing an issue with my Django application running in production on CPanel, and I'm using Passenger for WSGI. The application works fine on the local machine but on the live server it only works the root route (/), but all other routes return a 500 - Internal Server Error. I haven’t been able to pinpoint what’s causing the issue. Note: even a teste route like this returns the error 500 on live server: path('test/', lambda request: HttpResponse('Test route works!')), Main URL.py from django.urls import include, path from django.http import HttpResponse urlpatterns = [ path('', include('accommodation.urls')), path('test/', lambda request: HttpResponse('Test route works!')),#This works only on local machine ] Accommodation URL.py from django.urls import path from .views.dashboard_view import dashboard from .views.booking_view import newBooking,manageBooking,walk_in,walk_in_checkin,check_out,book_workspace,book_room,check_in,booking_requests,get_booking_request_details,delete_booking_request,workspace,check_bed_availability from .views.guest_view import new_client,new_guest,manageClient,manageGuest,update_guest,delete_guest from .views.room_view import roomList,room_and_bed_availability,roomMaintenance,stayView,stay_data,dirtyRoom,clean_bed from .views.settings_view import add_site,manageSite,roomCategory,addRoomCategory,editRoomCategory,bedManagement,addBed,roomManagment, workspaceManagment from .views.finance_view import Debits,payments,mark_as_paid,completedPayments,rates,processReport,costCenter from .views.incidents_medical import incidents,medical_cases,add_incident,add_case from .views.reports_view import generate,generate_report from .views.miscellaneous_view import meals,vehicleRent urlpatterns = [ # Dashboard Routes path('', dashboard, name='accommodation_dashboard'), #only this works on live server #Booking Routes path('new_booking/', newBooking, name='new_booking'), path('new_booking/book/', book_room, name='book_room'), path('manage_booking/', manageBooking, name='manage_booking'), path('manage_booking/check_in/<int:booking_id>/', check_in, name='check_in'), path('online_request/', booking_requests, name='online_request'), path('online_request/<int:booking_id>/', get_booking_request_details, name='get_booking_request_details'), path('online_request/check_bed_availability/<int:bed_id>/<str:checkin_date>/<str:checkout_date>/', check_bed_availability, name='check_bed_availability'), path('delete_booking_request/<int:booking_id>/', delete_booking_request, name='delete_booking'), path('booking/workspace', workspace, name='workspace'), #Check-in Routes path('check_in/', walk_in, name='check_in'), … -
What is the best way to write a serializer for enum and subsequent display in drf_spectacular?
I want to create a constructor for enum serializers to use them in views later and correctly display data in Swagger, especially in the schema. My typical enum: class EServicePlatform(models.IntegerChoices): ONLINE = 1, 'Online' OFFLINE = 2, 'Offline' Which are directly sent to views as a dictionary: django Copy code class DictionaryPlatforms(APIView): @extend_schema(responses={ 200: OpenApiResponse(response=DictionarySerializer(enum_class=EServicePlatform, many=True)), 400: OpenApiResponse(description='Bad Request')} ) def get(self, request, *args, **kwargs): data = [{"value": item.value, "label": item.label} for item in EServicePlatform] serializer = DictionarySerializer(data=data, many=True, enum_class=EServicePlatform) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The serializer constructor itself: class DictionarySerializer(serializers.Serializer): value = serializers.ChoiceField(choices=[]) # Set an empty list by default label = serializers.CharField() def __init__(self, *args, **kwargs): # Expect enum_class to be passed via kwargs enum_class = kwargs.pop('enum_class', None) if not enum_class: raise ValueError("enum_class is required") # Dynamically set choices based on the passed enum class self.fields['value'].choices = enum_class.choices super().__init__(*args, **kwargs) self.enum_class = enum_class def validate(self, data): # Automatically add the label corresponding to the value data['label'] = dict(self.enum_class.choices)[data['value']] return data In the current implementation, two problems arise: It seems to me that the logic is overly complicated and it can be significantly simplified. But how? For some reason, Swagger pulls data from a different … -
Django web application on azure deployment
I am trying to deploy my Django web application on azure. It is running fine with debug = true. but after deployment on azure app service with debug = False in settings.py, it is not able to load user uploaded media files in an iframe, saying URL not found. I am able to delete and move media files but i am not able to show using Iframe in HTML. This is settings.py: MEDIA_URL = '/media/' # URL for accessing media files MEDIA_ROOT = BASE_DIR / 'media' # Directory where files will be uploaded to this is urls.py: urlpatterns+= static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is html: <iframe src="{{ MEDIA_URL }}{{ row.document.url }}" title="Document View" frameborder="0" width="100%" height="600px"></iframe> I tried adding core headers, but it is not working. -
Django - show data across all views for selected year
I’m developing a learner tracking system which shows all data for administration and management views relating to the current academic year. AcademicYear model has a boolean field of is_current, this is used to filter related models by the returned pk of the object where is_current = True. How can I set up the system so the default views offer what I currently have set up but then offer the user an archive option where they select a year from a dropdown menu of is_current = False, and all views then show data relating to the selected year? -
Where to place a sitemap.xml file in my django project?
I created a sitemap.xml file using Screaming Frog and now I want to place it in my django project so that it is reacheable at example.com/sitemap.xml. But I am not sure where to put it? Where should I put it? -
Django MultipleChoiceField not sending valid data in POST
My django form has a field MultipleChoiceField in with a list of tuples as the options. choice = forms.MultipleChoiceField( choices = [("1", "Option 1"), ("2", "Option 2"), ("3", "Option 3")], label="Choose an option", widget=forms.Select(), required=True, ) This creates the DOM element when it is loaded <select name="choice" id="id_choice"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> However, when it sends the POST request on the form being submitted, instead of giving a value ("1", "Option 1"), it just sends "1". As such, this triggers a ValidationError in the MultipleChoiceField when it is validated, as it has this function which requires the POST value to be a list or a tuple. def to_python(self, value): if not value: return [] elif not isinstance(value, (list, tuple)): raise ValidationError( self.error_messages["invalid_list"], code="invalid_list" ) return [str(val) for val in value] Is there any way of setting the POST value of the DOM element so that it sends this tuple? I tried to change it in the views.py function using field.data, but got This QueryDict instance is immutable Thanks in advance. -
ModuleNotFoundError when Module is apparently installed, Django
My final project for my Python course is making a Pizza website using Django. I have the init.py, forms.py, main.py, manage.py, models.py, myapp.forms, settings.py, and a README.md, according to what Tabnine said I needed to run this. Every time I go to launch the website, instead of being able to access it on 127.0.0.1:8000, it doesn't launch, and at the end, it keeps giving me ModuleNotFoundError: No module named myapp.forms, despite it being there, installed as correctly as I can tell with Pylint, and I am at a loss. Contents of the README: PizzaProject/ ├── myapp/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py # Your OrderForm should be here │ ├── models.py │ ├── tests.py │ └── views.py ├── PizzaProject/ ├── manage.py └── settings.py init.py: from django.apps import AppConfig class MyappConfig(AppConfig): name = 'myapp' forms.py: from django import forms from django.db import models # Import models from django.db instead of django.models class OrderForm(forms.ModelForm): """Form for creating and updating Order instances.""" class Meta: """Meta class for OrderForm.""" model = models.Model # Use models.Model instead of django.models.Model fields = ['pizza', 'toppings', 'customer_name', 'customer_phone'] main.py: from django.shortcuts import render, redirect from myapp.forms import OrderForm from myapp.models import Pizza, … -
Why does Django use WSGI instead of CGI for web applications?
Is using wsgi similar with how cgi was used in django web deveelopment? and are there web developers that are using the latest version of python to build web app as it doesn't support CGI I was learning django by building a web app but I couldn't get CGI components cause I was using the latest python version update and WSGI was recommended to me. -
POST Requests from JS front to Django backend not working with Ngrok
I'm working on a web service with Python using Django. I used Ngrok to test it before deploying. My problem happens when the POST request I make in JavaScript in some endpoints just won't retreive any of the data required, instead they just return None. In the Django logs and the browser the response is 200 OK, but even in the logs the data isn't showing (I'm printing all the json data before return it). This is the way I'm making the POST requests in JS const url = 'http://localhost:8000/register_equipment/'; const data = { "product": inputProduct.value, "description": inputDescription.value, "serial": inputSerial.value, "warehouse_location": inputWarehouseLocation.value, "shelf_location": inputShelfLocation.value, "additional_location": inputAdditionalLocation.value, "observations": inputObservations.value, "quantity": inputQuantity.value, "dedicated": dedicatedValues }; // Request configuration const options = { method: 'POST', mode: 'cors', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') // Add CSRF token header }, body: JSON.stringify(data) }; // Perform the request using fetch fetch(url, options) .then(response => { if (response.ok) { return response.json(); // Convert the response to JSON } throw new Error('Request failed'); }) .then(responseData => { console.log(responseData.groups); // Handle response data }) .catch(error => { console.error('Error fetching group list:', error); // Handle errors }); This is the function I'm using to retreive the CSRF Token function … -
Django - VS Code - custom model manager method typing
I'm trying custom model managers to add annotations to querysets. My problem, which started as a little annoyance but I now realize can be an actual problem, is that VS Code does not recognise the methods defined in the custom model manager/queryset. Example: from django.db import models from rest_framework.generics import ListAPIView # models.py class CarQuerySet(models.QuerySet): def wiht_wheels(self): # NOTE: intentional typo pass # assume this does some annotaion class Car(models.Model): objects = CarQuerySet.as_manager() # views.py class ListCarsView(ListAPIView): def get_queryset(self): return Car.objects.wiht_weels() # <--- white instead of yellow At first, I was just annoyed by the fact that wiht_weels is printed in white as opposed to the usual yellow for methods/functions. Then I was more annoyed because this means VS Code will not give me any hints as to what args the method expects or what it returns. Finally, I accidentally made a typo on a name of one of these custom model methods, I hit refactor->rename, but it only renamed it in place, not on the places where it is used (views), probably because VS Code doesn't understand that method is being used anywhere. Is there a solution to this? -
How to receive data from client-side of websocket in Django using Channels
I’m trying to receive a websocket message on the server side. It is not being received. Am I misusing the function? How should this function be implemented as to receive messages and have the 30s live updates running in parallel. I have created a web server using Django Channels (Daphne) in Python. It is sending data async to the client via a websocket to live-update charts created using chart.js every 30 seconds. This all works fine. However, when the user makes a selection and a graph changes, I need new data to be sent immediately. So I'm trying to make a request: the client sends a request to the server via the websocket, the server then receives said request and sends data back to the client. My problem is, that the websocket is not receiving any data from the client, although everything seems to be alright. Am I misunderstanding how the functions are to be used? Any help will be appreciated! There are no errors in the log or console, neither server- nor client-side. See the code for my AsyncWebsocketConsumer: from asyncio import sleep from channels.generic.websocket import AsyncWebsocketConsumer from func.web_read import DatasetBuilder from datetime import datetime, timedelta, timezone class ChartDraw(AsyncWebsocketConsumer): … -
What is the best way to get an url parameter in a django translation?
So I have a site that sould support multiple languages, but when i have to translate a block with an url in it, i run into trouble. For example when I have something like: {% blocktrans %} This is an english sentence with a <a href="{% url 'app:link' %}">link <\a>. {% endblocktrans %} It raises an error as there can be no actions inside the blocktrans. So i tried to do it like: {% with link='{% url "app:link" %}' %} {% blocktrans %} This is an english sentence with a <a href="{{ link }}">link <\a>. {% endblocktrans %} {% endwith %} But sadly this also raises an error, saying: Could not parse the remainder: ''{%' from ''{%' Does anyone know how to add an url to the translation without an ugly split? A split like:" {% translate "this is an enlish sentence with a" %}<a href="{% url 'app:link' %}">{% translate "link" %}</a>. As in different languages there might be different amounts of text before and after the 'split'. As in this case there should be space after the text link in other languages. Does anyone know how to put the url in the translation? -
Django custom model queryset returns fields dynamically
I have a few models that are translatable. The way we implemented it was: for each translatable model, there is a ModelTranslation model. E.g. for the Car model exists a CarTranslation model with FK to Car. The translation models also have as fields: the language, and any text/char fields of the original model. E.g. if the Car model looks like this class Car(models.Model): name = models.CharField() description = models.TextField() the CarTranslation then looks like this: class CarTranslation(models.Model): car = models.ForeignKey(to=Car) language = models.CharField(choices=LANGUAGE_CHOICES) name = models.CharField() description = models.TextField() In views that return translatable data, we check what language the user has defined and, if it's not english (the default), return the translated data for that model and that language (if it exists, otherwise default to english). We have an old implementation of this that I want to improve: right now add the translations in the serializer context and then, in the serializer, we check if there are translations, otherwise return the default. But I don't like this. I think a much better solution would be using custom model managers/querysets. I'm trying this: from django.db.models.functions import Coalesce from django.db.models import F, Subquery class CarQuerySet(models.QuerySet): def with_translation(self, language): from cars.models import … -
Django Admin Custom Add
Say I have a model called Book: class Book(EOModel): title = models.CharField(max_length=100, null=False, blank=False) subtitle = models.CharField(max_length=100, null=True, blank=True) open_library_key = models.CharField(max_length=32, null=True, blank=True) ... location = models.ForeignKey(Order, null=False, blank=False, on_delete=models.PROTECT) The Book model has a classmethod to craete an entry using openlibrary ID. @classmethod def from_open_library(cls, open_library_key: str, location: Order) -> Self: data = open_library_get_book(open_library_key) ... book.save() return book So given a correct openlibrary ID and an Order object from_open_library would create a new entry. My question is, how can I implement an django admin page for it? Can I add a "add via openlibrary" next to the actual add button? The page has a char field to get the ID and dropdown would list the Orders to select. -
Changes detected after squashmigrations
python manage.py showmigrations shows mainapp [X] 0001_initial ... [X] 0240_employer_data [X] 0241_person_metadata [X] 0242_personemployer_employerworkplace [X] 0243_personemployer_employed_personemployer_stage [X] 0244_remove_employerworkplace_and_more I ran python manage.py squashmigrations mainapp 0244 and now showmigrations shows mainapp [-] 0001_squashed_0244_remove_employerworkplace_and_more (244 squashed migrations) Run 'manage.py migrate' to finish recording. But python manage.py migrate reports the errors No migrations to apply. Your models in app(s): 'mainapp' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. How can there be changes detected immediately after running squashmigrations without doing anything in between? python manage.py makemigrations --dry-run shows many "Alter field" lines like Migrations for 'mainapp': mainapp/migrations/0001_squashed_0244_remove_employerworkplace_and_more.py ~ Alter field field on employergroup ~ Alter field image_alt on employee ~ Alter field context on employer ... My expectation: After running squashmigrations, makemigrations should show "No changes detected" So what happened? What might have caused this bizarre situation? How might I fix it? -
Pytest fails with "ValueError: Missing staticfiles manifest entry for 'assets/img/favicon.ico' " while STATICFILES_STORAGE is set to default in tests
FAILED tests/test_views.py::test_index_view - ValueError: Missing staticfiles manifest entry for 'assets/img/favicon.ico' In my Django Template based project I have the error above when running pytests on views. Generally I understand what this is and how to deal with this when deploying BUT do not wish to worry about the static files manifest with these tests. The most obvios solution I found is to disable it by setting STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' in settings/test.py; this being the default, I shouldn't be worrying about the manifest entries any more, but it persists. I wrote a testcase to confirm that pytest infact uses this setting and that test case passes. In summary, why do I have a manifest entry error from tests running with the default STATICFILES_STORAGE setting and how do I specifically fix this? have tried a few other options but the general principle seems to be around changing the settings for STATICFILES_STORAGE. What am I missing/getting wrong? The simple view function: def index(request): return render (request, "main/index.html") The test cases i.e. tests/test_views.py: import pytest from django.urls import reverse from django.test import Client from django.conf import settings from main.models import SubscriptionPlan def test_static_storage(): print(settings.STATICFILES_STORAGE) assert settings.STATICFILES_STORAGE == 'django.contrib.staticfiles.storage.StaticFilesStorage' def test_index_view(): """ Test that the … -
Django: "KeyError: 'Django'"
The immediate traceback is this: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/template/utils.py", line 69, in __getitem__ return self._engines[alias] ~~~~~~~~~~~~~^^^^^^^ KeyError: 'django' During handling of the above exception, another exception occurred: Okay, here is the complete traceback: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/template/utils.py", line 69, in __getitem__ return self._engines[alias] ~~~~~~~~~~~~~^^^^^^^ KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/threading.py", line 1041, in _bootstrap_inner self.run() ~~~~~~~~^^ File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/threading.py", line 992, in run self._target(*self._args, **self._kwargs) ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) ~~^^^^^^^^^^^^^^^^^ File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run self.check(display_num_errors=True) ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/core/management/base.py", line 486, in check all_issues = checks.run_checks( app_configs=app_configs, ...<2 lines>... databases=databases, ) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/contrib/admin/checks.py", line 79, in check_dependencies for engine in engines.all(): ~~~~~~~~~~~^^ File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/template/utils.py", line 94, in all return [self[alias] for alias in self] ~~~~^^^^^^^ File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/template/utils.py", line 85, in __getitem__ engine = engine_cls(params) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/template/backends/django.py", line 26, in __init__ options["libraries"] = self.get_templatetag_libraries(libraries) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^ File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/template/backends/django.py", line 88, in get_templatetag_libraries libraries … -
Django not Working in ASGI app in second/defferent process
I have Django and FastAPI on process#1, and they work in Sync and Async functions with no problem. I am running the SocketIO app in process#2 with multiprocessing. ProcessusingAsyncServerandASGIApp. The problem is that Django works with Sync functions like get()orcreate(), but if we use aget()oracreate()` the process disappears and vanishes. The rest of the line never runs with no error. self.sio = socketio.AsyncServer( async_mode="aiohttp", cors_allowed_origins=self.socket_config.cors_allowed_origins, always_connect=self.socket_config.always_connect, logger=self.logger if self.socket_config.logger else False, engineio_logger=self.logger if self.socket_config.engineio_logger else False, ) self.socket_application = socketio.ASGIApp(self.sio, socketio_path=self.socket_config.socketio_path) and run it with uvicorn with pro multiprocessing.Process( target=uvicorn.run, kwargs={ "app": "0.0.0.0", "host": 8002, "port": int(service_config.SERVICE_PORT), }, daemon=True ).start() I have tried to add get_asgi_application() into other_asgi_app of socketio.ASGIApp but nothing changed. I think the problem isn't from the Django setting with async permissions, it is between the ASGIApp and Django. When it logged the self.socket_application from ASGIApp something interesting showed up, ...DjangoDBProcessRemove object .... I would be looking forward to any help. Update: If I run the SocketIO application in the main process works just fine. So I did. SocketIO in the main process and FastAPI in the Second with multiprocess, This time FastAPI faced this issue. -
I dont have intellisense in django while im using vscode
my vscode doest have intellisense for these things: settings.py: Ihave no intellisense in that file importing settings: when i do this: from django.conf import settings a = settings. # i have no intellisense after the dot too saving objects: when im using filter , get and etc in .objects i dont i have any intellisense. For example: from .models import Account user: Account = Account.objects.get() # i dont have any intellisense in get method even with filtering with Q method I try installing extenstions like django django-intellisense, django template but they dont work, also i try using mypy and django-stubs but they dont work too, and i try changing my vscode settings but none of them worked. my settings: { "djangointellisense.projectRoot": "C:/path/myprojectname", "djangointellisense.settingsModule": "myprojecctname.settings", "djangointellisense.debugMessages": false, "python.languageServer": "Jedi", "python.analysis.extraPaths": ["C:/path/myprojectname"], "python.autoComplete.extraPaths": ["C:/path/myprojectname"], "python.analysis.autoImportCompletions": true, } -
Relier plusieurs projets django à une même base des données? [closed]
J’essaye de creer une base des données postgreSQL qui sera commune à deux projets django qui utilisent les mêmes models Premièrement j’ai crée une application commune CommonModels dans le repertoire parents des deux projets django en utilisant django-admin startapp CommonModels ! Je l’ai installé en tant que module avec pip install -e CommonModels .Ensuite je l’ai inclus dans les deux projets django . Mais quand j’essay de mettre CommonModels dans installed_apps de chaque projet et que j’applique les migrations , une erreur d’importation de CommonModels dans installed_apps empêche l’execution des migrations! J’ai besoin d’aide pour la resolution de ce problème svp ! -
In Django are updates of dict within a form class from a view persistent for all users? [duplicate]
I use Django 5.1.2 In order to clarify what my users need to do when my app serves them a form, I've added a dict to my forms called 'contents'. It contains a bunch of instructions for the template form.html: class MyForm(forms.Form): contents = { 'icon' : 'img/some-icon.png', 'title' : 'Description of form', 'message' : 'Some instruction for user', 'value' : 'text-label-of-the button', } class Meta: fields = ('',) Then in the view myview the form.contents are updated according to what the view does: def myview(request): if request.method == 'GET': form = MyForm() form.contents.update({ 'icon' : 'img/wrong_red.png', 'title' : 'You did it wrong', 'color' : 'red', 'message' : 'Something user did wrong', 'value' : 'Cancel', }) context = {'form' : form} return render(request, 'form.html', context) I run into the problem that the updated content for color persist throughout multiple requests from users. I would expect that update to a value in a class instance wouldn't persist. In my memory this used to be the case. As a work-around I could make a unique form class for each view, but this would result in a lot of repetitive code. What is the best fix for this issue? -
HTMX Django not activating on form fields
I have a form with 3 select options, when the user selects the first one i updated the second with htmx, when the used selects the second i would like to update the third the same way. However, the third doesn't initialize the htmx request. Here is my django form: purchased_by = forms.ModelChoiceField( label="Empresa compradora", queryset=OurCompany.objects.filter(definecat=2).order_by('name'), widget=forms.Select(attrs={'class': 'form-control', 'hx-get': reverse_lazy('compras:oc_update_local'), 'hx-trigger': 'change', 'hx-target': '#div_local', 'hx-swap': 'outerHTML'}), ) delivery_location = forms.ModelChoiceField( label="Local de Entrega/Obra", queryset=Empreendimento.objects.all().order_by('name'), widget=forms.Select(attrs={'class': 'form-control', 'hx-get': reverse_lazy('compras:oc_update_cc'), 'hx-trigger': 'change', 'hx-target': '#div_cc', 'hx-swap': 'outerHTML'}), ) This is my views: def oc_update_local(request): company = request.GET.get('purchased_by') empresa = OurCompany.objects.get(pk=company) if empresa.definecat == 1: if empresa.name[:5] == "Cabiu": company = OurCompany.objects.get(name='Cabiunas Inc') empreendimentos = Empreendimento.objects.filter( company=company).order_by('name') elif empresa.name[:5] == "Coque": company = OurCompany.objects.get( name='Coqueiral Agropecuaria Matriz') empreendimentos = Empreendimento.objects.filter( company=company).order_by('name') else: empreendimentos = Empreendimento.objects.filter( company=company).order_by('name') return render(request, "compras/partials/oc_update_local.html", {"empreendimentos": empreendimentos}) def oc_update_cc(request): local = request.GET.get('delivery_location') ccs = CentroCusto.objects.filter(imovel=local).order_by('name') return render(request, "compras/partials/oc_update_cc.html", {"ccs": ccs}) And this is my html template: <div class="form-row"> <div class="form-group col-3"> {{ form.purchased_by | as_crispy_field }} </div> <div class="form-group col-4" id="div_local"> {{ form.delivery_location | as_crispy_field }} </div> <div class="form-group col-4" id="div_cc"> {{ form.cc |as_crispy_field }} </div> </div> And i have a partial for each update, but the second never triggers. … -
Why is the JSONField data not displayed correctly in the vector tile response?
I’m encountering an issue with displaying data from a JSONField in a vector tile (MVT) in Django. The value of the data in the test_json_field column is as follows: { "look": "1", "at": 2, "some": "asdfjkl;", "JSON": [ { "data": 1234, "arranged": "(and how!)" }, "as an example" ] } In my code, I’ve defined the tile_fields as: tile_fields = ("start_time", "end_time", "test_json_field") However, when I render the view, I only see the following fields in the JSON response: { "start_time": "2024-12-12 08:00:00+00", "end_time": "2024-12-12 08:15:00+00", "at": 2, "look": "1", "some": "asdfjkl;", "layer": "trajectory" } But the other values in the test_json_field column (such as the JSON array) are not displayed. Here’s my code: The TrajectoryTileView class: `class TrajectoryTileView(VectorLayer): """ A view to represent trajectory data as a vector tile layer. """ model = Trajectory id = "trajectory" tile_fields = ("start_time", "end_time", "test_json_field") geom_field = "geom" def get_queryset(self): device_id = getattr(self, "device_id", None) queryset = Trajectory.objects.all() if device_id: queryset = queryset.filter(device__uid=device_id) return queryset` The TrajectoryMVTView class: `class TrajectoryMVTView(MVTView): """ MVTView handles one or more vector layers defined in the layer_classes attribute. """ layer_classes = [TrajectoryTileView] def get(self, request, *args, **kwargs): device_id = kwargs.get("device_id") for layer_class in self.layer_classes: layer_class.device_id = device_id … -
Dead lock found in django transaction with select_for_update function
I have two functions: one for updating data and one for reading data. When they run concurrently in two threads, a deadlock occurs. Does anyone know why? The database's isolation level is set to REPEATABLE-READ. sleep function is used to increase the likelihood of a deadlock occurring. @transaction.atomic() def func_change_data(): print("start") time.sleep(10) boos = Boo.objects.select_for_update(skip_locked=True).filter(pk=xxx) if not changes.exists(): return print("sleep") time.sleep(10) boo = boos.first() boo.stage = 'stage_2' boo.save() print("end") @transaction.atomic() def func__read(): boo = Boo.objects.select_for_update().get( pk=xxx, target_branch='master', stage='stage_1' ) time.sleep(10) print("end sleep")