Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Filter an String as Integer?
I have a problem when I need to make my filter: I need that Django compare a String field as Integer (Almost the entire table are Integers) This don't work, because only return the entry with 9, not with 12 or 13. queryset = Cards.objects.extra(select={'stars': 'CAST(stars AS INTEGER)'}).filter(stars__gte= 9) I tried also this: Cards.objects.annotate(stars_integer=Cast('stars', output_field=IntegerField())).filter(stars__gte= 9) With the same result, and I can't change the field to Integer because some values are Strings like "?" and "X" class Cards(models.Model): # CARD NAME name = models.CharField( max_length=128, null=False, unique=True, ) # AMMOUNT OF STARS stars = models.CharField( max_length=2, null=True, unique=False, default="", verbose_name="Stars" ) Thanks -
My django is returning a blank page after trying to go to a page with a form
I am new on django, so it may be a easy thing to solve, but I just can't see it myself. I am working on a Django project. It was already on, and I am just working on implementations. One of those implementations is to create a form for user to register allowed people. There is a page called "Persons", that permits user to search for someone and also displays a list of people already registered. I put a button, on that page for user click on it an go to the fom, add new allowed people. That button redirects to a page with this form, where user will type "name" and "userid" of the person. But everytime I trie to go to the page, it shows a blank page. I saw in some of the responses I found in my search, that since the page was not found, it is being redirect to home.html, that is in the web folder( that is empty). I will also put the code for a secondary problem, there is a button in home page, that when clicked redirects to a pdf file(tutorial). But the path is not recognized, this was implemented by the … -
Accessing a field in a through table in Django
I am using a through table on a many to many field and I am trying to get information to automate the submission of a form. I am having trouble accessing the fields in the through table. Here are my models: class ClientInformation(models.Model): client_id = models.AutoField(primary_key=True) client_custom_id = models.CharField(max_length=100, unique=True, null=True, blank=True) client_first_name = models.CharField(max_length=50) #required client_middle_name = models.CharField(max_length=50, blank=True, null=True) client_last_name = models.CharField(max_length=50) #required client_dob = models.DateField() #required client_street_address = models.CharField(max_length=100) #required client_unit_address = models.CharField(max_length=100, blank=True, null=True) client_city = models.CharField(max_length=50) #required client_state = models.ForeignKey('USStates', related_name="usstates", on_delete=models.SET_NULL, null=True) client_zip = models.CharField(max_length=10) #required client_telephone_number = models.CharField(max_length=100) #required client_email = models.EmailField(max_length=100, blank=True, null=True) client_service_branch_id_fk = models.ForeignKey('ServiceBranches', on_delete=models.SET_NULL, null=True) client_ssn = models.CharField(max_length=11, blank=True, null=True) client_admission_date = models.DateField() #required client_primary_diagnosis = models.ForeignKey('ICDDiagnoses', related_name='primarydiagnosis', on_delete=models.SET_NULL, null=True) client_secondary_diagnoses = models.ManyToManyField('ICDDiagnoses', related_name='secondarydiagnoses', through='ClientToSecondaryICD', blank=True) client_surgical_diagnoses = models.ManyToManyField('ICDSurgicalDiagnoses', related_name='surgicaldiagnoses', through='ClientToSurgicalICD', blank=True) client_date_of_injury = models.DateField() #required client_gender_fk = models.ForeignKey('Genders', on_delete=models.SET_NULL, null=True) #required client_race_fk = models.ForeignKey('RaceCategories', on_delete=models.SET_NULL, null=True) client_marital_status_fk = models.ForeignKey('MaritalStatus', on_delete=models.SET_NULL, null=True) client_preferred_hospital_fk = models.ForeignKey('Hospitals', on_delete=models.SET_NULL, null=True) client_drug_allergies = models.ManyToManyField('SimplifiedMedicineNames', related_name="drug_allergies", blank=True) client_other_allergies = models.CharField(max_length=1000, blank=True, null=True) client_referral_date = models.DateField() #required client_last_hospitalization_note = models.CharField(max_length=500, blank=True, null=True) client_last_hospitalization_discharge_date = models.DateField() #required client_claim_source_fk = models.ForeignKey('ClaimSource', on_delete=models.SET_NULL, null=True) client_image = models.TextField(null=True, blank=True) client_pharmacy_fk = models.ForeignKey('Pharmacies', related_name="pharmacy", blank=True, null=True, on_delete=models.SET_NULL) client_last_update = models.DateTimeField(default=timezone.now) … -
Django orm query fails in Postgresql
I am trying to perform a makeshift spatial join in django between 2 unrelated tables in a postgis database. An example query would be to locate points in one table within a certain distance of points in a second table. the first query could be cafes found using the following query: q1 = Pois.objects.filter(tags__amenity__contains = "cafe") for the next query, I would like to use the 1st to return objects within a certain dist or ideally return only the distance between the closest objects. In sql this looks like: select stops.id, stops.the_geom as geom, min(dist/(1.3*60)) as wlk_time from ways_vertices_pgr stops, lateral ( select st_distance(st_transform(stops.the_geom, 4326)::geography, st_transform(p.geom, 4326)::geography, false) as dist from pois p where p.tags @> '{"sport":"soccer", "leisure":"pitch"}'::jsonb ) as dist where dist < 400 group by stops.id, stops.the_geom; In django orm, when using the manager.raw() to execute a facsimile query with the q1 as an insertion into the query, the function fails when attempting to pass the results of q1 into the second query. Based on the documentation for the spatial queries, I need to pass the results of q1 or the q1.query string into the second query is a specific way but I am not sure how this … -
How to use properly Postgres group by year, month in Django raw query?
This is my first project when I'm using Postgres. Before I used sqlite3 and the syntax is different sometimes. I have this query that works well in pgAdmin4: SELECT auth_user.id, COUNT(coachregiszter_latogatoi_stat.id) AS count_id, DATE_TRUNC('year', datetime) AS year, DATE_TRUNC('month', datetime) AS month FROM auth_user LEFT JOIN coachregiszter_latogatoi_stat ON coachregiszter_latogatoi_stat.user_id = auth_user.id WHERE user_id=1 GROUP BY year, month, auth_user.id If I implement it to my project I get SyntaxError: invalid syntax. I know it points to this part DATE_TRUNC('year', datetime) AS year, DATE_TRUNC('month', datetime) AS month specially the '' marks at year and month but I can't find the solution what or how to use it in the project. -
How to better handle/save Python (3.x) exception traces that aren't immediately raised?
I have an exception class I created that I find extremely handy when dealing with multiple errors, and I would like to improve it. I call it AggregateErrors. Background Basically, it buffers exception objects. (The code that uses it is left to deal with addressing cascading errors so that the script can otherwise proceed, e.g. skip a row of input data). I wrote it because we have a scientific data submission interface and the data is always prone to many user errors (improper formatting, data conflicts, missing data, and a whole host of data-specific issues). The loading script takes a long time to run, and to have to restart the load after encountering individual errors can be a weeks long process. With my AggregatedErrors class, all errors and warnings are buffered, and eventually summarized at the end of the run. We have a data validation interface that re-uses the same loading code and provides the error summary to the researcher for them to be able to fix issues on their own and then attempt to revalidate. The Original Problem Since the exceptions are raised later, you don't get a trace of where the exception was caught and buffered. Mitigation of … -
How to use the Field API and Field attribute in django
How to use the Field API like get_internal_type() get_prep_value(value) from_db_value(value, expression, connection) and get the value from Field attributes like Field.auto_created Field.concrete Field.is_relation -
Python Django: make strftime return german language, not english
In my Django project, I'm using strftime, specifically %b to get the abbreviated month name. Those names are returned in english. My settings contain the following: LANGUAGE_CODE = 'de' # also tried 'de_DE' USE_I18N = True USE_TZ = True Why does strftime still return english language? -
403 Error when try to test Stripe CLI in windows
hello I am trying to Test Stripe CLI on my windows machine i am download the stipe.exe and i add it to the PATH i read Dcoumnet and but unfortunately when i tring to login with : stripe login i get 403 Error like this : unexpected http status code: 403 We're sorry, but we're unable to serve your request. I try also run the command in Powershell and i run both of cmd and powershell with adminstaration access but result is same any idea how can i fix this problem ? thank you so much -
Issue deploying webpage [Angular(v17) / Django(v4) / Nginx Proxy Manager / Portainer]
Well my problem is that I need to deploy a webpage which I used Angular v17 as frontend and Django v4 as backend, I'm pushing my application to seperated docker containers example-client-1:4200 and example-api-1:8000. In my nginx proxy manager, I set it up to work with example.com > http | example-client-1 | 4200 and api.example.com > http | example-api-1 | 8000. Well my Django application works, but my Angular application doesn't. So what I found out, when I pause the backend in nginx, my frontend works fine, well except my requests to the api fails (obviously). If I have both running, my frontend end up in 504 Gateway Time-out error and I don't get anything in nginx logs or from the frontend container. Anyone have an Idea what it could be? I had yesterday tried it on a dev. domain, and I got it somehow working, well today I wanted to deploy it to the real domain, did everything exactly like before, but doesn't work, I'm missing something I guess. Domains are hosted on a plesk server which got an A dns to point to my linux machine where my portainer is located. I've tried a few things (can't tell … -
How to patch ViewSet.filterset_class to return None?
I have this test @mock.patch("app.views.MyViewSet.filterset_class", return_value=None) def test_filter_chat_request_management_status(self, mock_filterset_class): query_parameter = "status=accepted" response = self.client.get(URL + "?" + query_parameter) assert 1 == 1 With filterset_class, query_parameter variable does change the behaviour of the MyViewSet (which I do not want), therefore it changes the response. That is why I used @mock.patch to disable filterset class so it does not influence for the response. However, when I debug my test (in local test_filter_chat_request_management_status scope), MyViewSet.filterset_class does not return None as I expect, but returns magic mock object instead. >>> print(MyViewSet.filterset_class) <MagicMock name='filterset_class' id='4894544640'> Therefore, in rest_framework.backends.py, in class DjangoFilterBackend, in get_filterset_class() method, while executing filterset_class = getattr(view, "filterset_class", None) line of code, filterset_class variable contains <MagicMock name='filterset_class' id='4894544640'> object instean of None. How can I force MyViewSet.filterset_class return None? -
Cannot specify the url in template. NoReverseMatch
I tried to create blog with Django and now i have 2 models Publications and Comments(ForeignKey). My URLconf in blog app: from django.urls import path from . import views app_name="publications" urlpatterns = [ path("", views.index, name="index"), path("<int:pk>/", views.detail, name="detail"), path("<int:publication_id>/comments/", views.comment, name="comment") ] The URLconf of my project: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("publications/", include("publications.urls")) ] My template for page with comments: {% extends "publications/base.html" %} {% block content %} <h1>{{ title }}</h1> <p>{{ text }}</p> <small><i>Publicated : {{ pub_date }}</i></small> <a href="{% url 'publications:comment' publication.id%}">comment</a> {% endblock %} Now when I try to open http://127.0.0.1:8000/publications/1/ Django raises Reverse for 'comment' with arguments '('',)' not found. 1 pattern(s) tried: ['publications/(?P<publication_id>[0-9]+)/comments/\Z'] Error during template rendering. When i remove the link to comment from my template it works fine. My function for comments in views.py now is just a plug: def comment(request, publication_id): return HttpResponse("Hello comment") Also can you give me some links where i can read more about url routing in Django I tried to specify the app_name for my URLconf. I tried to change my view name and the name for URL in URLconf. -
How do you have a class that inherits elements from another in Django?
I have a Customers class that has the attributes (corporate name....) and another that has Customer Data. It is a textfield, but does not appear as a textfield. And I'm calling it in the clients class with models.ForeignKey(OutraClasse, on_delete=models.CASCADE). Am I doing it wrong? What is missing? -
How to set Nginx reverse proxy for local Docker Django
I'm developing a docker project with nginx and django services. I've django.conf.template parametrised to pass environment variables dynamically depends on environment. django.conf: upstream django_app { server ${DJANGO_PRIVATE_IP}:${DJANGO_PORT}; } server { listen 80; listen 443 ssl; listen [::]:443 ssl; server_name ${NGINX_SERVER_NAME}; ssl_certificate /etc/nginx/certs/elitecars_cert.pem; ssl_certificate_key /etc/nginx/certs/elitecars_privkey.pem; access_log /var/log/nginx/nginx.django.access.log; error_log /var/log/nginx/nginx.django.error.log; location / { proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_redirect off; proxy_pass http://django_app; } } The template works well because i can see the env vars values with more /etc/nginx/conf.d/sites-available/django.conf command upstream django_app { server django:8000; } server { listen 80; listen 443 ssl; listen [::]:443 ssl; server_name 0.0.0.0 127.0.0.1 localhost; ... But when i tried to access through the browser but doesn't work. Any idea? Anybody could help me please ? Thanks in advance. -
Request timeout DJANGO API when uploading files, even if the file is 1 pixel only
so I am working on a android studio app, and I am having trouble uploading images from the app to my host using my DJANGO API. This is literally my endpoint: @api_view(['POST']) def changeProfile(request): user_id = int(request.data.get('userId', '')) pfp_file = request.FILES.get('pfp', None) pfb_file = request.FILES.get('pfb', None) data = {'rescode': '0001', 'message': 'Profile updated'} # Set CORS headers response = Response(data) response = Response(data) response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Headers'] = 'content-type' response['Access-Control-Allow-Methods'] = 'POST, OPTIONS' return response I have made the request from Postman, from the android app even from a js file in the same directory as the API. All had the request "pending" and after 2 minutes it just gave error 500 timeout. It isn't due to the file size cause I even tried with a 1 by 1 image and it still had the same problem. It is also not lack of host resources like RAM or CPU cause I have checked them while the request was pending and it just stayed the same. And the weirdest part is that neither the client or server side have errors on the logs. -
How to set calender form in list_filter for datetime field in django admin?
models.py: class XYZ(models.Model): title = models.CharField(max_length=256) start = models.DateTimeField() end = models.DateTimeField() def __str__(self): return self.title admin.py: class XYZAdmin(admin.ModelAdmin): list_filter = (start,) admin.site.register(XYZ,XYZAdmin) and it's return now I want to change this filter to a pop-up calender and select custom start datateime and filter them. like this image: -
what does static() in django.conf.urls do?
I don't quite understand what it does from the doc what this function does and why it is useful. From the code snippet it provides from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ALso, what is this MEDIA_URL and MEDIA_ROOT? -
How can I change the type of a field in a linked model?
I have two models: the first is called 'PurchaseList', it includes a field, called 'recipe'. The field 'recipe' is a ForeignKey for building up the link to the second model, called 'Recipe' by creating a new field called 'is_in_shopping_cart': class PurchaseList(models.Model): author = models.ForeignKey('User', on_delete=models.CASCADE, verbose_name='Автор', related_name='added_to_cart') recipe = models.ForeignKey('Recipe', on_delete=models.CASCADE, verbose_name='Рецепт', related_name='is_in_shopping_cart') class Meta: verbose_name = 'Список покупок' verbose_name_plural = 'Списки покупок' ordering = ['recipes'] def __str__(self): return self.recipe class Recipe(models.Model): tags = models.ManyToManyField(Tag, verbose_name='Теги') author = models.ForeignKey('User', related_name='recipes', on_delete=models.CASCADE, verbose_name='Автор') ingridients = models.ManyToManyField(Product, through='IngredientToRecipe', verbose_name='Ингредиент') name = models.CharField(max_length=16, verbose_name='Наименование') image = models.ImageField( upload_to='recipes/images/', default=None, verbose_name='Изображение' ) text = models.TextField(verbose_name='Описание') cooking_time = models.IntegerField( verbose_name='Время приготовления в минутах') pub_date = models.DateTimeField(auto_now_add=True, verbose_name='Дата публикации') class Meta: verbose_name = 'Рецепт' verbose_name_plural = 'Рецепты' ordering = ['-pub_date'] def __str__(self): return self.title My target is to make the field 'is_in_shopping_cart' a BooleanField. So the question is how to determine the type of a field formed from a related model in the main model. I've found this way of solving the problem: @property def is_in_shopping_cart(self): return PurchaseList.objects.filter(author=self.author).exists() But i'm not sure if it works. Moreover, my friend advised me to try include attribute called 'field' to the field 'recipe' but I haven't found anything about … -
pyCharm does not find library file in django program
In a Django programm pyCharm (prof.) highlights utils_modal in a %load% statement with the info "unresolved library 'utils_modal'". My Django program has this structure djProgram | +-+- app_1 | +-- __init__.py | +-- templates | +-- app_1 | +-- template.html | +-+- app_2 | +-- __init__.py ... +-- utils +-- templatetags +- utils_modal.py utils is a non app folder, just a library for some modals used in the apps. This folder is mentioned in settings.py in the TEMPLATES structure: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ # some definitions ], 'libraries': { 'utils_modal': 'utils.templatetags.utils_modal', }, }, }, ] template.html starts like this: {% extends 'users/base.html' %} {% load crispy_forms_tags %} {% load utils_modal %} {# <-- Here is the pyCharm warning "Unresolved library 'utils_modal'" #} {% block content %} <!-- HTML code --> {% endblock %} What mistake have I made here? Thanks in advance. I am working with Windows 11, pyCharm professional 2023.3.2, Django 4.2.7 -
Toast message color Django
In A django App I want to return a message from views and show it using toast. and my main page is: <div class="toast-container p-3"> <div id="toast" class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true"> <div class="d-flex"> <div id="toast-body" class="toast-body"></div> <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button> </div> </div> </div> <div class="col-md-3"> <div id="Chamber_list"> {% if messages %} {% for message in messages %} {% if message.tags == 'error' %} <div class="alert alert-danger" style="...">{{ message }}</div> {% else %} <div class="alert alert-success" style="...">{{ message }}</div> {% endif %} {% endfor %} {% endif %} {% include 'Home/MOG_Division/rooms/Detaile/Chamber_list.html' %} </div> </div> And this is my views.py code > def edit_actl(request, pk): theroom = get_object_or_404(room_actual, pk=pk) form_erAO = False if request.method == "POST": form = room_actualForm(request.POST, instance=theroom) try: if form.is_valid(): form.save() response_data = {'success': True,'message': 'Room updated successfully'} response = HttpResponse(json.dumps(response_data), content_type='application/json',status=204) response['HX-Trigger'] = json.dumps({"roomListChanged": None, "showMessage": f"{theroom.room} {theroom.first_name} updated." }) return response except ValueError: form_erAO = 'Check your input dates' response_data = {'error': True, 'message': 'Room Already Occupied, Try another range'} response = HttpResponse(json.dumps(response_data), content_type='application/json',status=204) response['HX-Trigger'] = json.dumps({"roomListChanged": None, "showMessage":'Try another range'}) return response else: form = room_actualForm(instance=theroom) return render(request, 'Home/MOG_Division/rooms/Detaile/Actul_form.html', { 'form': form, 'theroom': theroom, 'form_erAO' : form_erAO }) … -
How do I Go About correcting certain css style in my django project not taking effect after deployed on Vercel
This is what it looks like on my local machin This is what i am getting after being uploaded to Vercel How do I Go About correcting certain css style in my django project(URLSHORTNER) not taking effect after deployed on Vercel So what possibly could go wrong in this code. here is the link to the code https://github.com/aaronicks/urlshortner/tree/gh-pages/shortner -
Python Opencv, send data to website via port
I have a python opencv code for age detection. import cv2 import math import time import argparse def getFaceBox(net, frame,conf_threshold = 0.75): frameOpencvDnn = frame.copy() frameHeight = frameOpencvDnn.shape[0] frameWidth = frameOpencvDnn.shape[1] blob = cv2.dnn.blobFromImage(frameOpencvDnn,1.0,(300,300),[104, 117, 123], True, False) net.setInput(blob) detections = net.forward() bboxes = [] for i in range(detections.shape[2]): confidence = detections[0,0,i,2] if confidence > conf_threshold: x1 = int(detections[0,0,i,3]* frameWidth) y1 = int(detections[0,0,i,4]* frameHeight) x2 = int(detections[0,0,i,5]* frameWidth) y2 = int(detections[0,0,i,6]* frameHeight) bboxes.append([x1,y1,x2,y2]) cv2.rectangle(frameOpencvDnn,(x1,y1),(x2,y2),(0,255,0),int(round(frameHeight/150)),8) return frameOpencvDnn , bboxes faceProto = "opencv_face_detector.pbtxt" faceModel = "opencv_face_detector_uint8.pb" ageProto = "age_deploy.prototxt" ageModel = "age_net.caffemodel" genderProto = "gender_deploy.prototxt" genderModel = "gender_net.caffemodel" MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746) ageList = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)'] genderList = ['Male', 'Female'] #load the network ageNet = cv2.dnn.readNet(ageModel,ageProto) genderNet = cv2.dnn.readNet(genderModel, genderProto) faceNet = cv2.dnn.readNet(faceModel, faceProto) cap = cv2.VideoCapture(0) padding = 20 while cv2.waitKey(1) < 0: #read frame t = time.time() hasFrame , frame = cap.read() if not hasFrame: cv2.waitKey() break #creating a smaller frame for better optimization small_frame = cv2.resize(frame,(0,0),fx = 0.5,fy = 0.5) frameFace ,bboxes = getFaceBox(faceNet,small_frame) if not bboxes: print("No face Detected, Checking next frame") continue for bbox in bboxes: face = small_frame[max(0,bbox[1]-padding):min(bbox[3]+padding,frame.shape[0]-1), max(0,bbox[0]-padding):min(bbox[2]+padding, frame.shape[1]-1)] blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227), MODEL_MEAN_VALUES, swapRB=False) genderNet.setInput(blob) … -
Django Rest -api User registration
I've been trying to implement register method on UserView , to create new user each time I call Post request , But I got this error in postman "detail": "Method \"POST\" not allowed." views.py class UserView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializers @action(detail=True, methods=["post"]) def register(self, request): serializer = UserSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND even when I set detail=False , I got this error too ,even though I dont have any many-to-many relationship between any tow models.. TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead. Serializer.py class UserSerializers(ModelSerializer): class Meta: model = User fields = "__all__" # exclude the 'password' field from the serialization extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user -
Django Azure deployment : Failed to build pycairo\nERROR: Could not build wheels for pycairo, which is required to install pyproject.toml-based
I am trying to deploy on Azure web apps, I am getting an error around pycairo, I have tried using containers to work around that , containers are not working and even worse they don't show what the problem is. So I have reverted to Azure Web apps cause atleast I can tell the issue from the logs. In detail the error looks like: Failed to build pycairo\nERROR: Could not build wheels for pycairo, which is required to install pyproject.toml-based projects\n\n[notice] A new release of pip is available: 23.0.1 -> 23.3.2\n[notice] To The web app runs smooth on my local computer, the problem comes on deployment. Whats even worse is even If I uninstall pycairo, the error will persist. Almost like there is no way around it. I have long engaged microsoft Azure support team for days now but there is no solution from their side. And thats why I am appealing to you my coding super heros, to finally end my struggle, this problem has literally stolen a week of my time and afteer spending a long time. The stack used is Django and postgres Deploying on Azure using both Web Apps and containers service. I have changed python … -
Convert string to boolean using database expression in Django (for generated field)
I have the following models code: class Product(models.Model): ... barcode_data = models.CharField( max_length=255, blank=True, default="", ) @property def is_scannable(self): if self.barcode_data: return True else: return False Basically, if barcode_data is not empty, is_scannable returns True. I want to turn is_scannable into a generated field, something like this: class Product(models.Model): ... barcode_data = models.CharField( max_length=255, blank=True, default="", ) is_scannable = models.GeneratedField( expression=..., output_field=models.BooleanField(), db_persist=True, ) I've read the docs here: https://docs.djangoproject.com/en/5.0/ref/models/database-functions/, but it seems like there isn't really a function to convert a string to boolean based on whether it is empty or not. Is there a way to do this?