Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django oscar send_email result in ValueError: EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive,
This function trigger an error that doesn't make sense to me: File "/venv/virtualenvs/ZHR-f7z/oscar/apps/communication/utils.py", line 128, in send_email_messages email.send() in the settings: EMAIL_USE_SSL = None #False doesn't change result EMAIL_USE_TLS = None Someting wrong is happening as both are None so these can't be True: File "/venv/virtualenvs/ZHR-f7z/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 31, in __init__ self.use_ssl = settings.EMAIL_USE_SSL if use_ssl is None else use_ssl self.timeout = settings.EMAIL_TIMEOUT if timeout is None else timeout self.ssl_keyfile = settings.EMAIL_SSL_KEYFILE if ssl_keyfile is None else ssl_keyfile self.ssl_certfile = settings.EMAIL_SSL_CERTFILE if ssl_certfile is None else ssl_certfile if self.use_ssl and self.use_tls: raise ValueError( "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set " "one of those settings to True.") self.connection = None self._lock = threading.RLock() [console ready] >>> use_ssl >>> self.use_ssl 'None' >>> self.use_tls 'None' >>> If I start a shell with: >>> from django.core import mail >>> mail.send_mail( ... 'Subject here', 'Here is the message.', ... 'mailfrom', ['mailto'], ... fail_silently=False, ... ) result in a success. Any advice as the settings are both false and the ValueError should be trigger if both are True? Thanks, BR -
Expected a list of items but got type queryset
I want to make a get api that returns a json containing 3 tables. These 3 arrays must contain a list of different objects. I want to get as a result: { "array_1": [{"id", "name"}, {"id2", "name2"}], "array_2": [{"id", "date"}, {"id2", "date2"}], "array_4": [{"id", "otherfield"}, {"id2", "otherfield2"}], } My serializers: class Object1Serializer(serializers.ModelSerializer): class Meta: model = Object1 fields = ['id', 'photo',] class Object2Serializer(serializers.ModelSerializer): class Meta: model = Object2 fields = ['id', 'name', 'date'] class Object3Serializer(serializers.ModelSerializer): class Meta: model = Object3 fields = ['id', 'file'] class ObjectsSerializer(serializers.Serializer): object_1 = Object1Serializer(many=True, required=False) object_2 = Object2Serializer(many=True, required=False) object_3 = Object3Serializer(many=True, required=False) My view: class getObjectAPIView(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = ObjectsSerializer def get(self, request, machine_pk): user = request.user if not machine_pk: return Response("Missing id machine field", status=status.HTTP_400_BAD_REQUEST) if not Machine.objects.filter(pk=machine_pk).exists(): return Response("Machine not found", status=status.HTTP_404_NOT_FOUND) if not user.is_staff and not user.groups.filter(name="frigo").exists(): return Response("You are not allowed to access this machine", status=status.HTTP_403_FORBIDDEN) machine = Machine.objects.get(pk=machine_pk) object1 = Object1.objects.filter(machine=machine) object2 = Object2.objects.filter(machines=machine) object3 = Object3.objects.filter(client=machine.client) json_response = { "object1": object1.values(), "object2": object2.values(), "object3": object3.values(), } serializer = ObjectsSerializer(data=json_response) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) But I got an error: { "object1": { "non_field_errors": [ "Expected a list of items but got type \"QuerySet\"." ] }, "object2": { … -
Strategy to apply a common filter to all my graphene queries in a django project
When a user is asked to be removed from the system, I'll delete all his personal info like name and address from the auth_user table, but I'll keep all his system actions for internal analytics purposes. These analytics however, should not show up in our frontend web. For example, there's a table 'training' and one of the queries related to that is to see how many users are currently enrolled in a training. If an user has been removed he should not show up in there. Unfortunately I did the mistake of not creating a custom user model in the beginning of my Django project and it seems quite a hassle to do that now. Instead what I'm doing is to have a related model that links to the default User model. I created the RemovedUser model that simply flags that a user has been deleted. I know there is the 'is_active' field in the default model, but I don't want to use that one as I want to keep a distinction of actual completely removed users and inactive ones. Here is the model class RemovedUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) date_removed = models.DateTimeField(editable=False, default=timezone.now, help_text='Date the user was removed') Nothing … -
Taking over products together with the relationship of the categories django
I made a relationships as follows on products and categories. class Category(models.Model): DoesNotExist = None id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(verbose_name='category name', max_length=50) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) product_name = models.CharField(verbose_name='product_name', null=False, max_length=200) product_description = models.TextField(verbose_name='product description', null=False, max_length=1000) stock = models.IntegerField(verbose_name='stock', null=False) expire_date = models.DateTimeField(verbose_name='expire date') company = models.ForeignKey(Company, on_delete=models.CASCADE) store = models.ForeignKey(Store, blank=True, null=True, on_delete=models.SET_NULL) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name def get_cat_list(self): k = self.category # for now ignore this instance method breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb) - 1): breadcrumb[i] = '/'.join(breadcrumb[-1:i - 1:-1]) return breadcrumb[-1:0:-1] But I would like an output like this when I take over the products It`s possible? [ { "name":Cars, "slug":"cars", "subcategories":{ "id":, "name":, } }, ] And the view class is this products = Product.objects.all() product_serializer = ProductSerializer(products, many=True) return Response({'data': products.data}, status=200) So is there a functionality in … -
How to export the date entered in one model to the other using django
#model 1 class Timesheet(models.Model): project=models.ManyToManyField(Project) Submitted_by=models.ForeignKey(default=None,related_name="SubmittedBy",to='User',on_delete=models.CASCADE) status=models.CharField(max_length=200) ApprovedBy=models.ForeignKey(default=None,related_name="ApprovedBy",to='User',on_delete=models.CASCADE) Date =models.DateField() Hours=models.TimeField(null=True) #model 2 class Monday(models.Model): Dates=models.Foreignkey(Timesheet,related name='Dates',on_delete=models.CASCADE) def str(self): return self.Dates this was throwing an error and couldn't able to view the date inputted in Timesheet model in the Monday Model. Please help on solving this logic. -
How to integrate django-unicorn with chart.js?
Can anyone show me an example on how to integrate Django-unicorn with chart.js? I'm just new to this django-unicorn framework and a bit confused about its documentation. I just want to creat a real time graph using this framework. thanks. -
django validator for USA phone number validation with regex
how do i write a python function that takes phone as argument to validate with below model attributes with regex models.py class MyModel(models.Model): phone = Phonefield(max_length = 255,blank = True) -
My Vue app is displaying images vertically
I am making a Vue / Django app but any image I add is displaying vertically but the tut I am following, his own is displaying horizontally. I have trace back my code but found nothing. I add a screenshot of the code and images the code screenshot for the page and the screenshot of my webapp -
Django Query is not ordering / Sorting Correctly in pagination model in rest framework
I have 705 Meta#Data of Instagram videos but I am unable to sort it by name | id | uploading date or any order query. My MetaData model is class MetaData(models.Model): # Info id = models.IntegerField(primary_key=True) tag = models.CharField(max_length=500) # User Info username = models.CharField(max_length=400) followers = models.IntegerField() verified = models.BooleanField() profile = models.URLField() # Video Info upload_date = models.DateField() upload_time = models.TimeField() views = models.IntegerField() duration = models.CharField(max_length=50) comments = models.IntegerField() likes = models.IntegerField() dimension = models.CharField(max_length=50) framerate = models.CharField( max_length=100, blank=True, default='Not Found') # Post link = models.URLField() codecs = models.CharField(max_length=200, blank=True, default='Not Found') caption = models.CharField(max_length=100, blank=True, default='Not Set') status = models.CharField(max_length=20, choices=( ('Pending', 'Pending'), ('Acquired', 'Acquired'), ('Rejected', 'Rejected')), default='Pending') I am using Django rest framework pagination and getting my filters fields in parameters def fetchVideosContentwithFilter(request, filters, directory=None): paginator = PageNumberPagination() paginator.page_size = 12 # Parameters flts = ['upload_date'] if filters: flts = json.loads(filters) if 'upload_date' in flts: flts.append('upload_time') if directory and directory != 'all': objs = MetaData.objects.filter(tag=directory) else: objs = MetaData.objects.all() pages = paginator.paginate_queryset(objs.order_by(*flts), request) query = s.MetaDataSerializer(pages, many=True) return paginator.get_paginated_response(query.data) I also try or replace *paginator.paginate_queryset(objs.order_by(flts), request) with paginator.paginate_queryset(objs.order_by('-id'), request) but in vain data is not ordering correctly -
Wagtail how to add benefit template context to catalogue view?
I added the discount to productdetailview by adding context and editing the template. Everything works fine in Detailview but the context is not passed to catalogue view so this doesn't appear in browse. I tried to add the same context with little change to the catalogue view but it doesn't work. anyone have any idea? working detail view catalogue views.py Benefit = get_model('offer', 'Benefit') def get_discounts(self): try: discounts = Benefit.objects.get(id=self.object.id ) except: discounts = '' return discounts def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['alert_form'] = self.get_alert_form() ctx['has_active_alert'] = self.get_alert_status() ctx['benefits'] = self.get_discounts() return ctx stock_record.html <!--Added discount price--> {% if benefits %} <mark class="sale">Product in Sale!</mark> {% with type=benefits.type %} {% if type == 'Percentage' %} <p> Price after {{benefits.value}}% discount </p> <p class="price_color">{{ session.price.excl_tax |percent:benefits.value|currency:session.price.currency }}</p> {% elif type == 'Absolute' %} <p> Price after {{benefits.value}}{{session.price.currency }} discount </p> <p class="price_color">{{ session.price.excl_tax |subtract:benefits.value|currency:session.price.currency }}</p> {% endif %} {% endwith %} {% endif %} -
Django elastic search dsl-drf
RequestError at /elastic-producthub/category-search RequestError(400, 'search_phase_execution_exception', 'No mapping found for [division_id] in order to sort on') this is the error am getting from django elastic search dsl .Actually I have a model called category and have a foreign key called division. Here, I want to perform a search query on category with division name. -
How To Skip RSS Feeds Missing Certain Attributes
I have a list of RSS feeds that i want to parse in my Django Application. Some contain all my desired attributes, others don't have some of the attributes. The ones that miss my desired attributes keep crashing my program. I keep getting such errors. raise AttributeError("object has no attribute '%s'" % key) AttributeError: object has no attribute 'summary' My model class Posts(models.Model): title = models.CharField(max_length=500, verbose_name='Post Title', null=False) link = models.URLField(max_length=500, verbose_name='Post Link', null=False) summary = models.TextField(verbose_name='Post Summary', null=False) image_url = models.URLField(max_length=500, null=False, verbose_name='Post Image URL', default='') slug = models.SlugField(unique=True, max_length=500, null=False) tags = TaggableManager() pub_date = models.DateTimeField(verbose_name='Date Published', null=False) guid = models.CharField(max_length=500, verbose_name='Guid Code', null=True) feed_title = models.CharField(max_length=500, verbose_name='Feed Channel Title', null=False) feed_description = models.TextField(verbose_name='Feed Channel Description', null=False) date_created = models.DateField(auto_now_add=True, verbose_name='Date Created', null=False) last_modified = models.DateField(auto_now=True, verbose_name='Last Modified', null=False) source = models.ForeignKey(Source, on_delete=models.CASCADE, verbose_name='Source', null=False) category = models.ForeignKey(Categories, on_delete=models.CASCADE, verbose_name='Category', null=False) def __str__(self): return f"{self.title} - {self.feed_title}" class Meta: verbose_name_plural = 'Posts' My RSS save function if not Posts.objects.filter(slug=post_slug).exists(): try: post = Posts.objects.get(slug=post_slug) except Posts.DoesNotExist: post = Posts( title = post_title, link = post_link, summary = post_summary, image_url = image_link, slug = post_slug, pub_date = date_published, guid = item.guid, feed_title = channel_feed_title, feed_description = channel_feed_desc, source_id = … -
how can I get requests(module name) data parameter to my dJango server?
my tkinter app def _calculation(self): myList = [1,2,3,4,5] url = "http://127.0.0.1:8000/test" response = requests.post(url, data=json.dumps(myList)) my dJango Server @csrf_exempt def test(request): print(request.data) # why error happen? return HttpResponse('') I am making a tkinter app(front) and django Server(back) post matching, but I can't get requests(module name) data(request parameter) from django server. how can I get requests data parameter -
how to show all product when not apply any filter
class ProductListView(TemplateView): template_name = "storefront/shop/product/list.html" def get_context(self,request,id,slug, *args, **kwargs): category = get_object_or_404(Category,id=id,slug=slug) return category.get_option_list_context(request) def get(self, request,id, slug, *args, **kwargs): template=self.template_name if request.GET.get('ajax'): # print("In ajax call") template = "storefront/shop/product/includes/sidebar.html" if request.GET.get('pagination_ajax'): template = "storefront/shop/product/includes/list-ajax.html" return render(request, template, self.get_context(request,id, slug, args, kwargs)) -
Django: AuthStateMissing at /oauth/complete/google-oauth2/
I am using social-auth-app-django for GoogleOauth2 authentication. It works fine for all users but in case of django admin it gives me following error: AuthStateMissing at /oauth/complete/google-oauth2/ Session value state missing. I have tried all answers posted on stackoverflow but the error still persists. This is the result it returns. The state value seems to be present there but either it gets null or overridden somehow. This is my GoogleOAuth2 class, created by overriding social-auth-app-django's GoogleOAuth2 class. Though there is not much difference except for pipeline from base class. It works fine for non-admin user login. class GoogleOAuth2(GoogleOAuth2): """Google OAuth2 authentication backend""" name = 'google-oauth2' REDIRECT_STATE = False AUTHORIZATION_URL = 'https://accounts.google.com/o/oauth2/auth' ACCESS_TOKEN_URL = 'https://accounts.google.com/o/oauth2/token' ACCESS_TOKEN_METHOD = 'POST' REVOKE_TOKEN_URL = 'https://accounts.google.com/o/oauth2/revoke' REVOKE_TOKEN_METHOD = 'GET' # The order of the default scope is important DEFAULT_SCOPE = ['openid', 'email', 'profile'] EXTRA_DATA = [ ('refresh_token', 'refresh_token', True), ('expires_in', 'expires'), ('token_type', 'token_type', True) ] def pipeline(self, pipeline, pipeline_index=0, *args, **kwargs): out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs) user_ip = get_request_ip_address(self.strategy.request) if not isinstance(out, dict): return out user = out.get('user') if user: user.social_user = out.get('social') user.is_new = out.get('is_new') if user.is_new: logger.info(f'Register attempt', extra={"email": user.email, "remote_ip": user_ip, "status": "success", "user_id": user.pk, "oauth_backend": "google"}) else: logger.info(f'Login attempt', extra={"email": user.email, … -
FlowPaper Integration with Python
I want to integrate Flowpaper as ebook viewer in my python/django web but unable to do it as there is no documentation. Kindly help me by providing the same or any good alternate ebook viewer. -
Cannot start apache server with mod_wsgi config
I am trying to set up a simple django app on a windows vm with apache2 server and mod_wsgi. I cannot start apache server after adding wsgi config. LoadFile "C:/Python310/python310.dll" LoadModule wsgi_module "C:/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Python310" WSGIScriptAlias / "C:/Users/karna/Desktop/webproject/webproject/wsgi.py" WSGIPythonPath "C:/Users/karna/Desktop/webproject/" <Directory "C:/Users/karna/Desktop/webproject/webproject/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/Users/karna/Desktop/webproject/static/" <Directory "C:/Users/navar/Desktop/webproject/static/"> Require all granted </Directory> This is the error i am getting in apache logs. Starting the 'Apache2.4' service The 'Apache2.4' service is running. pm_winnt:notice] [pid 1800:tid 628] AH00455: Apache/2.4.52 (Win64) mod_wsgi/4.9.0 Python/3.10 configured -- resuming normal operations [Mon Jan 31 05:58:26.207229 2022] [mpm_winnt:notice] [pid 1800:tid 628] AH00456: Apache Lounge VS16 Server built: Dec 17 2021 10:17:38 [Mon Jan 31 05:58:26.207229 2022] [core:notice] [pid 1800:tid 628] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Mon Jan 31 05:58:26.222856 2022] [mpm_winnt:notice] [pid 1800:tid 628] AH00418: Parent: Created child process 2784 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Apache24\\bin\\httpd.exe' sys.base_prefix = 'C:\\Python310' sys.base_exec_prefix = 'C:\\Python310' sys.platlibdir = 'lib' sys.executable = 'C:\\Apache24\\bin\\httpd.exe' sys.prefix = 'C:\\Python310' sys.exec_prefix = 'C:\\Python310' sys.path = [ 'C:\\Python310\\python310.zip', '.\\DLLs', '.\\lib', 'C:\\Apache24\\bin', ] Fatal Python … -
How do I pass URLs from my Django rest API to the Flutter front-end
I am very new to Django REST framework and Flutter so if the solution to this is very simple I apologies. I am trying to pass the URLs from my Django back-end to the Flutter front-end. I feel like the solution is a urls.dart file where I can store all the URLs from Django. However, I have no idea what the code for this file would look like. Here are the URLs that I need passed over urlpatterns = [ path('', views.getRoutes), path('notes/',views.getNotes), path('notes/create/', views.createNote), path('notes/<str:pk>/update/', views.updateNote), path('notes/<str:pk>/delete/', views.deleteNote), path('notes/<str:pk>/',views.getNote), ] It is not deployed so I am using localhost. When I implement the URLs into the flutter code I want them to look something like this: .put(updateUrl(widget.id), body: {'body': controller.text}); widget.client.post(createUrl, body: {'body': controller.text}); Any help would be much appreciated. -
FATAL: password authentication failed for user in Postgresql
GETTING AN ERROR IN POSTGRESQL (connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "postgres" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "postgres") -
creating a List type Field/attribute in django model
What I'm trying to do class Node(models.Model): Name = models.CharField(max_length=10) Ancestor = models.CharField(max_length=10) Descendent = models. In the Descendent attribute I want to assgin a list of objects of Node. What can I Do? -
How to access a field from a ForeignKey on a Queryset in django?
This is my models.py: class Computer(models.Model): name = models.CharField(max_length=40) ip = models.GenericIPAddressField(blank=True, null=True, unique=True) class Template(models.Model): data = models.JSONField(...) computer = models.ForeignKey(Computer,on_delete=models.CASCADE) When I delete a template object, from django admin, I need to make an API request, so I edited the delete() method. That works fine. But this doesn't work for the multiple delete option in django admin. I already know that I have to edit the delete_queryset() in admin.py. What I need to know is how to get the field IP from Computer from the queryset that the delete_queryset() method returns. When I do the following in admin.py: class TemplateAdmin(admin.ModelAdmin): def delete_queryset(self,request,queryset): print(queryset) print(queryset.values('computer')) ... And I try to delete multiple template objects (A,B and C) I get the following response: <QuerySet [<Template: A>, Template: B>, Template: C>]> <QuerySet [{'computer': 22}, {'computer': 21}, {'computer': 21}]> 22 and 21 are the computer_id referenced by the ForeignKey in A,B and C. The question is, how do I access the IP field from those computers so that I can make the API request in the delete_queryset() method? -
django unable to connect with postgres from docker container
Dockerfile FROM python:3.8 ARG index_url ENV PYTHONUNBUFFERED 1 WORKDIR /usr/src/report_backend COPY ./ /usr/src/report_backend RUN apt-get -y update RUN pip install -r requirements.txt CMD ["/bin/bash"] docker-compose file version: "3.9" services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" django db settings DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "story", "USER": "monetree", "PASSWORD": "Thinkonce", "HOST": "dev.report.inergio.io", "PORT": 5432 }, } Here i am trying to connect local server database. but i am getting below error web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 25, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 199, in get_new_connection web_1 | connection = Database.connect(**conn_params) web_1 | File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect web_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | django.db.utils.OperationalError: FATAL: database "story" does not exist here is my database. database already exist but it is not working . psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) Type "help" for help. postgres=# postgres=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -------------+----------+----------+---------+---------+----------------------- postgres | postgres | UTF8 | C.UTF-8 | C.UTF-8 | story | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =Tc/postgres + | | | … -
Picking database in django
I am developing a patient tracking system. to summarize. I need a database in the backend where we create a flexible schema (will evolve over time) for keeping track of health related data. I have some of the fields I want in it now. also i will develop front-end portal that people can access themselves or be access by an admin where we will ask questions that fill those fields. That front-end will also display to the user or the admin a summary of those datapoints. Can anyone tell me does postgresql can solve this problem or should i choose mongoDB? i am so sorry for posting without code, actually i tried of making decision which one should i choose. -
Docker-compose cant reach second command
I have my docker-compose.yaml file like this: version: "3" services: app: build: context: . dockerfile: Dockerfile ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" sh -c "python simple_script.py" and the problem is that when i run docker-compose up it never reaches the second command ( sh -c "python simple_script.py" ) . I think this is because the first command sh -c "python manage.py runserver 0.0.0.0:8000" never exits. Is there a way to run two commands like this? -
Async Class Based Views in Django
I am new to Django and I have been working on a Stripe based application and I found out that my class based views are quiet slow and I need to make them run as fast as possible. I discovered that in Django there is Asynchronous Support available but I am unable to figure how can I use it in class based views everywhere I find there are functional based example just. Django documentation that I was looking into was: Django Asynchronous Support I am adding an example code where I want to convert it into async support view VIEW: class BillInfo(DisablePATCHMethod, generics.RetrieveAPIView): serializer_class = BillSerializer SERIALIZER: class BillSerializer(ReturnNoneSerializer, serializers.ModelSerializer): interval = serializers.CharField(read_only=True, required=False) amount = serializers.IntegerField(read_only=True, required=False) date = serializers.DateTimeField(read_only=True, required=False) is_active = serializers.BooleanField(read_only=True, required=False) subscription_expiry = serializers.BooleanField(read_only=True, required=False) active_jobs = serializers.IntegerField(read_only=True, required=False) class Meta: model = Billing fields = "__all__" def to_representation(self, validated_data): stripe.api_key = settings.STRIPE_API_KEY stripe_sub = (stripe.Subscription.retrieve(self.context["request"].billing.stripe_subscription_id)) stripe_object = stripe_sub.get("items") quantity = stripe_object.get("data")[0].get("quantity") amount = stripe_object.get("data")[0].get("price").get("unit_amount") // 100 * quantity interval = stripe_object.get("data")[0].get("plan").get("interval") date = datetime.fromtimestamp(stripe_sub.current_period_end).strftime("%Y-%m-%d %H:%M:%S") if validated_data.subscription_end < make_aware(datetime.now()): is_active = False else: is_active = True if validated_data.subscription_end <= make_aware(datetime.now()): subscription_expiry = True else: subscription_expiry = False return { "date": date, "interval": interval, "amount": …