Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert timestamp to correct datetime in local timezone - Django
I get a timestamp from an API. When I transform it with: timestamp = datetime.fromtimestamp(json.loads(m)["_timestamp"], tz=pytz.timezone('Europe/Berlin')) I get the correct time in the console when I print it: 2021-11-10 15:22:26+01:00 But when I save it to the database with: BedTemperatureHistory.objects.create(TimeStamp=timestamp) The Timestamp looks something like this in the database (one hour less): 2021-11-10 14:22:26.000000 +00:00 My Timezone Settings look like this: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Berlin' USE_I18N = True USE_L10N = True USE_TZ = False Does anyone know what I need to do in order to save the correct timestamp in my database? -
Django doesn't detect changes in my model
I have an Orders model, in which I didn't have slug field before. So I decided to add a slug field to it. But when I run makemigrations command it says 'No changes detected'. I've tried to manually create migration and run it, but it didn't affect my database. Yes, I did check in settings, app is registered there. Model: class Orders(models.Model): customer = models.ForeignKey('contractors.Customers', models.DO_NOTHING, blank=True, null=True) slug = models.SlugField(max_length=150, blank=True) employee = models.ForeignKey('employees.Employees', models.DO_NOTHING, blank=True, null=True) order_date = models.DateField(blank=True, null=True, auto_now=True) required_date = models.DateField(blank=True, null=True) shipped_date = models.DateField(blank=True, null=True) ship_via = models.ForeignKey('contractors.Shippers', models.DO_NOTHING, db_column='ship_via', blank=True, null=True) freight = models.FloatField(blank=True, null=True) ship_name = models.CharField(max_length=40, blank=True, null=True) ship_address = models.CharField(max_length=60, blank=True, null=True) ship_city = models.CharField(max_length=15, blank=True, null=True) ship_region = models.CharField(max_length=15, blank=True, null=True) ship_postal_code = models.CharField(max_length=10, blank=True, null=True) ship_country = models.CharField(max_length=15, blank=True, null=True) class Meta: managed = False db_table = 'orders' def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.customer + "-" + str(self.order_date)) super(Orders, self).save(*args, **kwargs) def get_absolute_url(self): return u'/orders/%d' % self.pk def __str__(self): return f"{self.customer} {self.order_date}" My attempt to manually create migration: # Generated by Django 3.2.7 on 2021-11-10 13:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('orders', '0008_alter_orderdetails_options'), ] operations = [ migrations.AddField( model_name='orders', … -
Join multiple tables and calculate the average in a queryset
I have five Models: Ville, Machine, Compte, Signal, Donnees. The Machine table which has the key of the Ville table gives its key to Signal and Compte. Donnees has the Signal key. Class Ville(models.Model): nom_ville = models.CharField(maxlength=50) ... Class Machine(models.Model): ville = models.ForeignKey(Ville,on_delete=models.CASCADE) ... class Compte(models.Model): machine = models.ForeignKey(Machine,on_delete=models.CASCADE,related_name="credits") montant= models.FloatField() ... class Signal(models.Model): machine = models.ForeignKey(Machine,on_delete=models.CASCADE,related_name="signaux") ... class Donnees(models.Model): signal= models.ForeignKey(Signal,on_delete=models.CASCADE,related_name="donnees_signal") donne1 = models.FloatField() ... I have to calculate the average of Compte.montant and Donnees.donne1 grouped by Ville.nom I'm having trouble writing a single queryset to link these tables and calculate the two averages. Here is what I tried to do: Donnees.objects.values('signal__machine__ville__nom').annotate(moy1=Avg('donnee1'),moy2=Avg(Compte.objects.value('montant'))) It does not work. I need help ! I am open to all proposals and suggestions -
django: how to override the save() function in a model class so that it displays the saved information in an html template?
I am new to the django world and web development in general what I want to do is to preview the data that is saved in one of the created models "Tool" in models.py class Tool(models.Model): text1 = models.CharField(max_length=255) text2 = models.CharField(max_length=255) text3 = models.CharField(max_length=255) def save(self, *args, **kwargs): #override code super(Tool, self).save(*args, **kwargs) now I know that I need to override the save() method inside the class Tool but I don't know how it is done? in veiws.py I did the following from .models import Tool def preview(request): context = { "Tools": Tool.object.all() } return render (request,'myApp/preview.html',context) and in preview.html I have the following <!DOCTYPE html> <html> <head> <title></title> </head> <body> <p>{{Tools.text1}}</p> <p>{{Tools.text2}}</p> <p>{{Tools.text3}}</p> </body> </html> now from here, how can I render the html inside save() in Tool class? -
Can I use OpenCV in Django to draw line on the image from users?
I have developed the program, and one part of the program is getting line information from users. So I made the module in which users can draw lines on the image. (I made the module by two ways - one is opencv and the other is matplotlib) It is similar with below video. https://youtu.be/wx_oxF3vGRE Now I proposed to change my program into django project. But I cannot sure I can make similar function in the django project using matplotlib or opencv. I hope below process in the django webpage: Users select image file in their computer and upload Django save that image file and show that image (as canvas!) Users draw their own line on the shown image Drawn image and coordinates of lines are saved in the Django server. Is it possible with django? -
Send model property value to other model and display it in it's form
I'm working on an app where the user will fill a first form of a model, and he will be redirected to the next form where I want to get a value from property of the first model to be passed to the seconde model and display it in it's form. ***Models*** class Delivery(models.Model): user = models.ForeignKey( Client, on_delete=models.CASCADE, verbose_name=_("Client"), related_name=_("delivery_user") ) pickup_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("pickup_address")) destination_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("destination_address")) operation_date = models.DateField( _("desired pickup date"), auto_now=False, auto_now_add=False, blank=False, null=False ) invoice = models.BooleanField(_("check if you want an invoice"), default=False) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) delivery_key = models.CharField(max_length=200) @property def distance(self): distance = Distance( m=self.pickup_address.address_point.transform(32148, clone=True).distance( self.destination_address.address_point.transform(32148, clone=True) ) ) context = {} context["distance"] = f"{round(distance.m / 1000, 2)}" print(context) return context def __str__(self): return str(self.delivery_key) class DeliveryDetails(models.Model): delivery = models.ForeignKey(Delivery, on_delete=models.CASCADE, related_name=_("delivery")) distance = models.DecimalField(_("Distance Approximative "), max_digits=7, decimal_places=2) delivery_price = models.DecimalField(max_digits=7, decimal_places=2) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) def __str__(self): return str(self.created_at) ***Views*** class DeliveryCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView, FormView): model = Delivery form_class = UserDeliveryForm template_name = "deliveries/customer/edit_deliveries.html" def get_success_url(self): return reverse( "delivery:delivery-details", kwargs={"pk": self.object.pk, "distance": self.object.distance}, ) def test_func(self): return self.request.user.is_active class DetailsDeliveryCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView, … -
Error in Kubernetes cronjob to dump and restore postgres database for Django application
I need to create a testing environment for a specific team to use our Django application for testing against the database. This database must be somewhat in sync with out production database. Considering we have two clusters production and staging, my approach is the following: Create a db_test in the staging Postgres server db_test will be periodically synced with db_prod. To do so: Create a cronjob in the staging cluster that connects to the production database, do a pg_dump and then do a pg_restore to the db_test (using localhost because it's connected through a pgbouncer). I run the migrations to make sure the tables are up to date Next: I need to run a management command that will erase some customer data from this copy (to be GDPR compliant). Desired behavior: pg_dump and pg_restore are successful and the new database is cleared of customer information Actual behaviour: pg_dump and pg_restore are successful. I can psql into the newly created database and everything looks alright. migrate command fails with the traceback below clean_db fails because it can't find some tables (which they exist as I inspected with psql. This is the simple shell script I run in the cronjob: #!/bin/bash # … -
Django project structure for blog
Im new to django and im folowing many tutorial about django and every one of them have a different style and technique. my main focus is to structure my project for my django blog project. please help me to figure it out Here are my question Should i seperate the app for the example post, comment, categorie,tag, meta descriptions or just create the blog app and have all that model view in one app or i need to create the post, comment, categorie, tag, meta descriptions, and adding the frontend app to handle the views and url. if i have to seperate the the app that i mention above should the administrator for the dashboard area so the user can add post or delete in the app it self or i have to create the dashboard/administrator app. Should i seperate the project for dashboard administrator with public page. or should their in same project but in deferent app. i have done many schenario but one of the one i thing the best is. like this but i need aloot of comment about it blog --blog --frontend ---- models.py model i leave it empty ---- views.py i focus handel the view … -
how do I refer to a QuerySet element in Django?
I have such a QuerySet: 'category_1': Product.objects.filter(category__slug='white') how how can I refer to a certain element of this QuerySet? for example, like referring to the elements of a list. in template: {{ category_1[1].image.url }} thanks! -
Can I use textblob library in Django app?
I am working on Django web application. I have input field where user enters word and if the word is entered correctly, user is able to click on that word and get the translation of it. But, if the word is not entered correctly, user has to go back on the previous page and enter the word correctly. So, I need to make something like 'Did you mean' feature. Is it possible to make it by using textblob library, and if it is, can you get me some hints how to make it? Thanks on your answers! -
how to calculate 38 days from next month starting in Django
For example let us consider invoice_date = 09/11/2021 but is payment_period is for 38 days then it should start from 1/12/2021 to 7/01/2022 (because december month have 31 days) then the due_date will be 7/01/2022 the invoice_date can be any date of the month but payment_period should start form 1st date of next upcoming month and due_date should be 38th date from that today = datetime.date.today() (#09/10/11) -
Maintaining and using a list of user in backend using django
I am building a web-chat application using django and django-channels. I have figured out the actual chat part, however I was trying to implement a random chat pairing feature which would allow to pair any two user who choose to chat randomly. I cannnot figure out how to implement this in the backend to create a sort of list which would update automatically and from which I can take two user, pair them and thus remove them from the list. I hope, my question is clear. -
How can I put a list of integers (bit choices) to a database in django
I'm trying to get a list of weekday options into a PositiveSmallIntegerField in Django. I found a very similar question from the year 2011, Representing a multi-select field for weekdays in a Django model I tried the approach with the BitChoices class in there, and the class itself seems to work. However, I cannot put the list returned by the class to the database, since it somehow has to be the sum of that list. But how do I accomplish that? What am I missing? Here's what I have so far (disclaimer: maybe a few lines are superfluous for this example, I tried to reduce it to the bare minimum): models.py from django.db import models from django.conf import settings from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from datetime import date class BitChoices(object): def __init__(self, choices): self._choices = [] self._lookup = {} for index, (key, val) in enumerate(choices): index = 2**index self._choices.append((index, val)) self._lookup[key] = index def __iter__(self): return iter(self._choices) def __len__(self): return len(self._choices) def __getattr__(self, attr): try: return self._lookup[attr] except KeyError: raise AttributeError(attr) def get_selected_keys(self, selection): """ Return a list of keys for the given selection """ return [ k for k,b in self._lookup.items() if b & … -
not able to run vapid --sign claim.json
I'm following this link to create web push notification for my App, right now I'm stuck in step2 (creating public and private key) because I can't run this command(even tough I have implemented successfully the vapid vapid --sign claim.json I got this error when running this command!! 'vapid' is not recognized as an internal or external command, -
How to authenticate user present in one project db from another project?
I have two graphql django projects, lets say project1 and project2. In project1, I have users db and I am building project2 for some other purpose. Now, when I am performing some function in project2, I want to check if the user is authenticated or not from user db in project1. Please provide some suggestion on how to implement this functionality. -
WebSocket wss:// on SSL with Nginx Gunicorn Daphne Channels Redis
I try to get my Django project running with WebSockets; in the browser console I get the error WebSocket connection to 'wss://www.xxx.com:8001/ws/asdf/1234/' failed: settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("config('REDIS_SERVER_NAME')", 6379)], }, "ROUTING": "myproject.routing.channel_routing", }, } asgi.py: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') django.setup() application = get_default_application() nginx configuration: server{ server_name <IP-adress> <xxx.xxx>; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/myproject/myproject.sock; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://127.0.0.1:8001/; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/xxx.xxx/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/xxx.xxx/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } daphne.service: Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/ubuntu/myproject ExecStart=daphne -e ssl:8001:privateKey=/etc/letsencrypt/live/xxx.xxx/privkey.pem:certKey=/etc/letsencrypt/live/xxx.xxx/fullchain.pem myproject.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target The site works just fine and ws:// was working when I tested it without the SSL certificates from certbot for the domains. Any help is appreciated... -
django generate thumbnail of view
I want to generate a thumbnail image for my static view. for example, I have a view: def exampleView(request): return HttpResponse('<h1>here</h1>') How can I get an image of a blank page with a here title? It may sounds like a non-sense feature request, but I really need it to achieve my app functionality, I will be so grateful for any suggestion you make. -
Initial values, initialized using JS, not changing while updating data in Django Model Form
models.py class Package(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=models.ForeignKey(Treatment, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) Based on the treatment and patient_type, I want max_fractions and total_package to be given initial values. For that I wrote a JS function: function mf(){ tt_select = document.getElementById("id_package_form-treatment"); tt = tt_select.options[tt_select.selectedIndex].text; ptt_select = document.getElementById("id_package_form-patient_type"); ptt = ptt_select.options[ptt_select.selectedIndex].text; max = document.getElementById("id_package_form-max_fractions"); if (tt=="MVTR" && ptt=="JTCPR") max.value=40; else if (tt=="MVTR" && ptt=="JTCPR/PC") max.value=40; else if (tt=="MVTR" && ptt=="CASH") max.value=40; else if (tt=="CRFP" && ptt=="JTCPR") max.value=40; else if (tt=="CRFP" && ptt=="JTCPR/PC") max.value=40; else if (tt=="CRFP" && ptt=="CASH") max.value=40; else if (tt=="5DTYU" && ptt=="JTCPR") max.value=30; else if (tt=="5DTYU" && ptt=="JTCPR/PC") max.value=30; else if (tt=="5DTYU" && ptt=="PMJAY") max.value=30; else if (tt=="5DTYU" && ptt=="CASH") max.value=30; else if (tt=="FRTC" && ptt=="JTCPR") max.value=40; else if (tt=="FRTC" && ptt=="JTCPR/PC") max.value=40; else if (tt=="FRTC" && ptt=="PMJAY") max.value=30; else if (tt=="FRTC" && ptt=="CASH") max.value=35; else if (tt=="PALLATIVE" && ptt=="JTCPR") max.value=10; else if (tt=="PALLATIVE" && ptt=="JTCPR/PC") max.value=10; else if (tt=="PALLATIVE" && ptt=="CASH") max.value=5; else if (tt=="RADICAL" && ptt=="JTCPR") max.value=0; else if (tt=="RADICAL" && ptt=="JTCPR/PC") max.value=0; else if (tt=="RADICAL" && ptt=="CASH") max.value=0; else if (tt=="ADJUVANT" && ptt=="JTCPR") max.value=0; else if (tt=="ADJUVANT" && ptt=="JTCPR/PC") max.value=0; else if (tt=="ADJUVANT" && ptt=="CASH") max.value=0; else max.value=0 } function tp(){ tt_select = document.getElementById("id_package_form-treatment"); … -
How to access properties of foreign key in csv file, django
views.py properties = [ 'first_name', 'policy__request' # Here I want to access the request of policy ] for row_num, model in enumerate(Model.objects.all()): for col_num, property in enumerate(properties): ws.write(row_num+1, col_num, getattr(model, property), font_style) I got the following error 'Model' object has no attribute 'policy__request' I'm trying to create a csv file with my data frmo database and I want to have access the properties of the foreign key -
Django PIPE youtube-dl to view for download
TL;DR: I want to pipe the output of youtube-dl to the user's browser on a button click, without having to save the video on my server's disk. So I'm trying to have a "download" button on a page (django backend) where the user is able to download the video they're watching. I am using the latest version of youtube-dl. In my download view I have this piece of code: with youtube_dl.YoutubeDL(ydl_opts) as ydl: file = ydl.download([f"https://clips.twitch.tv/{pk}"]) And it works, to some extend. It does download the file to my machine, but I am not sure how to allow users to download the file. I thought of a few ways to achieve this, but the only one that really works for me would be a way to pipe the download to user(client) without needing to store any video on my disk. I found this issue on the same matter, but I am not sure how to make it work. I successfully piped the download to stdout using ydl_opts = {'outtmpl': '-'}, but I'm not sure how to pipe that to my view's response. One of the responses from a maintainer mentions a subprocess.Popen, I looked it up but couldn't make out … -
How to insert the data that is returned from an API in a text format to the Django models
I'm using an API (https://www.metoffice.gov.uk/pub/data/weather/uk/climate/datasets/Tmax/date/UK.txt) that returns the data in a text format. so with the data returned I want to add those data in the Django model. so Now I'm stuck with the problem that how should I parse the data in order to add them to the model. Because since the data returned by that API as you can see that the year 2021 doesn't have all the data. Currently, I have 18 fields in the Django model (each field for each value) and my approach was to extract all the data which has a numerical constant pattern using regex and with the extracted data, I will insert the data into the DB model by iterating it over the list. But the problem is that year 2021 doesn't have all the data and the regex that I'm using is just extracting the numerical values from the string that is returned from the API. for example: ear jan feb mar apr may jun jul aug sep oct nov dec win spr sum aut ann 2021 4.9 7.0 9.8 10.9 13.4 18.7 21.1 18.9 18.7 14.0 6.21 11.35 19.56 code that I've written so far. numeric_const_pattern = '[-+]? (?: (?: … -
How to make a local form to stored in Django admin
Hi there i tried for make Django project and make a local form to stored in django admin here is my "view" code from django.http import request from django.shortcuts import render,redirect from templates.forms import Registrationform from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm def home(request): numbers = [1,2,3,4,5] name = 'max' args = {'myName': name,'numbers':numbers} return render(request, 'accounts/home.html',args) def register(request): if request.method == 'POST': form = Registrationform(request.POST) if form.is_valid(): form.save() return redirect('/account') else: form = Registrationform() args = {'form':form} return render(request,'accounts/reg_form.html',args) def view_profile(request): args ={'user':request.user} return render(request,'accounts/profile.html',args) def edit_profile(request): if request.method == 'POST': form = UserChangeForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('/account/profile') else: form = UserChangeForm(instance=request.user) args={'form':form} return render(request,'accounts/edit_profile.html') error: from templates.forms import Registrationform ModuleNotFoundError: No module named 'templates' -
How to join two querysets from different model to create a new queryset with additional fields?
Currently on Django/MySQL setup I need to join two queries from different models into one but unlike CHAIN or UNION(), I need the final queryset's record set to expand to include data retrieved from both queries based on the common key (sales_date) as well as a SUM field. Please see below for better explanation of my question: querysetA: id sales_date store_sales 1 2020-01-15 2000.00 2 2020-01-16 1000.00 3 2020-01-17 3000.00 querysetB: id sales_date online_sales 1 2020-01-15 1500.00 2 2020-01-16 800.00 3 2020-01-17 2800.00 Joined querysetC from querysetA and B (my target result querysetC): id sales_date store_sales online_sales combine_sales 1 2020-01-15 2000.00 1500.00 3500.00 2 2020-01-16 1000.00 800.00 1800.00 3 2020-01-17 3000.00 2800.00 5800.00 My code for both querysets as below (both working and giving me the correct results): querysetA = store_shop.objects.filter( sales_date__range=(fromdate, todate)) \ .values('sales_date') \ .annotate(store_sales=Sum('sales_income')) \ .order_by('sales_date') querysetB = online_shop.objects.filter( sales_date__range=(fromdate, todate)) \ .values('sales_date') \ .annotate(online_sales=Sum('sales_income')) \ .order_by('sales_date') Both union() and itertools.chain does not give me what I want. Any help or suggestions would be greatly appreciated. -
Deserializer JSON objects containing Jason web signatures in Django. App Store Server Notifications responseBodyV2
So I have a python django rest application that I need it to be able to handle post request for App Store Server Notifications. Thing is that v2 of the App Store Server Notifications payload is in JSON Web Signature (JWS) format, signed by the App Store. Which contains fields that in turn are also in JSON Web Signature (JWS) format, signed by the App Store. I know how to handle that using python-jose procedurally but I can't figure out how to fit the whole process within Django serializers in a graceful manner with as minimal hacking as possible. The data could be something like: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJub3RpZmljYXRpb25UeXBlIjoidHlwZSIsInN1YnR5cGUiOiJzdWJfVHlwZSIsIm5vdGlmaWNhdGlvblVVSUQiOiJzdHJpbmcgbm90aWZpY2F0aW9uVVVJRCIsImRhdGEiOnsiYXBwQXBwbGVJZCI6MTIzNCwiYnVuZGxlSWQiOiJhZmRzYXNkIiwiYnVuZGxlVmVyc2lvbiI6ImJ1bmRsZVZlcnNpb24iLCJlbnZpcm9ubWVudCI6ImVudmlyb25tZW50Iiwic2lnbmVkUmVuZXdhbEluZm8iOiJleUpoYkdjaU9pSklVekkxTmlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKaGRYUnZVbVZ1WlhkUWNtOWtkV04wU1dRaU9pSjBaWE4wSUhSdmJHVnRJaXdpWVhWMGIxSmxibVYzVTNSaGRIVnpJam94TENKbGVIQnBjbUYwYVc5dVNXNTBaVzUwSWpvMExDSm5jbUZqWlZCbGNtbHZaRVY0Y0dseVpYTkVZWFJsSWpveE5qTTJOVE0xTVRReExDSnBjMGx1UW1sc2JHbHVaMUpsZEhKNVVHVnlhVzlrSWpwMGNuVmxMQ0p2Wm1abGNrbGtaVzUwYVdacFpYSWlPaUowWlhOMElIUnZiR1Z0SWl3aWIyWm1aWEpVZVhCbElqb3hMQ0p2Y21sbmFXNWhiRlJ5WVc1ellXTjBhVzl1U1dRaU9pSjBaWE4wSUhSdmJHVnRJaXdpY0hKcFkyVkpibU55WldGelpWTjBZWFIxY3lJNk1Td2ljSEp2WkhWamRFbGtJam9pZEdWemRDQjBiMnhsYlNJc0luTnBaMjVsWkVSaGRHVWlPakUyTXpZMU16VXhOREY5LnYwWW9YQUd0MTFPeVBXUk8zV2xTZDRiSWVtcVV6Q0ZJbFdjd0ZwcEI5TmMiLCJzaWduZWRUcmFuc2FjdGlvbkluZm8iOiJleUpoYkdjaU9pSklVekkxTmlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKaGNIQkJZMk52ZFc1MFZHOXJaVzRpT2lKMFpYTjBJSFJ2YkdWdElpd2lZblZ1Wkd4bFNXUWlPaUp6WkdaellYTmtaaUlzSW1WNGNHbHlaWE5FWVhSbElqb3hOak0yTlRNMU1UUXhMQ0pwYmtGd2NFOTNibVZ5YzJocGNGUjVjR1VpT2lKMFpYTjBJSFJ2YkdWdElpd2lhWE5WY0dkeVlXUmxaQ0k2ZEhKMVpTd2liMlptWlhKSlpHVnVkR2xtYVdWeUlqb2lkR1Z6ZENCMGIyeGxiU0lzSW05bVptVnlWSGx3WlNJNk1UUTFMQ0p2Y21sbmFXNWhiRkIxY21Ob1lYTmxSR0YwWlNJNk1UWXpOalV6TlRFME1Td2liM0pwWjJsdVlXeFVjbUZ1YzJGamRHbHZia2xrSWpvaWRHVnpkQ0IwYjJ4bGJTSXNJbkJ5YjJSMVkzUkpaQ0k2SW5SbGMzUWdkRzlzWlcwaUxDSndkWEpqYUdGelpVUmhkR1VpT2pFMk16WTFNelV4TkRFc0luRjFZVzUwYVhSNUlqb3hORFVzSW5KbGRtOWpZWFJwYjI1RVlYUmxJam94TmpNMk5UTTFNVFF4TENKeVpYWnZZMkYwYVc5dVVtVmhjMjl1SWpveE5EVXNJbk5wWjI1bFpFUmhkR1VpT2pFMk16WTFNelV4TkRFc0luTjFZbk5qY21sd2RHbHZia2R5YjNWd1NXUmxiblJwWm1sbGNpSTZJblJsYzNRZ2RHOXNaVzBpTENKMGNtRnVjMkZqZEdsdmJrbGtJam9pZEdWemRDQjBiMnhsYlNJc0luUjVjR1VpT2lKMFpYTjBJSFJ2YkdWdElpd2lkMlZpVDNKa1pYSk1hVzVsU1hSbGJVbGtJam9pZEdWemRDQjBiMnhsYlNKOS5lbnlkTnVwd2txOTNYQ2dfeG5yYzNXTmtNNjM4NXpITnpoa0tqa3cyb3VrIn19.OgSJ4xE3r2Tw0Q4KcwPSD4YFo21uCLDgrKOtKOomijo and then the part inbetween the dots decoded could look like b'{"notificationType":"type","subtype":"sub_Type","notificationUUID":"string notificationUUID","data":{"appAppleId":1234,"bundleId":"afdsasd","bundleVersion":"bundleVersion","environment":"environment","signedRenewalInfo":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdXRvUmVuZXdQcm9kdWN0SWQiOiJ0ZXN0IHRvbGVtIiwiYXV0b1JlbmV3U3RhdHVzIjoxLCJleHBpcmF0aW9uSW50ZW50Ijo0LCJncmFjZVBlcmlvZEV4cGlyZXNEYXRlIjoxNjM2NTM1MTQxLCJpc0luQmlsbGluZ1JldHJ5UGVyaW9kIjp0cnVlLCJvZmZlcklkZW50aWZpZXIiOiJ0ZXN0IHRvbGVtIiwib2ZmZXJUeXBlIjoxLCJvcmlnaW5hbFRyYW5zYWN0aW9uSWQiOiJ0ZXN0IHRvbGVtIiwicHJpY2VJbmNyZWFzZVN0YXR1cyI6MSwicHJvZHVjdElkIjoidGVzdCB0b2xlbSIsInNpZ25lZERhdGUiOjE2MzY1MzUxNDF9.v0YoXAGt11OyPWRO3WlSd4bIemqUzCFIlWcwFppB9Nc","signedTransactionInfo":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBBY2NvdW50VG9rZW4iOiJ0ZXN0IHRvbGVtIiwiYnVuZGxlSWQiOiJzZGZzYXNkZiIsImV4cGlyZXNEYXRlIjoxNjM2NTM1MTQxLCJpbkFwcE93bmVyc2hpcFR5cGUiOiJ0ZXN0IHRvbGVtIiwiaXNVcGdyYWRlZCI6dHJ1ZSwib2ZmZXJJZGVudGlmaWVyIjoidGVzdCB0b2xlbSIsIm9mZmVyVHlwZSI6MTQ1LCJvcmlnaW5hbFB1cmNoYXNlRGF0ZSI6MTYzNjUzNTE0MSwib3JpZ2luYWxUcmFuc2FjdGlvbklkIjoidGVzdCB0b2xlbSIsInByb2R1Y3RJZCI6InRlc3QgdG9sZW0iLCJwdXJjaGFzZURhdGUiOjE2MzY1MzUxNDEsInF1YW50aXR5IjoxNDUsInJldm9jYXRpb25EYXRlIjoxNjM2NTM1MTQxLCJyZXZvY2F0aW9uUmVhc29uIjoxNDUsInNpZ25lZERhdGUiOjE2MzY1MzUxNDEsInN1YnNjcmlwdGlvbkdyb3VwSWRlbnRpZmllciI6InRlc3QgdG9sZW0iLCJ0cmFuc2FjdGlvbklkIjoidGVzdCB0b2xlbSIsInR5cGUiOiJ0ZXN0IHRvbGVtIiwid2ViT3JkZXJMaW5lSXRlbUlkIjoidGVzdCB0b2xlbSJ9.enydNupwkq93XCg_xnrc3WNkM6385zHNzhkKjkw2ouk"}}' and then if the fields encoded in jws format are also decoded the same way mentioned aboce it is going to ultimately look like this: { "notificationType":"type", "subtype":"sub_Type", "notificationUUID":"string notificationUUID", "data": {"appAppleId":1234, "bundleId":"afdsasd", "bundleVersion":"bundleVersion", "environment":"environment", "signedRenewalInfo":{ "autoRenewProductId": "test tolem", "autoRenewStatus": 1, "expirationIntent" : 4, "gracePeriodExpiresDate": 1636535141, "isInBillingRetryPeriod": true, "offerIdentifier": "test tolem", "offerType": 1, "originalTransactionId": "test tolem", "priceIncreaseStatus": 1, "productId": "test tolem", "signedDate": 1636535141, }, "signedTransactionInfo":{ "appAccountToken": "test tolem", "bundleId": "sdfsasdf", "expiresDate" : 1636535141, "inAppOwnershipType": "test tolem", "isUpgraded": true, "offerIdentifier": "test tolem", … -
Django query to fetch multiple GenericRelation objects for multiple objects
I need to make quite complex query in Django to display some information from two models. There is FanGroup model, where I have few instances (let's say 5 and it's fixed) of this model. Each FanGroup model except few basic information contains GenericReleation to Fan model. For each FanGroup instance I could own few Fan instances (this is variable from 1 to many Fans assigned to each FanGroup). FanGroup model: class FanGroup(models.Model): name = models.CharField(max_length=32) default_state = models.BooleanField(default=True) fans = GenericRelation(Fan, related_query_name='fan_controller') Fan model: class Fan(models.Model): fan_inventory_id = models.CharField(max_length=16) manufacture = models.CharField(max_length=32) model = models.CharField(max_length=64) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') I'd like to display in one View all the Fans belonging to FanGroup. How to combine the data to display this in single query? I could do it dirty, making simple queries for Fan model with filters to FanGroup, but this is not very dynamic solution and not very elegant.