Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django creates new record instead of updating existing record
I am new to Python and Django, trying to create an app that can create and update the Member (custom table in SQL Database). Create works fine but on update instead of updating the existing member it is creating new record every time I submit. Sorry because stackoverflow was not allowing me save 'VIEW.py single view class handled with URL parameter with ?id=idofrecord and &ed=T to show the Edit form' #LISTS VIEWS class NewMember(LoginRequiredMixin,TemplateView): def get(self, request, \*args, \*\*kwargs): memberId = request.GET.get('id') isEdit = request.GET.get('ed') print('NEW MEMBER VIEW TRIGGERED') print(memberId) print(isEdit) if isEdit == 'T': memberObject = Member.objects.get(id=memberId) form = MemberForm(instance=memberObject) print("EDIT TRIGGERED") return render(request, 'components/list/list-new-member.html', {'form':form, 'memberid':memberId}) elif memberId: form = MemberForm() context = Member.objects.get(id=memberId) print('VEIW MEMBER TRIGERRED') return render(request, 'components/list/list-view-member.html', {'context':context,'form':form}) else: #CREATE NEW MEMBER form = MemberForm() context = {'form':form} return render(request, 'components/list/list-new-member.html', context) def post(self, request, \*args, \*\*kwargs): print('REST POST PRINTED') form = MemberForm(request.POST, request.FILES) if form.is_valid(): retObj = form.save() print('RECORD UPDATED') return redirect('/app/list/member?id='+str(retObj.id)) else: print(request.POST) print(form.errors) print('REST PRINTING POST :form.is_valid() '+ str(form.is_valid())) if form.is_valid(): retObj = form.save() print(retObj.id) return redirect('/app/list/member?id='+str(retObj.id)) context = {'form':form} return render(request, 'components/list/list-new-member.html', context) It should update the existing record as form object has passed with Instance and Post object Model.py #MEMBER … -
How to connect Django web socket with the third-Party Web Sockets?
I want to connect my Django WebSocket with a third-party web socket. This program is one I wrote, and it functions properly. To avoid having to re-login with the third-party API, I have now added the code to check whether the same room is present in my database. if we use the same API KEY to re-connect to the third-party API. It gives the following error: {"event":"login","status":401,"message":"Connected from another location"} I want to see if the same cryptocurrency coin is already connected or not. We don't want to logon with the same API KEY once we're connected. I have two issues here: Don't send the login request to that web socket again. Don't send the subscribe request, if the same coin already exists. Let's say BTCUSD already connected and giving me the data. I want to just connect to the next user to same room and get the data on next request. import websocket import time import ssl from channels.generic.websocket import AsyncWebsocketConsumer from .models import Room login = { "event": "login", "data": { "apiKey": "API_KEY", }, } class CryptoConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) self.ws.connect("wss://crypto.financialmodelingprep.com") async def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = "crypto_%s" % … -
add onclick event radio buttons django forms
So i have a form i use django forms to render out and i have radio buttons that i have added the onclick function to using the code below. class Profile(forms.ModelForm): class Meta: model = User fields = [ "username", "email", "first_name", "last_name", "avatar", "staff_id", "matric_no", "library_id", "designation", "lib_user", ] widgets = { "designation": forms.RadioSelect(attrs={ "id":"label_68", "class":"form-radio validate[required]", "required":"", "name":"q68_typeA68", "onclick":"myFunction(0)", }), } whenever the form is rendered in html, it look like this <input type="radio" name="lib_user" value="" id="label_70_0" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(0)"> <input type="radio" name="lib_user" value="Yes" id="label_70_1" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(0)"> <input type="radio" name="lib_user" value="No" id="label_70_2" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(0)"> what i want to achieve is this <input type="radio" name="lib_user" value="" id="label_70_0" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(0)"> <input type="radio" name="lib_user" value="Yes" id="label_70_1" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(1)"> <input type="radio" name="lib_user" value="No" id="label_70_2" class="form-radio validate[required]" aria-describedby="label_70" name="q70_typeA70" onclick="myFunction1(2)"> So how do i go about it is what i need help with. -
Django Form resubmit issue when press back button
Django Form submit and link to the main page but when press back button, it shows data and ready to submits again. Views.py is here def contact(request): if request.method == "POST": form = ContactsForm(request.POST, request.FILES) if form.is_valid(): form.save() form = ContactsForm() messages.success(request, 'Contact request submitted successfully.') return HttpResponseRedirect(request.path_info) else: messages.error(request, 'Invalid form submission.') else: form = ContactsForm() projects = Projects.objects.filter(status=1).order_by('-updated_at') return render(request,'main/contact.html',{'contact':'current','projects':projects,'form':form}) -
Django AttributeError: 'tuple' object has no attribute 'splitlines'
I'm trying to create an user registration with email confirmation and came up with this code in the models.py class UserRegister(SuccessMessageMixin, FormView): template_name = 'login/form_register.html' form_class = UserRegisterForm redirect_authenticated_user = True success_url = reverse_lazy('tasks') success_message = "User has been created, please login" def form_valid(self, form): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(self.request) subject = 'Activate Your Account' message = render_to_string('login/account_activation_email.html'), { 'user':user, 'domain':current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), } user.email_user(subject, message) messages.add_message( self.request, messages.SUCCESS, 'Check Your Email For Account Activation Link' ) if user is not None: login(self.request, user) return super(UserRegister, self).form_valid(form) def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect('tasks') return super(UserRegister, self).get(*args, **kwargs) But I keep getting this error AttributeError: 'tuple' object has no attribute 'splitlines' This is the traceback Internal Server Error: /register/ Traceback (most recent call last): File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/views/generic/base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/views/generic/edit.py", line 153, in post return self.form_valid(form) File "/home/ihzacordova/projects/todo-list/login/models.py", line 52, in form_valid user.email_user(subject, message) File "/home/ihzacordova/.local/share/virtualenvs/todo-list-KiFNCv1Z/lib/python3.8/site-packages/django/contrib/auth/models.py", line 402, in email_user send_mail(subject, … -
Django annotate(),Count()
i get the output like this using annotate() and Count() <QuerySet [{'pid': 11, 'status': 'Completed', 'status__count': 3}, {'pid': 11, 'status': 'Hold', 'status__count': 12}, {'pid': 11, 'status': 'InProgress', 'status__count': 2}, {'pid': 11, 'status': 'New', 'status__count': 3}, }] this is code i write to get like this ** view.py** tasks = Task.objects.values('pid','status').annotate(Count('status')).order_by('pid') Actuallt i want my output like this ** <QuerySet [{'pid': 11, 'Completed': 3, 'Hold': 12, 'InProgress': 2,'New': 3},}] ** How can i do? -
Serializer returning empty Strings in a Django Project while displayed in Json
I have a serializer and views.py in a django which I am trying to access from flutter app. But the issue is that in the json I can see the string available but when it is called it is not showing any results. Here is the serializer: class ActiveSessionSerializer(serializers.ModelSerializer): .................................. class Meta: model = ActiveSession fields = '__all__' def __init__(self, queryset, *args, **kwargs): print(f'queryset: {queryset}') self.queryset = queryset super(ActiveSessionSerializer, self).__init__(*args, **kwargs) def to_representation(self, instance): print(f'instance: {instance}') return super(ActiveSessionSerializer, self).to_representation(instance) Here is the json: [ { "session_workout": "Lower1Updated", "activated": false, } ] but in the views.py def getActiveSession(request, **kwargs): last_active_session = ActiveSession.objects.filter(user=user).latest('id') serializer = ActiveSessionSerializer(last_active_session, many=False) print(f"Serialized active session data: {serializer.data}") return Response(serializer.data) The result of the serializer.data is the following: Serialized active session data: {'activated': False, 'session_workout': ''} My question what is the reason for showing empty string in the serializer.data while in the json data there is data populated. How to fix this error ? -
Django allauth Access blocked: This app’s request is invalid
I'm using django allauth. Everything working fine, except when trying to signup using Google. I got this error: Access blocked: This app’s request is invalid. Is there any solution to this? -
Please, I do have a little problem. it is no bug, my program is just not functioning the way I want it to
I have a list of product with each products having a "pack" feature which can allow users to input any number and then multiplies the number by "food price" of the selected product. views.py def food_box_func(): my_food_box = Food.objects.all() append_list_item = [] for item in my_food_box: image = item.image food_item = item.food_item food_price = item.food_price food_slug = item.slug list_item = [image,food_item,food_price,food_slug] new_list_item = append_list_item.append(list_item) return append_list_item def food_box(request, slug): quantity = "" total_price = "" for item in food_box_func(): if request.method == "POST": try: quantity = int(request.POST.get("price in pack")) print(quantity) total_price = quantity*item[2] print(total_price) return render(request,'payments/pay.html',{'price':total_price,'slug':slug,'quantity':quantity,'total_price':total_price}) except ValueError: return render(request,'food_app/404.html') break return render(request,'food_app/food_box.html',{'item':food_box_func(),'price':total_price,'slug':item[3]}) Here is my food template which is connected to the view above: <body> <div class="container"> <br><br><h1><center>Food box page!</center></h1><br><br> </div> {% for message in messages %} <div class="alert alert-{{message.tags}} alert-dismissible fade show" role="alert"> <strong>Message:</strong> {{message}} <button type="button" class="close" data-dismissible="alert" aria-label="close"> <span aria-hidden="True">&times;</span> </button> </div> {% endfor %} {% comment %} Each for loop item takes its slug input and directs the user to its particular view on the payment page. {% endcomment %} {% if user.is_authenticated %} {% for item in item %} <div class="container"> <a href= "{% url 'payments:payment' price=item.2 slug=item.3 %}"><img src={{item.0.url}} class="img-fluid"></a><br><br> <h2>{{item.1|capfirst}}</h2> <h3>₦{{item.2}}</h3> <button … -
Redux toolkit fullfilled even there is an error and showing the error message from django showing in fullfilled case
Fullfilled and update the state perfectly. But When use wrong credential, the detailed error from django showing in the fullfilled "userInfo" state. If we catch the error through rejectWithValue, the message is just "code 401" userSlice.js import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"; import axios from "axios"; export const login = createAsyncThunk( "USER_LOGIN_REQUEST", async (cred, thunkAPI) => { try { console.log("this is one thig"); console.log("username: ", cred.username, "password: ", cred.password); const config = { headers: { "Content-type": "application/json", }, }; const { data } = await axios.post( "/api/users/login/", { username: cred.username, password: cred.password }, config ); localStorage.setItem("userInfo", JSON.stringify(data)); return data; } catch (error) { return thunkAPI.rejectWithValue(error); } } ); const userInfoFromStorage = localStorage.getItem("userInfo") ? JSON.parse(localStorage.getItem("userInfo")) : null; const initialState = { userLogin: { userInfo: userInfoFromStorage }, }; const userSlice = createSlice({ name: "userRegister", initialState, reducers: {}, extraReducers: (builder) => { builder .addCase(login.pending, (state = {}, action) => { return { loading: true, userInfo: [] }; }) .addCase(login.fulfilled, (state = {}, action) => { return { loading: false, userInfo: action.payload }; }) .addCase(login.rejected, (state = {}, action) => { return { loading: false, error: action.payload.message }; }); }, }); export default userSlice.reducer; store.js const store = configureStore({ reducer: { userLogin: userLoginReducer, … -
django changeform_view extra_context
I'm trying to learn on model admin template customization. I need that custom template can read some data stored/passed in 'extra_context' admin.py from django.contrib import admin from .models import MailTemplate # Register your models here. class MailTemplateAdmin(admin.ModelAdmin): change_form_template = 'change_form_htmx.html' def changeform_view(self,request, object_id=None, form_url="", extra_context=None): extra_context = extra_context or {} extra_context['myvar']='this is myvar' return super(MailTemplateAdmin, self).changeform_view(request, object_id=object_id, form_url=form_url, extra_context=extra_context) admin.site.register(MailTemplate,MailTemplateAdmin) template 'change_form_htmx.html' {% extends "admin/base_site.html" %} {% load i18n admin_urls static admin_modify %} {% block extrahead %}{{ block.super }} <script src="{% url 'admin:jsi18n' %}"></script> {{ media }} {% endblock %} {% block extrastyle %}{{ block.super }}<link rel="stylesheet" href="{% static "admin/css/forms.css" %}">{% endblock %} {% block coltype %}colM{% endblock %} {% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} change-form{% endblock %} {% if not is_popup %} {% block breadcrumbs %} <div class="breadcrumbs"> <a href="{% url 'admin:index' %}">{% translate 'Home' %}</a> &rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a> &rsaquo; {% if has_view_permission %}<a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst }}</a>{% else %}{{ opts.verbose_name_plural|capfirst }}{% endif %} &rsaquo; {% if add %}{% blocktranslate with name=opts.verbose_name %}Add {{ name }}{% endblocktranslate %}{% else %}{{ original|truncatewords:"18" }}{% endif %} </div> {% endblock %} {% endif %} {% block content %}<div … -
Using generic views with HTTP verbs
I am trying to mix HTTP verbs with Django's Built-in class-based generic views, i understand that is a good pattern (correct me if not) to keep Url's like app/pets/ and use HTTP's verbs to define what to do (GET, POST/create, PUT/update, DELETE/delete, etc) instead of something like app/pets/add or app/pets/delete as Django's documentation shows when using generic views with forms So i tried something like this: urls.py: path('login/', views.sign_in, name='login'), path('logout/', views.log_out, name='logout'), path('register/', views.register, name='register'), path('pets/', views.Pet.as_view(), name= "pets"), Views.py class Pet(LoginRequiredMixin, View): login_url= "/vet/login/" #handle Get Request class PetListView(ListView): model= models.Pet context_object_name= "pets" template_name= "vet/index.html" #Handle Put request class PetUpdateView(): pass but i am getting and error of 405 method not allowed (and i think is not a good practice do this). i also tried this (defining the PetListView same as above): class Pet(LoginRequiredMixin, View): login_url= "/vet/login/" def get(self, request): return HttpResponse(PetListView.as_view()) But this just print the object on the screen. I am new to Django and i do not know what is the better approach to accomplish this using Django generic's views since it reduce a lot code for CRUD operations -
How do I manage my models in Django, is there an equivalent to a database diagram in VS Code?
I'm learning Django and my models are getting complex. The FK and PK relationships are doing my head in. I'm used to create database diagrams with SSMS in MS SQL Server, is there anything equivalent to this in SQLite? I've tried a number of VS code extensions, such as ERD Editor, ERD Preview and even just simple diagram tools such as draw.io The problem with them is there is no integration with the DB so or the classes in models.py -
Subprocess Popen to call a tasks file python which cannot able to load models in Django
I have Django app ..we have several tasks file(stored into tasks folder). And we want to call those tasks file from views.py Now when we call p = Popen("python","./tasks/task1.py", "jobid", stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True) output_filename, err = p.communicate(b"input data that is passed to subprocess' stdin") now in task1.py from app.models import Job #its throwing error It cannot import Models into task1.py where I have sent job id -
What is best way to serialize
I am quite new to django rest framework and I would like to discuss what is the best way to implement an API endpoints I am aiming to have. I have following JSON example: [ { 'top_lvl_key1': { id: 1 'some_key1': "value" 'some_key2' : "value" } }, { 'top_lvl_key2': { id: 1 'some_key1': "value" 'some_key2' : "value" } }, { 'top_lvl_key3': { id: 1 'some_key1': "value" 'some_key2' : "value" } }, { 'top_lvl_key1': { id: 2 'some_key1': "value" 'some_key3' : "value" } }, ] and I want to have 3 endpoints [POST] /insert inserting and parsing the entire JSON to store it into models [GET] /detail/<top_lvl_key>/ Display all record for specfici top_lvl_key [GET] /detail//<top_lvl_key>/id/ Display a record for specific top_lvl_key and specific id (only 1 record) As you can see, I need to store each type of top_lvl_key to different model so I can retrieve for GET requests. However I am not sure how should I got about serializing the JSON, since the dictionaries of the top_lvl_keys can differ. For example top_lvl_key_1 can sometimes have some_key_1 and some_key_2, but sometimes some_key_1 and some_key_2. So far I have been implementing the models with blank=True, null=True, but I am not sure this … -
Django server crashes after clicking button
I currently have code that used to run and now it appears to crash the server I run the python manage.py runserver and I have a function in my views that outputs a dataframe after a trigger button is clicked. Something in this function is messing up the output, because as I click the button to output the html table the server crashes and I have to retype python manage.py runserver to launch it back to the home page. Does anyone have any idea on a potential solution? -
Debugging Django request lifecycle
What's the first function Django executes after receiving a request? I need to put a breakpoint just at the moment Django receives the request and observe the methods being called next, step by step. For example, I call localhost:8000/test where do I insert the very first breakpoint to see how the middleware processes the request? -
Django Rest Framework - Why am I getting a CSRF cookie not set on only one URL when there is NO difference from the other forms
I have this URL for someone to rate an opportunity: path("opportunities/rate/", RateOpportunity.as_view), I am using a Vue application to make a post request and all the other forms on the site work fine and I can make the requests and post content but this specific endpoint gives me a CSRF cookie not set error. There is no difference between this form and the other forms. This is the view I am using: class RateOpportunity(generics.CreateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = OpportunityRateSerializer name = "rate-opportunity" def get_queryset(self): id = self.kwargs["pk"] return Opportunity.objects.all().filter(opportunity=id) Why am I getting this error only on this endpoint and not any one of the others? -
how to remove deprecated code from the old django migration files
I am removing dead code in my django apps, and realized that one of the functions is being used in an old migration file. What is the correct way to remove this code from the old migration file without causing database issues? -
Add payment in django project to extend an expiration date of posts./
I have a project where the user can post an Ad and this Ad will be available only for 30 days. I need to add a payment method to extend the Expiration date of the Ad. Here is my Ad creation view . class AdvertiseCreateView(APIView): permission_classes = [IsAuthenticated] def post(self, request): serializer = AdvertiseSerializer(data=request.data) user = request.user if serializer.is_valid(): print(user) serializer.save(owner = user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) List view: class AdvertisesListView(APIView): def get(self, request): advertises = Advertise.objects.filter(Q (expiration_date__gt = Now())) serializer = AdvertiseSerializer(advertises, many=True) return Response(serializer.data, status = status.HTTP_200_OK) Models: class Advertise(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="advertise") category = models.CharField(max_length= 200, choices = CATEGORY) location = models.CharField(max_length= 200, choices = LOCATIONS) description = models.TextField(max_length=600) price = models.FloatField(max_length=100) expiration_date = models.DateField(default = Expire_date, blank=True, null=True) #Expire date come from another file created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) class Meta: ordering = ['created_at'] def __str__(self): return self.category So the thing is when the user make his payment the expire date extends. I need help in payment part. Thanks in Advance. -
Request url without pagination django rest
All my sistem has pagination. I want request a single url without pagination, but as a request param, not in my remove in my application, because sometimes I want with pagination and sometimes without. Anyone can help me? -
ERROR: Failed building wheel for twisted-iocpsupport
error image I was trying to install daphne===4.0.0 but I keep getting this error, ERROR: Failed building wheel for twisted-iocpsupport -
Write a test to check if a post has been removed from the old group
I need to check that the post has disappeared from the old group page. I need to get my old group for her slack. old_group_response = self.authorized_client.get( reverse('group_list', args=(self.group.slug,)) ) And compare that old_group_response.context['page_obj'].paginator.count equals zero. This means that there are no posts in our old group. And check another new group, that there is 1 post there. How can I write it in the right way? I know what rubbish is written here (I'm just learning), this is what I was able to sketch. from django import forms from django.test import Client, TestCase from django.urls import reverse from ..models import Group, Post, User NEW_POST = reverse('posts:post_create') class PostFormTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.author_auth = User.objects.create_user(username='test auth') cls.not_author = User.objects.create_user(username='Not Author') cls.group = Group.objects.create( title='Test group_title', slug='test_slug', description='Test description') def setUp(self): self.authorized_client = Client() self.authorized_client.force_login(PostFormTests.author_auth) self.authorized_client_not_author = Client() self.authorized_client_not_author.force_login( PostFormTests.not_author) def test_post_old_group_response(self): """ Check if a post has been removed from the old group.""" post = Post.objects.create( group=PostFormTests.group, author=PostFormTests.author_auth, text='test post') group_2 = Group.objects.create( title='Test group_title2', slug='test_slug2', description='Test description2') posts_count = Post.objects.count() form_data = { 'text': 'text_post', 'group': group_2.id} old_group_response = self.authorized_client.get( reverse('posts:group_list', args=(self.group.slug)), data=form_data, follow=True) self.assertEqual( old_group_response, reverse( 'posts:post_detail', kwargs={'post_id': post.pk})) self.assertEqual(Post.objects.count(), posts_count) self.assertEqual(old_group_response.context[ 'page_obj'].paginator.count == 0) -
Why would a django-rest-framework test return a different response than an identical post via postman?
Context: I'm currently rewriting my django-rest-framework implementation to use a custom permissions class. In the process, I am writing tests to make sure that any future changes don't break anything. Related Objects: View class EventViewSet(viewsets.ModelViewSet): serializer_class = EventSerializer permission_classes = [ReadOnly, CheckPermission] def get_permissions(self): # This passes the kwargs needed for the permission check to the permission class if self.action in ['create'] and self.request.user.is_authenticated: return [CheckPermission(capability='events', action='write')] if self.action in ['retrieve', 'list']: return [CheckPermission(capability='events', action='read')] elif self.action in ['update', 'partial_update'] and self.request.user.is_authenticated: return [CheckPermission(capability='events', action='edit', org=Organization.objects.get(short_name=self.request.data['organizationChange']))] elif self.action == 'destroy' and self.request.user.is_authenticated: return [CheckPermission(capability='events', action='edit')] return super().get_permissions() def get_queryset(self): user = self.request.user if 'org' in self.request.query_params: org = Organization.objects.get(short_name=self.request.query_params['org']) # check if user has necessary permissions for the specific organization perm = CheckPermission(capability='event', org=org, action='read').has_permission(self.request, self) if perm: return Event.objects.filter(organization=org, removed=False) else: #return public events for that org return Event.objects.filter(organization=org, type=0, removed=False) else: try: q1 = Event.objects.filter(type=0, removed=False) if user.is_authenticated: memberships = AccountRoleMembership.objects.filter(user=user, removed=False, role__removed=False, role__capabilities__removed=False, role__capabilities__capability__name='event', role__capabilities__read=True) orgs = get_orgs(memberships) if orgs.count() > 0: for org in orgs: # check if user has necessary permissions for events with a specific organization perm = CheckPermission(capability='event', org=org, action='read').has_permission(self.request, self) if perm: q1 = q1 | Event.objects.filter(organization=org, type=1, removed=False) return q1 else: … -
Complex JSON Serialization in Django
I have a complex JSON (trimmed) [ { "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents": [ { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2021-09-25" }, "value": "35929000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2020-09-26" }, "value": "39789000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2019-09-28" }, "value": "50224000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2022-09-24" }, "value": "24977000000" } ], "NetIncomeLoss": [ { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2021-09-26", "endDate": "2022-09-24" }, "value": "99803000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2020-09-27", "endDate": "2021-09-25" }, "value": "94680000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2019-09-29", "endDate": "2020-09-26" }, "value": "57411000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2021-09-26", "endDate": "2022-09-24" }, "segment": { "dimension": "us-gaap:StatementEquityComponentsAxis", "value": "us-gaap:RetainedEarningsMember" }, "value": "99803000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2020-09-27", "endDate": "2021-09-25" }, "segment": { "dimension": "us-gaap:StatementEquityComponentsAxis", "value": "us-gaap:RetainedEarningsMember" }, "value": "94680000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2019-09-29", "endDate": "2020-09-26" }, "segment": { "dimension": "us-gaap:StatementEquityComponentsAxis", "value": "us-gaap:RetainedEarningsMember" }, "value": "57411000000" } ] } ] I have created the following class to use so that its easier to massage the data in @dataclass class Period: instant: …