Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Verify-Email 2.0.3 is not defined even after i installed it
im new to django and im trying to verify users email with Django-Verify-Email 2.0.3. As the documentation says i installed the package and did the same steps as they say but i get this error ModuleNotFoundError: No module named 'verify_email' i checked pip and it's already installed what is the problem is there any steps i should do first like create new app of name verify_email or something? i tryed to reinstall the package but same problem still appear -
How can communicate between HTML docs using Django server running via Google Colab notebook?
I want to simply experiment with this tutorial and reflect inputs of Home.html and reflect the summation of them in result.html using Django Server running in Google Colab notebook. I can run the Django server successfully in Google Colab medium, as shown in this screenshot You just need to manually set ALLOWED_HOSTS = ['colab.research.google.com'] in settings.py once you have installed django library in your cluster. The problem is I can't communicate and reflect the results of Home.html and reflect the summation of them in result.html. I saw in the Tutorial the browser of the local machine when opening HTML docs are: I tried following the set-up, but I still could figure out how I could communicate between HTML docs running by Django in Google Colab medium. I think I'm close to a solution, but I still can't manage it yet. ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] Please feel free to access the notebook for quick troubleshooting. You can create HTML docs quickly using Win notepad and save with .html and upload to notebook if necessary. home.html or download from this link: <h2> Welcome to my Web </h2> <form action="result"> <input type="number" name="no1" placeholder="input1"/> <input type="number" name="no2" placeholder="input2"/> <input type="submit"/> </form> result.html or … -
How can I display data from the current hour of data collection from my Django database using Chart.js on my frontend canvas?
I have an issue displaying data from the current hour of data collection from my django database to my frontend Chart.js . (See code below) I have tried what I found with datetime.now() queries below: #1. This block is the one I am trying to fix from datetime import datetime def datapage(request now = datetime.now() print(now.day) # to check current day output print(now.hour) # to check current hour output # Storing appends labels = [] data = [] queryset = Object.objects.filter(datefield__day=now.day, datefield__hour=now.hour) for entry in queryset: labels.append(entry.date.strftime('Hour %H')) data.append(entry.Datafield) return render(request, 'datapage.html', { 'labels': labels, 'data': data, }) #2 This is the compromise I made but it would display rather the current day's data # Modifying this line queryset = Object.objects.filter(datefield__day=now.day, datefield__hour__lte=now.hour) For Context, here's my script on the chart in the frontend, <body> <div class="flex w-full justify-around g-4"> <div class="w-1/2 shadow-md rounded-lg"> <div class="py-3 px-5 bg-gray-50"> Total Environmental Temperature </div> <canvas class="p-10" id="barChart1"></canvas> </div> </div> </body> <script> const barData = { labels: {{labels|safe}}, datasets: [ { label: 'Bar Dataset', backgroundColor: "rgb(34 211 238)", borderColor: "rgb(34 211 238)", data: {{data|safe}}, }, ], }; const barConfig = { type: 'bar', data: barData, options: { responsive: true, plugins: { legend: { position: … -
How to render django form with validators errors ussing reverse() instea of render() to not duplicate the code actually rendering the whole view?
I am trying to implement forms with validators for the 1st time. I have learned that to actually display validators errors to user after he/she will send the form, in the view function definition that covers POST request processing I have to once again trigger view rendering and pass all saved form data (I am storing that in form variable) to this view. I could do it like that: if form.is_valid: (..) else: return render(request, "auctions/listing-details.html", {"auction_id": auction_id, "bidding_form": form} The problem is, that my view requires bunch of params that are being calculated before render function is being called. So to not have to repeat all the calculation code + render() with all the params, I wanted to use HttpResponseRedirect(reverse()) - in my understanding that would redirect the app to the GET request processing of the view (that includes all the params calculation needed for the view rendering). So for example I could do somethig like: if form.is_valid: (..) else: return HttpResponseRedirect(reverse("auctions:listing_details", kwargs={"auction_id": auction_id, "bidding_form": form},)) BUT with this approach I am getting error Reverse for 'listing_details' with keyword arguments '{'auction_id': 3, 'bidding_form': <BidForm bound=True, valid=False, fields=(bid_amount)>}' not found. 1 pattern(s) tried: ['listing\\-details/(?P<auction_id>[0-9]+)\\Z'] Why is that? Is the only … -
Problem with Python Zappa deploy to AWS Lambda
I couldn't fix the problem with zappa aws lambda deploy. My zappa settings: { "dev": { "aws_region": "us-east-1", "django_settings": "photo_crm.settings", "profile_name": "default", "project_name": "photo-crm", "runtime": "python3.10", "s3_bucket": "photo-crm-zappa", "keep_warm": true, "slim_handler": true, "events": [ { "function": "photo_crm.tasks.destroy_galleries_by_terms", "expression": "cron(0 0 * * ? *)" }, { "function": "photo_crm.tasks.birthdays_telegram_bot", "expression": "cron(0 8 * * ? *)" } ], "remote_env": "s3://bucket_link", "exclude": [".env"] } } and I've got the error in the end: Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 500 response code. Part of Logs Calling tail for stage dev.. [1685898767317] INIT_START Runtime Version: python:3.10.v5 Runtime Version ARN: arn:aws:lambda:us-east-1::runtime:51b59a64d1fa5125d324f5fe77fbc805ea96f487f1d112fe4bf3f60323b552cb [1685898767841] Instancing.. [1685898772523] [ERROR] ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' Traceback (most recent call last): File "/var/task/handler.py", line 657, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 241, in lambda_handler handler = global_handler or cls() File "/var/task/handler.py", line 150, in __init__ wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line 13, in get_django_wsgi return get_wsgi_application() File "/var/task/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/task/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/task/django/apps/registry.py", line 116, in populate app_config.import_models() File "/var/task/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/var/lang/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], … -
Recreating Stack Overflow's tag input in Django
I've been trying to recreate Stack Overflow's tag input using Django, Alpine, and Tailwind. I managed to create the UI for it but have no idea how to save it to the database via Django's ORM. For context, we're trying to create a matchmaking system. I am using two fields named wins and losses, based on the teams that player X has wins and losses against. The catch is, a team name that's yet to exist can be entered to accommodate future teams to be registered in the database. Using model forms, I've been told to just use a ManyToMany field for the wins and losses field (related to the Team model), but I don't think that'll work because if they are to be translated into forms, they'd just be dropdowns of pre-existing teams. What's the best approach to this? -
How to safely and atomically decrement a counter with Django and PostgreSQL?
I've been reading up on PostgreSQL transaction isolation and how that relates to Django's transaction.atomic() (e.g. this article, PostgreSQL docs), but I'm far from fluent in this topic and I'm not sure I understand what I've read. We've got a PostgreSQL-backed Django app that involves quota objects. Simplified, it's just this: class Quota(models.Model): obj = models.OneToOneField(AnotherModel) count = models.PositiveIntegerField() An instance of this controls how many times a certain operation can be performed against the obj instance. count is initialized to a certain number, and will only ever decrement until it hits zero. Any number of processes/threads can concurrently perform these operations. Basically, we need to atomically decrement (with UPDATE) the count of a single database row without deadlocking and without two processes/threads ever e.g. starting with a count of 100 and both trying to decrement it to 99. My naive approach would be this: with transaction.atomic(): cursor = connection.cursor() cursor.execute('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE') Quota.objects.filter(obj=instance).update(count=F('count')-1) However, I'm not sure if this is subject to this issue, from the linked article: if at COMMIT the database cannot determine that the transaction could have been performed serially with respect to the read/writes of other transactions, then it will fail with a … -
PostgreSQL synchronous stored procedure execution calls from Django Backend
We have 5 PostgreSQL stored procedures and we need them to be chronologically executed in order. We have them listed in one stored procedure: CREATE PROCEDURE main(input_file_path varchar) LANGUAGE 'plpgsql' begin as $$ CALL get_input_file(input_file_path); CALL gla_first_step(); CALL glab_first_step(); CALL jet_first_step(); CALL completeness(); end; $$ We need gla_first_step procedure to be called after get_input_file procedure is done etc We have tried using PERFORM as was suggested by GPT but that brought the following error: ERROR: get_input_file(character varying) is a procedure LINE 1: SELECT get_input_file(input_file_path) ^ HINT: To call a procedure, use CALL. We have tried calling them separately from our backend with a loop of SELECT 1 to simulate a wait but that also did not work. cur.execute('CALL get_input_file(%s)', [path]) result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() cur.execute('CALL CALL gla_first_step()') result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() cur.execute('CALL glab_first_step()') result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() cur.execute('CALL jet_first_step()') result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() cur.execute('CALL completeness()') result = None while result is None: cur.execute("SELECT 1") result = cur.fetchone() -
What is non_field_errors?
I use forms.Form and forms.ModelForm {% if form.non_field_errors %} {% for err in form.non_field_errors %} <span style="color:darkred;">{{ err }}</span><br /> {% endfor %} {% endif %} Show nothing {{ form.errors }} Show everything,clean_fields() and form. -
I am getting this error django.core.exceptions.FieldError: Unsupported lookup 'icontains' for ForeignKey or join on the field not permitted
Below is models.py: class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def __str__(self): return self.first_name + ' ' + self.last_name class Book(models.Model): title = models.CharField(max_length=100) rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) author = models.ForeignKey(Author,on_delete=models.CASCADE,null=True) is_bestselling = models.BooleanField(default=False) slug = models.SlugField(default="",null=False,blank=True) def get_absolute_url(self): return reverse("model_detail", args=[self.slug]) def __str__(self): return self.title Below is admin.py: class BookAdmin(admin.ModelAdmin): list_display = ('title', 'rating', 'author','is_bestselling',) list_display_links = ('title', 'rating',) search_fields = ('title', 'rating','author',) list_filter = ('rating', 'is_bestselling',) prepopulated_fields = { 'slug': ('title',) } class AuthorAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name',) list_display_links = ('first_name', 'last_name',) search_fields = ('first_name', 'last_name',) I was trying to search Author in my Books Model. Update: This is answer below : To resolve this issue, you can modify the search_fields attribute to search on related fields of the Author model instead. Here's an updated version of my BookAdmin class: class BookAdmin(admin.ModelAdmin): list_display = ('title', 'rating', 'author', 'is_bestselling',) list_display_links = ('title', 'rating',) search_fields = ('title', 'rating', 'author__first_name', 'author__last_name',) list_filter = ('rating', 'is_bestselling',) prepopulated_fields = { 'slug': ('title',) } In the modified search_fields, 'author__first_name' and 'author__last_name' are used to search on the first_name and last_name fields of the related Author model. The __ syntax is used to traverse the relationship between Book and Author models. By specifying the … -
I cannot pass the values between the methods in classBasedView
I need to pass the bundle and the message values to get_context_data() method, but I cannot figure out how to do it. In this instance the form is valid when I pass it (I can add the better error handling when I figure out why the data gets updated in the post method, but doesn't in the get_context_data()). The form has just 1 filed and it takes the file. Please help. class FirmwareView(FormView, TemplateView): template_name = "dev_tools/firmware_cbv2.html" form_class = forms.InitialFirmwareForm2 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.bundle = {} self.message = {} def get_success_url(self): return self.request.path def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): if request.FILES: if "file" in request.FILES: file = request.FILES["file"] try: content = json.loads(file.read().decode('utf-8')) folder_name = utils.format_folder_name(content["title"]) units = [] for unit in content["units"]: units.append(unit) self.bundle["units"] = units self.bundle["file"] = { "name": folder_name, "content": json.dumps(content) } self.message = { "type": "info", "content": "The form was parsed successfully" } except Exception as e: print("there was an error", e) return self.form_valid(form) else: print("the form is invalid") return self.form_invalid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["bundle"] = self.bundle context["msg"] = self.message return context def form_valid(self, form): if isinstance(form, forms.InitialFirmwareForm2): return super().form_valid(form) -
Allow Django model to load non specified DB fields
I have non managed model (having managed = False), which has specified only single field. However, DB table contains more fields than specified on model. I would like retrieve ALL fields, even those, which are not specified by Django's model. My Model: from django.db import models class Employee(models.Model): active = models.BooleanField() class Meta: db_table = "employees" managed = False My Employees DB table: |----------------------------------- | id | active | address | |----------------------------------- | 1 | true | Dolphins street 5 | |----------------------------------- | 2 | false | Green Avenue 1/C | |----------------------------------- What I want: e = Employees.objects.first() print(e.address) # Will return "Dolphins street 5" The problem: e = Employees.objects.first() print(e.address) # Will raise in Attribute error I don't want to specify Employee.address field, because Django would force me to specify max_length. However, max_length is irrelevant for my application, because my model has managed = False. Moreover, DB definition of employees table is managed by third party software. -
coverage won't test the whole files test coverage right?
I'm trying to understand if we we have lot of services file written in the Djano project. We're writing the tests using pytest framework. I have a question related to this command coverage run -m pytest && coverage report && coverage xml So the coverage will not show all the files which has not test cases it will just show the file you have written the test for and how much you have written(in percentage)? is my understanding correct? Can we see somehow for all the files it hasn't covered yet. I tried running the command but its only showing me for one file can someone explain me here -
The rewind slider does not work on the video when trying to replay via Html5 Django
I tried to do video hosting on Django and play videos using Html5, but the video cannot be rewound, the problem disappears after the page is reloaded post.html {% extends 'main/base.html' %} {% block content %} <link href="https://vjs.zencdn.net/7.14.3/video-js.css" rel="stylesheet" /> <script src="https://vjs.zencdn.net/7.14.3/video.min.js"></script> <div class="container"> {% for p in post %} <h1>{{p.title}}</h1> <div> <video id='my-video-{{p.id}}' class='video-js' controls preload='none' width='640' height='264'> {% if door == "1" %} <source src="{{ p.video_door_1.url }}" type="video/mp4"> {% else %} <source src="{{p.video_door_2.url }}" type="video/webm"> {% endif %} <p class='vjs-no-js'> Чтобы посмотреть это видео, пожалуйста, включите поддержку JavaScript и обновите свой браузер. </p> </video> <div> <button onclick="changeSpeed('my-video-{{p.id}}', 0.5)">0.5x</button> <button onclick="changeSpeed('my-video-{{p.id}}', 1)">1x</button> <button onclick="changeSpeed('my-video-{{p.id}}', 1.5)">1.5x</button> <button onclick="changeSpeed('my-video-{{p.id}}', 2)">2x</button> <button onclick="changeSpeed('my-video-{{p.id}}', 5)">5x</button> </div> </div> <script> // Инициализация плеера Video.js для каждого видео var player = videojs('my-video-{{p.id}}', { // Настройки плеера }); function changeSpeed(playerId, speed) { // Получение объекта плеера по его идентификатору var targetPlayer = videojs(playerId); // Определение и установка новой скорости воспроизведения targetPlayer.playbackRate(speed); } </script> {% endfor %} </div> {% endblock %} views.py def show_post(request, post_slug, door): post = Avtobus.objects.filter(slug=post_slug) context = { 'post': post, 'menu': menu, 'door': door, 'title': 'Видео', } return render(request, 'main/post.html', context=context) -
what is React py and in how much time it will be stable?
React.py is a Python library that enables developers to build web applications using the principles and concepts of React, a popular JavaScript library for building user interfaces. React.py allows developers who are more comfortable with Python to leverage the benefits of React without having to write JavaScript code. At the time of my knowledge cutoff in September 2021, React.py was not a widely recognized or established library in the Python ecosystem. It is important to note that the development of open-source libraries and frameworks can be unpredictable, and it is difficult to determine an exact timeline for when a particular library will reach a stable version. However, typically, the stability of a library depends on factors such as community adoption, active maintenance, and the resolution of any reported issues or bugs. Therefore, it is advisable to check the latest updates and releases from the React.py community to assess the current status and stability of the library. Regarding the differences between React.py and React.js, the key distinction lies in the programming language used. React.js is primarily used with JavaScript, while React.py enables the use of Python for building web applications with React concepts. While React.js has a large and established ecosystem, … -
How to make given url path restful
/account/admin/otp /account/admin/otp/verification /account/delegate/otp /account/delegate/otp/verification /account/refresh-token /account/register-delegate /account/delegate-types /account/delegate-proof-documents In here account is the app name in Django and the there is User model and I try to provide the separate endpoint for the delegate and admin login -
code for understand that facebook has removed a link
how to check automatical that a facebook link has been removed I want to write a python script that will take input of a list of facebook links and automatically check whether these links have been removed or not. Finally it will give me another list that contains the result -
Need console bar that should display messages of my views.py
I am using django to build my application. here is my code: def upload_sequence(request): if request.method == "POST": sequence = request.POST.get("sequence") #sequence = sequence.replace("\n", "") file = request.FILES.get("file") try: if sequence: script_dir = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(script_dir, "sequences.fasta") with open(file_path, "w") as f: f.write(sequence) elif file: script_dir = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(script_dir, "sequences.fasta") with open(file_path, "wb") as f: for chunk in file.chunks(): f.write(chunk) calculate_features(file_path) except Exception as e: print(f"Error analyzing sequence: {e}") return JsonResponse({"status": "Error analyzing sequence"}, status=500) return redirect("results") return render(request, "upload.html") In this code: calculate_features(file_path) is a function which is displaying messages as: completed_steps += 1 progress=int((completed_steps / total_steps) * 100) progress_callback(f"Sequence {ID} uploaded successfully", progress) I tried man methods to display these messages in html webpage in real time when the analysis runs, but none works. Please suggest me a good method for this. -
How can I fix 'You can't execute queries until the end of the 'atomic' block' error in Django signals?
I'm using Django 4.1.3 in my signals.py, for an object, I want to do these things: Create an object of CLASS1 Create an objects of CLASS2 Call a function for sending a message and this is my code: @receiver(pre_save, sender=Event) def is_confirmed_changed(sender, instance, **kwargs): if instance.id is None: pass else: e = Event.objects.get(id=instance.id) try: with transaction.atomic(): CLASS1.objects.create( user=instance.creator, ) except: pass send_text_message() try: with transaction.atomic(): CLASS2.objects.create( event=e, ) except: pass on my localhost everything looks fine but when I test it on my server i get this error: You can't execute queries until the end of the 'atomic' block. I tried adding "with transaction.atomic()" or changing the order of my steps but i failed anyway. -
Django: Complex slot booking
I am working on a project where clinic will be able to book a slot I have done the slot booking code but now I want that when user select the date for another user he should not be able to view the already booked slots I have tried the following code Please review the same and let me know what i have done wrong Please help me if urgent view.py def treatment_plan(request, pk): title = 'Plan Treatment' patient_unique_number = request.GET.get("punique_number") treatment_session = request.GET.get("treatment_session") email = request.GET.get("email") pname = request.GET.get("name") address = request.GET.get("address") phone = request.GET.get("phone") treatment_name = request.GET.get("treatment_name") treatment_category = request.GET.get("treatment_category") treatment_code = request.GET.get("treatment_code") treatment_duration = int(treatment_session) time_slots = [] booked_slots = [] if request.method == "POST": session_dates = request.POST.getlist("session_dates[]") session_times = request.POST.getlist("session_times[]") if not session_dates: messages.error(request, 'Please select the date') if not session_times: messages.error(request, 'Please select time') for i in range(0, len(session_dates)): # Convert the date format from "DD/MM/YYYY" to "YYYY-MM-DD" session_date = datetime.strptime(session_dates[i], "%d/%m/%Y").strftime("%Y-%m-%d") appointment = Appointment.objects.create( patient_unique_number=patient_unique_number, date=session_date, time=session_times[i], patient_email=email, patient_name=pname, patient_treatment=treatment_name, patient_treatment_code=treatment_code, patient_treatment_category=treatment_category, patient_address=address, phone=phone ) appointment.save() messages.success(request, "Slots booked successfully") # Generate time slots from 9 AM to 9 PM with 30-minute intervals start_time = datetime.strptime("09:00", "%H:%M") end_time = datetime.strptime("21:00", "%H:%M") current_time = start_time … -
Managing User Authentication Across Multiple Django Projects with a Custom User Model
I have three Django projects: Project A, Project B, and Project C. Project A serves as the authentication project, Project B is responsible for managing user-related functionalities, and Project C handles restaurant-related operations. In Project A, I have created a custom user model to suit my authentication requirements. Now, I want to utilize this custom user model to access the APIs of both Project B and Project C. How can I achieve this integration between the projects? Specifically, I would like to accomplish the following: Enable user authentication: I want to use the custom user model defined in Project A to authenticate users when they access the APIs of Project B and Project C. Share user information: I need to access user information from Project B and Project C using the custom user model defined in Project A. This includes retrieving user details, updating user profiles, and performing user-related operations. Maintain consistency: It is essential to ensure that any changes made to the custom user model in Project A are reflected across all projects, including Project B and Project C. Here is my Custom user Model from Project A. import uuid from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import … -
RegisrationError in Django Algolia for multiple indices of the same model
How do I use the raw_search with a specific index after implementing multiple indices in Django Algolia? When I perform it like raw_search(VideoPublishIndex, "", query_params) where VideoPublishIndex is one of the indices of multiple indices for a specific model, it shows a RegistrationError, ...is not registered with Algolia engine. Also, can you please confirm, if we should be registering the meta index in the apps.py file? The error is show below: -
getattr(): attribute name must be string?
My models.py class Simple(models.Model): class Inner(models.TextChoices): a = 'small','Small' b = 'medium','Medium' c = 'large','Large' id = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False) name = models.CharField(max_length=200) size = models.TextField(choices=Inner.choices,default='medium', db_index=True) When use admin interface to add... TypeError at /admin/main/simple/add/ getattr(): attribute name must be string -
Is there a way to start an SQS listener alongside a Django web server on Elastic Beanstalk without causing the main thread to stop on AWS?
I am trying to set up a SQS listener that works alongside my django web server which is hosted on AWS Elastic Beanstalk. So far everything that I have tried has caused the main thread to just stop. I have tried threading (daemon & not daemon), I have tried async. I am not sure what else to try. The class attached works fine, I need to find a way to start it when django starts. My Class to listen to SQS import json import logging import boto3 # This is a Python class that listens to an Amazon Simple Queue Service (SQS) queue and handles # messages received. class SQSListener: def __init__(self, queue_url): self.queue_url = queue_url self.should_quit = False def start(self): self.sqs = boto3.client('sqs', region_name='us-west-2') while not self.should_quit: response = self.sqs.receive_message( QueueUrl=self.queue_url, MaxNumberOfMessages=1, WaitTimeSeconds=20 ) if 'Messages' in response: for message in response['Messages']: try: self.handle_message(message) except Exception as e: logging.error(f"Error processing message: {e}") self.sqs.delete_message( QueueUrl=self.queue_url, ReceiptHandle=message['ReceiptHandle'] ) def handle_message(self, message): # Override this method in a subclass to handle the message pass def stop(self): self.should_quit = True # This class creates a LogMessage object in Django's models based on a message received from an # SQSListener. class LogListener(SQSListener): def handle_message(self, … -
How to parse value from key in django template
First i want to explain what i want to achieve. at first this my query at view invoices = vendor.invoices.order_by('-due_date') this is the relevant model : class Booking(model.Models): ... invoice = models.ForeignKey('invoices.Invoice', related_name="bookings", on_delete=models.CASCADE, blank=True, null=True) POD_RETURN_STATUS = Choices( (1, 'on_driver', 'On Driver'), (2, 'taken_by_recipient', 'Taken by Recipient'), ... ) pod_return_status = models.PositiveSmallIntegerField(choices=POD_RETURN_STATUS, blank=True, null=True) whats new is i want to add the pod_return_status in template using invoice query. So like {% for invoice in invoices %} ... <td>{{ invoice.bookings.first.pod_return_status }}</td> {% endfor %} but of course it increases the number of query. at first i use prefetch_related but it seems to added more query. So after consulting with chatGPT this is my updated_query: invoices = vendor.invoices.order_by('-due_date').annotate( pod_return_status=Subquery( Booking.objects.filter(vendor_invoice=OuterRef('pk')).values('pod_return_status')[:1] ) ) it looks good on query numbers, but when i want to parse in template like this <td>{{ invoice.pod_return_status }}</td> it display the number like 1,2. what i want to display is the value of it like, 'On Driver' etc. Since im using model_utils.Choice, usually to display in template i use booking.get_field_name_display. but since the pod_return_status is acquired from annotation, not from the parents model. i cant use that. what im trying is to parse "POD_RETURN_STATUS": Booking.POD_RETURN_STATUS, to context_data so …