Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show the data in the Template according to the value of the select
Hi friends i need help as i am new to django! I need to show the information that I have saved in a table according to the option chosen from a select. When selecting the select option in the template I save the value in a variable using JavaScript (I do that without problems). I can't get the value of that variable to the get_context_data method, to later show it in my template. JavaScript code: $(function () { $('select[name="reporteFecha"]').on('change', function () { var fecha = $(this).val(); $.ajax({ url: window.location.pathname, type: 'POST', data: { 'action': 'search_fecha', 'fecha': fecha }, dataType: 'json', }) }); }); Views code: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ### I need to obtain within this function the value of the select in a variable ### context = { 'title': 'Reporte de Control de Electricidad', 'entity': 'Reporte Electricidad', 'list_url': reverse_lazy('cont_elect:Reporte_list'), 'form': ReportForm(), } return context I need to obtain in a variable inside the get_context_data the value that I capture with the JavaScript to later be able to show it in the template -
Django error "Select a valid choice. That choice is not one of the available choices." when use foreign key with djongo
I have a bug when i use django with mongoDB using djongo connector. I don't know why it has this error while doing any create operation in Django admin.. Its happening in models where foreign keys are there , for foreign key it is showing Models.py from djongo import models import uuid # Create your models here. class Blog(models.Model): name = models.CharField(max_length=100) class Meta: abstract = True class Entry(models.Model): blog = models.EmbeddedField( model_container=Blog ) headline = models.CharField(max_length=255) class Product(models.Model): img = models.ImageField(null=True, blank=True, upload_to="static/images/") name = models.CharField(max_length=200) price = models.FloatField() compare_at_price = models.FloatField() description = models.CharField(max_length=1000) estimate_ship_date = models.DateTimeField() def __str__(self): return self.name @property def imageURL(self): try: url = self.img.url except: url = '' return url class ProductTag(models.Model): title = models.CharField(max_length=10) color = models.CharField(max_length=7) background = models.CharField(max_length=7) product = models.ForeignKey( Product, on_delete=models.CASCADE, null=True) def __str__(self): return self.title class ThumbnailImage(models.Model): alt = models.CharField(max_length=200) img = models.ImageField(null=True, blank=True, upload_to="static/images/thumbnails") product = models.ForeignKey( Product, on_delete=models.CASCADE, null=True) @property def imageURL(self): try: url = self.img.url except: url = '' return url class Images(models.Model): alt = models.CharField(max_length=200) img = models.ImageField(null=True, blank=True, upload_to="static/images/images") product = models.ForeignKey( Product, on_delete=models.CASCADE, null=True) @property def imageURL(self): try: url = self.img.url except: url = '' return url i'm trying to use the … -
Is session auth possible in Django Rest Framework with a mobile client?
I want my application to have a mobile client (non native, built using Quasar). As I understand token auth will work, so I have chosen and implemented JWT for the web app though I havent tested the mobile client yet. I was wondering is it possible/recommended to use session auth in this context? -
Django form not registering user, even though all fields are valid
Within this app, I am presenting users with a registration form in which they enter their username, password, confirm their password (this confirmation is not part of the form, rather a check I do to ensure the passwords match in views.py), and their email. For some reason, whenever I attempt to register a with a the wrong confirmation password I keep getting the error "Something went wrong... Please try again!" in my else block instead of "passwords must match". I am pretty stuck and not sure what went wrong as before this functionality was fully operational and I started working on other features for my app. views.py def register(request): if request.method == "POST": form = UserRegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] confirmation = request.POST['confirmation'] # Ensure password matches confirmation if password != confirmation: messages.error(request, 'Passwords must match.') return render(request, "network/register.html", { "register_form": form }) # Attempt to create new user try: user = User.objects.create_user(username=username, email=email, password=password) user.save() except IntegrityError: messages.error(request, 'Username already taken.') return render(request, "network/register.html", { "register_form": form }) login(request, user) return HttpResponseRedirect(reverse("index")) else: # Always returns this whenever submitted messages.error(request, 'Something went wrong... Please try again!') return render(request, "network/register.html", { "register_form": form … -
Is there a way to load html AND event listeners dynamically?
Im using Django with htmx, and I use htmx in templates to load and remove not only html dynamically but also script tags that contain event listeners. Now the problem is that event listeners dont work when you load the script that contains them dynamically. I could use events like "onclick=dothis()" in the dynamically loaded html and have the "dothis()" function in the dynamically loaded script tag. This would work but I would prefer to use event listeners. Is there another way to solve this problem? -
Pictures do not show up in Django
I have uploaded a CSV file with the names of the image addresses and put the images in my media folder (media/album_pics) but when running the side it doesn't show me the images, before this it did. how come? my model: class Album(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True) release_date = models.CharField(max_length=10) artist = models.CharField(max_length=100) genre = models.CharField(choices=GENRE_CHOICES, max_length=20) image = models.ImageField(default='default2.jpg', upload_to='album_pics') spotify_url = models.URLField(max_length=250) -
I am not able to import the test_app model in the core/view.py
[enter image description heenter image description herere](https://i.stack.imgur.com/jeiya.png)enter image description here I want to import the Test_app class in core/view.py I am not able to import test_app in core ,I also added test_app in installed app in setting.py still not able to import ,Please help e=me with this problem -
Strange connection issue with Redis/Celery/Django/Kombu. Unable to use celery tasks
I have setup a celery task which connects to the Sendgrid API to update the contacts. However when the Celery and Celery Flower are running I cannot send tasks and it just repetitively sends error messages related to Kombu connecting. Here is a brief readout: Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: [E 230403 16:27:39 base_events:1753] Future exception was never retrieved Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: future: <Future finished exception=OperationalError('[Errno 111] Connection refused')> Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: Traceback (most recent call last): Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: yield Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/kombu/connection.py", line 433, in _ensure_connection Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: return retry_over_time( Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/kombu/utils/functional.py", line 312, in retry_over_time Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: return fun(*args, **kwargs) Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/kombu/connection.py", line 877, in _connection_factory Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: self._connection = self._establish_connection() Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/kombu/connection.py", line 812, in _establish_connection Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: conn = self.transport.establish_connection() Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: conn.connect() Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/amqp/connection.py", line 323, in … -
Django signals created value wrong return
I am generating a reference number to an objects field. If the record is new, the signal will fill other fields before saving. If the record is not new, I also have an action for it. I will check for an objects specific field and see if it changed and do some other action. Here is a snippet of the signal function: @receiver(pre_save, sender=ProofOfPayment) def pre_save_for_proof_of_payment(sender, instance, created=False, **kwargs): print('created', created) if created: upload_date = datetime.datetime.now().strftime('%Y%m%d%H%M%S') reference_number = 'PAYMENT-' + upload_date instance.reference_number = reference_number received = PaymentStatus.objects.get(pk=1) # Received instance.payment_status = received else: obj = sender.objects.get(pk=instance.pk) if not obj.payment_status == instance.payment_status: if instance.payment_status.name == 'Completed': instance.expiry_date = datetime.datetime.now() + datetime.timedelta(days=30) I am simulating the process in the admin. I create a new record. When I create the new object, I get an error because the variable created is set to False, doing the else function in the snippet. obj = sender.objects.get(pk=instance.pk) ProofOfPayment matching query does not exist. I am not sure why the created value is set to False even if the record is new. When I don't place a default value in the function: def pre_save_for_proof_of_payment(sender, instance, created, **kwargs): I get this error: pre_save_for_proof_of_payment() missing 1 required positional argument: … -
Django and Time Zone for regions that no longer observe the Daylight Save Time (DST)
I have a Django project, time zone is enabled for multiple purposes, my TIME_ZONE = 'America/Mexico_City', however, since this year 2023, in this time zone it's no longer observed the DST, I use the localtime to get the right date/time in some cases, but it detects the DST >>> localtime(timezone.now()) datetime.datetime(2023, 4, 3, 10, 14, 49, 782365, tzinfo=<DstTzInfo 'America/Mexico_City' CDT-1 day, 19:00:00 DST>) >>> timezone.now() datetime.datetime(2023, 4, 3, 15, 14, 54, 953013, tzinfo=<UTC>) >>> datetime.now() datetime.datetime(2023, 4, 3, 9, 15, 7, 628038) datetime.now() has the correct date/time, of course I can change the localtime for datetime.now(), but there are a lot of them, I want to understand how I can "update" or "sync" my Django project so it take the correct DST when some region change it for both observe or not longer observe it. -
Django - Retrieve line number with a wrapper decorator on CBV get()?
I wrote a logger handler, to use with my application based on Django 3.2 (Python 3.9). I'm using also Class-Based View. My views, without useless stuffs here: # app/views.py class AppHomeView(LoginRequiredMixin,TemplateView, LoggingHandler): @method_decorator(debug_pre_post_func) def get(self, req): # Some stuff here... return render(req, 'app/home.html', options) My custom logger, also without useless stuffs here: # app/logs.py class LoggingHandler: @staticmethod def static_log(level='info', msg=None, data=None, namespace=None): logger = logging.getLogger(namespace) extras = { 'data': data, } logger.log(getattr(logging, level.upper()), msg, extra=extras) # Other methods... And my cleaned wrapper: # app/logs.py def debug_pre_post_func(f): @functools.wraps(f) def wrapper(req, *args, **kwargs): LoggingHandler.static_log(level='debug', msg="Start function", namespace=f.func.__module__) result = f(req, *args, **kwargs) LoggingHandler.static_log(level='debug', msg="End function", namespace=f.func.__module__) return result return wrapper My logger is correctly called before and after view. My issue is: I can't retrieve the correct line number from the inspect.stack() When I debug [ i[3] for i in inspect.stack() ], I get: ["wrapper", "_wrapper", "dispatch", "dispatch", "view", "_get_response", "inner", "__call__", "inner", "__call__", "inner", "__call__", "inner", "__call__", "inner", "__call__", "inner", "__call__", "inner", "__call__", "inner", "__call__", "inner", "__call__", "inner", "get_response", "__call__", "handle_request", "handle", "accept", "run_for_one", "run", "init_process", "spawn_worker", "spawn_workers", "manage_workers", "run", "run", "run", "run", "<module>"] I don't see my method get to collect <FrameInfo>.lineno. Where did I do a mistake ? Thanks … -
Django not creating id (pk) on save
I have an old project that I have been asked to maintain and I'm getting some very strange behavior. I have this bit of code where a user's transaction is saved trans = Transaction( # id=str(newest_id), user=request.user, account=userAccount, # balance=balance, date=date, description=description, credit=credit, debit=debit, monthNum=monthNum, monthName=monthName, year=year ) trans.save() # adds record to the database The problem is that the transaction saves but it isn't assigned a id or a primary key (to an sqlite3 database). You can see by the commented code that I've even tried to force it to add an ID number but it didn't like that (and it is a horrible idea as well). I'm pretty sure it is not the code because I'm getting the same behavior from the Admin panel. If I create a new transaction there it saves, but when I try and access the newly created save I get the error "Transaction with ID "None" doesn't exist. Perhaps it was deleted?" I'm thinking this has something to do with the Django version. It was running on local machine which died. I've been asked to get it up and running again, but there was no requirements.txt file so I am guessing which version … -
Refresh django form widgets using htmx
I've successfully used htmx to handle a AJAX call to replace part of an django template form. Please see the question I posted on this here Django and HTMX for dynamically updating dropdown list in form.field . But, the form element being replaced is a multiple drop down list, which uses the django_easy_select2 library to render the drop down list nicely, and the form's widgets are not being refreshed when the partial is loaded (which means only the basic django MultipleChoiceSelect is shown). Grateful if someone could explain how I can solve this using htmx. Many thanks. -
Django Database error(after adding new field to exisiting old table)
I'm getting inconsistentmigration error in django production. Basically I tried doing python manage.py makemigrations and it shows old changes I made a while ago, then trying to migrate that it says inconsistentmigration. I can't delete or drop databases as I have lots of data. How do I solve this error as now I can't even make changes to my database tables. Please help. -
Trying to Redirect User to a Home page (Index.html) when they are signed out
I have been trying to solve one problem regarding redirect to another html page. I am creating a simple Restaurant Booking System (using python Django etc.) that will show the user (once logged in) their bookings to date, to amend or delete bookings and create a new booking. For the Admin, they can view and approve or reject bookings. But once logged out the user will see the main page describing the restaurant etc. The issue I am facing is that every time I log out as both admin and user, I am getting an Anonymous error message which I know the system needs someone to be signed in for a page to appear. So I created a new index.html and created the following: Index.html: enter image description here base.html: enter image description here the apps (booking) model.py: enter image description here the apps (booking) view.py: enter image description here the apps (booking) urls.py: enter image description here After all that I managed to get this error: enter image description here Where am I going wrong? I have tried everything. I tried everything as per the below in the views.py file: `from django.shortcuts import render, redirect from django.views import generic, … -
User is automatically being logout randomly when using session authentication in Django
I am using Django version 4.1 and haven't modified any codes for authentication and have used the defaults/built-ins provided by Django itself. I am facing issue of logging out automatically in random order when user is using my application. I tried to see the request logs during the time of logout, i even replicated it on my local computer, but i couldn't find any bugs or issue (until now) which caused this issue. Issue replication steps (but this doesn't happen always) More than 2 users using the app at same time From this question, i would like to ask What should i be looking for when debugging such scenarios? -
How to make the quantity field fill up automatically depending on the number of objects created in the adminpanel "StackedInLine"
As in the title, I would like the quantity field to fill in automatically. admin.py class ItemInline(admin.StackedInline): model = ProductIndex extra = 0 @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ['title', 'genre', 'price', 'quantity', 'is_available'] list_filter = ['genre', 'is_available'] search_fields = ['title'] exclude = ['popularity'] inlines = [ItemInline] form = BookForm forms.py class BookForm(forms.ModelForm): class Meta: model = Product fields = '__all__' def __init__(self, *args, **kwargs): super(BookForm, self).__init__(*args, **kwargs) self.fields['genre'].choices = [(x.pk, x.name) for x in Genre.objects.filter(category='book')] models.py class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=False, null=False) image = models.ImageField(upload_to='product', default=None) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse("ProductDetail", args=[str(self.pk)]) @property def model_name(self): return self._meta.model_name class ProductIndex(models.Model): inventory_number = models.CharField(max_length=255) product = models.ForeignKey(Product, on_delete=models.CASCADE) rental = models.ForeignKey(Rental, on_delete=models.CASCADE) is_available = models.BooleanField(default=True) def __str__(self): return str(self.inventory_number) class Book(Product): author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False, unique=True) I tried to do it in the clean() method in forms. But the problem may be that the product is done first and then the productindex. I tried to do a query, len(ProductIndex.objects.filter(product=product) but it didn't work properly. Please help, thank you -
How to prevent django HttpResponseRedirect from overriding URL
In views.py, I use the following to redirect to an HTML page with a parameter: return HttpResponseRedirect("my_page.html?request={"my_request"}") I fetch incoming request in my_page.html as following: <script> var params = new URLSearchParams(document.location.search); var request = params.get("request"); </script> This works as I expect, but of course with overriding URL, from currenturl.com/ to currenturl.com/my_page.html?request=my_request. How can I make the URL intact? -
Django adding current page url to static path
I'm facing an issue with serving my static files. My images are stored in project/static/images When I try to display images on my homepage, no problem, the url is good. But now that I'm trying t o display images on other pages I have the following error : "GET /contact_details/static/images/contact_image.png HTTP/1.1" 404 4212 Django is adding the name of my page 'contact_details' before the image path. Here's my code : settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/images/' MEDIA_ROOT =BASE_DIR /'images' urls.py urlpatterns = [ path('', views.home, name="home"), path('contact_details/', views.contactDetails, name="contact_details"), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I found on the forum that for other people the problem came from the STATIC_URL not starting with a slash, but in my case in didn't change nothing. -
Flattening multiple querysets that share the same name in Django
I have multiple querysets that look like: NAME1 | VALUE_FROM_COLUMN_1 NAME1 | VALUE_FROM_COLUMN_2 NAME1 | VALUE_FROM_COLUMN_3 How do I flatten this design other than using list(chain(q1, q2, q3)) function because it shows up like this: NAME1 | VALUE_FROM_COLUMN_1 | | NAME1 | | VALUE_FROM_COLUMN_2 | NAME1 | | | VALUE_FROM_COLUMN_3 And I want this: NAME1 | VALUE_FROM_COLUMN_1 | VALUE_FROM_COLUMN_2 | VALUE_FROM_COLUMN_3 -
Django post_save is not executed on CI/CD
I recently increased the default permissions for all my Django Views. In order for the users to have some default permissions I add new users to a default Group that has mainly viewing permissions. This is done via a post_save signal. MODELS_VIEW = [ "time entry", "time entry version", "project", "client", "user", ] MODELS_CHANGE = ["time entry version", "user"] MODELS_CREATE = ["time entry version"] MODELS_DELETE = ["time entry version"] def _add_permissions_to_group(group, perm_type: str, models: List[str]) -> None: """Add the permission of the `perm_type` to the given models.""" from django.contrib.auth.models import Permission for model in models: perm_name = f"Can {perm_type} {model}" permission = Permission.objects.get(name=perm_name) group.permissions.add(permission) def _add_view_permissions_to_group(group) -> None: _add_permissions_to_group(group, perm_type="view", models=MODELS_VIEW) def _add_create_permissions_to_group(group) -> None: _add_permissions_to_group(group, perm_type="add", models=MODELS_CREATE) def _add_change_permissions_to_group(group) -> None: _add_permissions_to_group(group, perm_type="change", models=MODELS_CHANGE) def _add_delete_permissions_to_group(group) -> None: _add_permissions_to_group(group, perm_type="delete", models=MODELS_DELETE) def _get_default_user_group_with_permissions(): """Get or create the default UserGroup and add all standard permissions.""" from django.contrib.auth.models import Group logger.debug("Getting default group for user") group, _ = Group.objects.get_or_create(name="default") # Add the standard permissions for users _add_view_permissions_to_group(group) _add_create_permissions_to_group(group) _add_change_permissions_to_group(group) _add_delete_permissions_to_group(group) return group class UsersConfig(AppConfig): """Config for Users""" default_auto_field = "django.db.models.BigAutoField" name = "users" def ready(self): """Add the user to the default UserGroup.""" logger.debug("User-config: App ready") def _add_to_default_group(sender, **kwargs): """Add the user … -
getting error when converting html to image using html2image
This is the code I am trying to execute in python shell, but I am getting this error. Please help!! >>> from html2image import Html2Image >>> hti = Html2Image(temp_path="/tmp", output_path="/var/www/html/commonservice/htmltoimage", custom_flags=["--no-sandbox", "--headless", "--hide-scrollbars", "--disable-gpu", "--default-background-color=ffffff"]) >>> html = """<h1> An interesting title </h1> This page will be red""" >>> css = "body {background: red;}" >>> hti.screenshot(html_str=html, css_str=css, save_as='temp_image.png') /snap/chromium/2406/snap/command-chain/desktop-launch: line 369: cannot create temp file for here-document: No such file or directory [0403/090244.518985:WARNING:bluez_dbus_manager.cc(247)] Floss manager not present, cannot set Floss enable/disable. [0403/090244.553724:WARNING:sandbox_linux.cc(393)] InitializeSandbox() called with multiple threads in process gpu-process. [0403/090244.788897:ERROR:headless_command_handler.cc(222)] Failed to write file /var/www/html/commonservice/htmltoimage/temp_image.png: No such file or directory (2) ['/var/www/html/commonservice/htmltoimage/temp_image.png'] -
How to access the names of fields in Django UniqueConstraint : 2?
I have original question here How to access the names of fields in Django UniqueConstraint? but it do not answer my question when *expressions contains different kind of "fields". I left the accepted answer. I want to access the unique constraint field names when declared in Meta class : class Book(models.Model): name = CharField(...) author = ForeignKey(...) description = ... class Meta: constraints = [ UniqueConstraint( Lower("name"), "author", name="unique__book_author", ), ] def do(self): unique_fields = ... # should be ["name", "author"] All fields are not necessarily a function like Lower. In this case, author is a foreign key. See https://docs.djangoproject.com/en/4.1/ref/models/constraints/ -
Django REST + Vue.js Google OAuth2 authorization code flow
I have a Django REST + Vue.js application where I'm using Google OAuth2 to handle authentication. Up to now, I've been using client-side authentication and the drf-social-oauth2 package, where the frontend gets an access_token from Google and sends it to the backend, which exchanges it for an in-house token which is returned to the frontend. I'm adding some integrations with the Google API services, and now I need to store the users' access_token and refresh_token when they log in. Therefore, I'm adding incremental auth using the authorization code flow: the frontend will get an authorization code after granting consent to my app to access the necessary scopes; the backend will exchange it for a pair of access_token and refresh_token and store them in a model. This is the way I've been doing it: when the user clicks the "Authorize" button on my frontend, the app makes a request to an endpoint that returns an auth url generated with a function that looks like this: from google_auth_oauthlib.flow import Flow def get_flow(scope_role: Optional[Union[Literal["teacher"], Literal["student"]]]): from integrations.classroom.views import GoogleClassroomViewSet scopes = get_scopes(scope_role) # returns a list of necessary scopes flow = Flow.from_client_config( GoogleClassroomIntegration().get_client_config(), scopes=scopes, ) # hard-coded url for proof of concept flow.redirect_uri … -
I want to write a template for my views, I am just struggling to make it
{'totals': <QuerySet [ {'trans_mode': 'Cash', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('99.25')}, {'trans_mode': 'Cash', 'month': datetime.date(2023, 2, 1), 'tot': Decimal('161.25')}, {'trans_mode': 'Cash', 'month': datetime.date(2023, 3, 1), 'tot': Decimal('40.5')}, {'trans_mode': 'ENBD', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('2215.72000000000')}, {'trans_mode': 'ENBD', 'month': datetime.date(2023, 2, 1), 'tot': Decimal('1361.66000000000')}, {'trans_mode': 'ENBD', 'month': datetime.date(2023, 3, 1), 'tot': Decimal('-579.130000000000')}, {'trans_mode': 'NoL', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('107')}, {'trans_mode': 'NoL', 'month': datetime.date(2023, 2, 1), 'tot': Decimal('56')}, {'trans_mode': 'NoL', 'month': datetime.date(2023, 3, 1), 'tot': Decimal('-69.5')}, {'trans_mode': 'Pay IT', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('0')}, {'trans_mode': 'SIB', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('208.390000000000')}, {'trans_mode': 'SIB', 'month': datetime.date(2023, 2, 1), 'tot': Decimal('-3.25')} ]>} above is the query set from Django views. I want to achieve the below, please suggest me a good way Trans Mode Jan 2023 Feb 2023 Mar 2023 Cash 99.25 161.25 40.5 ENBD 2215.72 1361.66 -579.13 NoL 107 56 -69.5 Pay IT SIB 208.39 -3.25