Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django localhost refusing connection from another django localhost
I have two django applications, currently running on localhost. I plan to have them on two separate servers, but for now, they are running on my machine. App A is running on :8000 App B is running on :8010 When I try to make a request from A to B by using: import requests requests.post('http://0.0.0.0:8010/api/plan', data=post_data) I get a connection error: urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='0.0.0.0', port=8010): Max retries exceeded with url: /api/plan (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f82fed36630>: Failed to establish a new connection: [Errno 111] Connection refused',)) In my B app I have ALLOWED_HOSTS = ['*'] Anyone has any idea what am I missing? -
postgresql: Invalid data directory | Can't open PID file /var/run/postgresql/10-main.pid (yet?) after start: No such file or directory
This error is showing after running this command: sudo systemctl status postgresql@10-main.service postgresql@10-main.service - PostgreSQL Cluster 10-main Loaded: loaded (/lib/systemd/system/postgresql@.service; indirect; vendor preset: enabled) Active: failed (Result: protocol) since Tue 2020-12-01 14:21:40 UTC; 2s ago Process: 1603 ExecStart=/usr/bin/pg_ctlcluster --skip-systemctl-redirect 10-main start (code=exited, sta Dec 01 14:21:40 ubuntu-s-1vcpu-2gb-sgp1-01 systemd[1]: Starting PostgreSQL Cluster 10-main... Dec 01 14:21:40 ubuntu-s-1vcpu-2gb-sgp1-01 postgresql@10-main[1603]: Error: Invalid data directory Dec 01 14:21:40 ubuntu-s-1vcpu-2gb-sgp1-01 systemd[1]: postgresql@10-main.service: Can't open PID file /va Dec 01 14:21:40 ubuntu-s-1vcpu-2gb-sgp1-01 systemd[1]: postgresql@10-main.service: Failed with result 'pro Dec 01 14:21:40 ubuntu-s-1vcpu-2gb-sgp1-01 systemd[1]: Failed to start PostgreSQL Cluster 10-main. Here is the content of /etc/postgresql/10/main/postgresql.conf file: # ----------------------------- # PostgreSQL configuration file # ----------------------------- # # This file consists of lines of the form: # # name = value # # (The "=" is optional.) Whitespace may be used. Comments are introduced with # "#" anywhere on a line. The complete list of parameter names and allowed # values can be found in the PostgreSQL documentation. # # The commented-out settings shown in this file represent the default values. # Re-commenting a setting is NOT sufficient to revert it to the default value; # you need to reload the server. # # This file is read … -
Django Only non-relations and foreign keys permitted
I'm trying to create a script here that looks at my staff table list that analyzes staffs email addresses and compares it to the login names in the system to assign them to their classrooms, but my script keeps on crashing. What's the goal ? The goal is I have a table called sections, sections are classrooms . Each classroom has a teacher assigned to them. However, in order for the teacher to see the classrooms they are assigned to, im linking this by the users login name which is their email address. However, although my logic from a print statment does work on my queries, it fails on updating the many to many fields. Here is my code. FUNCTION def AssignLoginToSection(): users = User.objects.all() for user_email in users: email = user_email.email print('Getting Email addresses in system.') if Section.objects.filter(staffpsid__email = email): section = Section.objects.filter(staffpsid__email = email) print("Found Matching Login Name.") print('The following sections were found with this users email.', section) Section.objects.filter(staffpsid__email = email).update(teacher_username= email) print('Added user login name to section.') else: print("No matching login name.") return("Done") MODELS # Section Information Stored class Section(models.Model): sectionpsid= models.CharField(primary_key = True, default = "", max_length = 50) schoolpsid = models.ForeignKey(School,on_delete = models.CASCADE, default = … -
Python, Django: Unique combinations inside a models.py-class?
Good afternoon, I would like to ask, if there's a way to define a unique combination inside my django-model? For example: class Example(models.Model): value_01 = models.Foreignkey(xyz, null=False, blank=False, on_delete=models.CASCADE) value_02 = models.Charfield(max_length=25, null=False, blank=False) Instead of making these two values unique on their own, is it possible to define a unique combination of these two values? Thanks a lot for you help and effort! -
How to post a list in django REST
I tried to get this: output { "counter": 2, "items": ["a", "a", "b", "c"] } serializers.py class OrderSerializer(serializers.ModelSerializer): items = serializers.ListField() counter = serializers.PrimaryKeyRelatedField(queryset=Counter.objects.all()) class Meta: model = Order fields = ['counter', 'items'] but I got this error: error Got AttributeError when attempting to get a value for field `items` on serializer `OrderSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Order` instance. Original exception text was: 'Order' object has no attribute 'items'. Should I create a variable in models.py called "items" because I tried it doesn't work either? -
Django IndexError at /viewissuedbookbystudent
so I happen to have this error while trying to run django projects. It saysIndexError at /viewissuedbookbystudent This was the project that I want to develop from https://github.com/sumitkumar1503/librarymanagement enter image description here Can anyone please help :) really need it.This is the viewissuedbookbystudent def, also I am very new at this so please help. def viewissuedbookbystudent(request): student=models.StudentExtra.objects.filter(user_id=request.user.id) issuedbook=models.IssuedBook.objects.filter(enrollment=student[0].enrollment) li1=[] li2=[] for ib in issuedbook: books=models.Book.objects.filter(isbn=ib.isbn) for book in books: t=(request.user,student[0].enrollment,student[0].branch,book.name,book.author) li1.append(t) issdate=str(ib.issuedate.day)+'-'+str(ib.issuedate.month)+'-'+str(ib.issuedate.year) expdate=str(ib.expirydate.day)+'-'+str(ib.expirydate.month)+'-'+str(ib.expirydate.year) #fine calculation days=(date.today()-ib.issuedate) print(date.today()) d=days.days fine=0 if d>15: day=d-15 fine=day*10000 t=(issdate,expdate,fine) li2.append(t) return render(request,'library/viewissuedbookbystudent.html',{'li1':li1,'li2':li2}) -
HTTP request function, indicates that there is no model attribute - DJango
I've implemented a model and a view function. The problem is that the function, which takes the http resquest, tells me that an attribute of the model does not exist. And I don't know what could be happening. views.py def home (request , data=None): #item.objects.filter(radius) items_area_location =item.objects.filter(radius<data) response = serialize('json', items_area_location) return HttpResponse(response) Models.py class item (models.Model): certificate=models.ImageField(default=None) provider = models.ForeignKey(serviceProvider, on_delete=models.CASCADE) radius = models.FloatField(default=None) description= models.TextField(blank = True) hour_init = models.TimeField() hour_end = models.TimeField() urls.py urlpatterns = [ path('admin/', admin.site.urls), path('home/<int:data>/', home, name='home'), ] This is what I get when there is a GET resquest with domain/home/somenumber: name 'radius' is not defined > NameError at /home/10/ name 'radius' is not defined Request > Method: GET Request URL: http://127.0.0.1:8000/home/10/ Django > Version: 2.2.12 Exception Type: NameError Exception Value: name > 'radius' is not defined Exception > in home, line 15 Python Executable: /usr/bin/python3 Python > Version: 3.8.5 Python Path: > ['/home/julian/Documentos/Programación/CallServiceBackEnd', > '/usr/lib/python38.zip', '/usr/lib/python3.8', > '/usr/lib/python3.8/lib-dynload', > '/home/julian/.local/lib/python3.8/site-packages', > '/usr/local/lib/python3.8/dist-packages', > '/usr/lib/python3/dist-packages'] Server time: Tue, 1 Dec 2020 > 13:46:46 +0000 -
Django is not sending an email
I'm currently making a Django website want to make sure that my user gets the email I sent but I get it in the console. Nothing is working. I'm using Django version 2.1.5 if it helps. Please help me!! Here is my code: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TDS = False EMAIL_HOST_USER = 'email' EMAIL_HOST_PASSWORD = 'password' Again, please help!!!! -
How to use serializer inside serializer?
Now this is my plan: I want to be able to show followers for users,but i have a problem.I have to use nested serializers to show serializers which gives me this error: followers_set= UserSerializer(source='followers',many=True) NameError: name 'UserSerializer' is not defined``` Now i am using this kind of modelling in my API: Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=80,unique=True,default='SOME STRING') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') class FollowUserModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE, related_name='followers') profile = models.ForeignKey(User,on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now=True) And here are my serializers: Serializers.py class UserSerializer(serializers.ModelSerializer): followers_set= UserSerializer(source='followers',many=True) class Meta: model = User fields = ('id','email','username','followers_set') How can i modify it in a way that it shows serializers inside serializer?? -
HOW TO FILTER BY BOOLEAN FIELD IN SEARCH BAR - DJANGO
I'm working on a Django Project that is a project management system. Basically in the navbar I've implemented a searcher to search for specific projects, the user can search for the title, the client, the description, ecc... I'd like to give them the possibility of searching also the projects that are urgent (urgent in my Project model is a boolean field), but the way I implemented it doesn't work. This is my Project Model: class Project(models.Model): title = models.CharField(max_length=255) description = models.CharField(max_length=1000) client = models.ForeignKey(Cliente, on_delete=models.CASCADE) complete = models.BooleanField(default=False) urgent = models.BooleanField(default=False) deadline = models.DateField() ... To make the search bar (that in my html file is:) <form method="get" class="form-inline"> <input class="form-control mr-sm-2" name="q" id="id_q" type="text" placeholder="Search..." aria-label="Search" value="{{query}}"> <button class="btn btn-outline-dark my-2 my-sm-0" type="submit"> <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-search" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M10.442 10.442a1 1 0 0 1 1.415 0l3.85 3.85a1 1 0 0 1-1.414 1.415l-3.85-3.85a1 1 0 0 1 0-1.415z"/> <path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11zM13 6.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0z"/> </svg> </button> work I've implemented this function: def get_projects_qs(proj, query=None): queryset = [] queries … -
password not geting hashed django rest framework
i'm using using customuser and trying to create user with drf but password not getting hashed. its returning raw password and because of that i can't use authentication its working with only user created by admin class CustomUserMananager(BaseUserManager): """ Custom user model manager where email will be unique identifier """ def create_user(self, email, password, **extra_fields): """ create and save user with given email and password """ if not email: raise ValueError(_('email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save superuser with given email and password """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('SuperUser must have is_staff=True')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('SuperUser must have is_superuser=True')) return self.create_user(email, password, **extra_fields) serializer: class CustomUserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) class Meta: model = CustomUser fields = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'password', 'is_active', 'user_type', 'otp') def create(self, validated_data): return CustomUser.objects.create_user(**validated_data) views: @api_view(["POST"]) @permission_classes((AllowAny,)) def register(request): #permission_classes = [(AllowAny, )] serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): serializer.is_active = False user_otp = randint(999, 9999) otp_code = str(user_otp) email = request.data.get('email') send_mail( 'Otp verification', otp_code, 'jv', [email], fail_silently=False, ) serializer.save(otp=user_otp) return Response({'response': 'User registered successfully, … -
Django FilteredRelation is not working with GenericRelation
I have the following models: class Workspace(Model): pass class Event(Model): workspace = ForeignKey(Workspace) limit = FloatField(default=0) entity_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) entity_id = models.PositiveIntegerField() entity = GenericForeignKey('entity_type', 'entity_id') class Entity(Model): events = GenericRelation(Event, content_type_field='entity_type', object_id_field='entity_id') class Meta: abstract = True class SomeEntity(Entity): pass Now I need to build a queryset to sort objects of SomeEntity by the limit of their events inside a given Workspace The SQL query I'm hoping to have is something like this: SELECT "some_entity"."id", workspace_events."id", COALESCE(workspace_events."limit", 0) AS "limit" FROM "some_entity" LEFT OUTER JOIN "event" workspace_events ON ( "some_entity"."id" = workspace_events."entity_id" AND workspace_events."entity_type_id" = SOME_ENTITY_CONENT_TYPE_ID AND workspace_events."workspace_id" = GIVEN_WORKSPACE_ID ) ) ORDER BY "limit" DESC' Where: SOME_ENTITY_CONTENT_TYPE_ID is the content type id of the SomeEntity model. GIVEN_WORKSPACE_ID is the workspace id I want to filter the events on. The queryset I'm using is this: SomeEntity.objects.annotate( workspace_events=FilteredRelation('events', condition=Q(events__workspace_id=GIVEN_WORKSPACE_ID)), limit=Coalesce('workspace_events__limit', 0), ).values('id', 'workspace_events__id', 'limit').order_by('-limit') But the query I'm getting from the above queryset doesn't include the workspace condition in the join at all! SELECT "some_entity"."id", workspace_events."id", COALESCE(workspace_events."limit", 0) AS "limit" FROM "some_entity" LEFT OUTER JOIN "event" workspace_events ON ( "some_entity"."id" = workspace_events."entity_id" AND workspace_events."entity_type_id" = SOME_ENTITY_CONENT_TYPE_ID AND ) ) ORDER BY "limit" DESC' What am I doing wrong? Why … -
Staff user can't login to django admin panel
I am trying to create a custom user model in my django app. But Whenever I tried to do so, I can't login with "staff user" created by the "super user" from the admin panel. It says: "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitve." app name: Backend Backend/models.py from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) # Create your models here. class UserManager(BaseUserManager): def create_user( self, username = None, email = None, password = None, is_active = True, is_staff = False, is_admin = False ): if not username: raise ValueError("Users must have a username") if not password: raise ValueError("Users must have a password") if not email: raise ValueError("Users must have a email") user_obj = self.model( username = username ) user_obj.email = self.normalize_email(email) user_obj.set_password(password) user_obj.is_active = is_active user_obj.is_staff = is_staff user_obj.is_admin = is_admin user_obj.save(using=self._db) return user_obj def create_staffuser(self, username, email, password): user_obj = self.create_user( username = username, email = email, password = password, is_staff = True ) return user_obj def create_superuser(self, username, email, password): user_obj = self.create_user( username = username, email = email, password = password, is_staff = True, is_admin = True ) return user_obj class User(AbstractBaseUser): … -
DRF - Custom Social Authentication
I want to ask a question about Social Auth WorkFlow. I was using simple JWT for my learning project and I wanted to add Social Auth which may work together with simple JWT. I searched and I found a lot libraries like allauth, python-social, social-app-django, drf-socialoath2 and etc. but they all were really complex to be honest to manage and customize so I decided to write my own direct way to authenticate with Facebook. In my code I am not keeping application secret in my backend and I am not using it at all. The procedure is as follow: Client click on "Sign in with Facebook" button and front-end gets access token from API call. No redirectURI Frontend send this access token to DRF Serializer validates the token and using python Facebook SDK, I check this token with Facebook If token is valid, I receive user information from Facebook. If user exists, authenticate it, if doesn`t, register with social password (which is really complex, long and is in environmental variables). After authenticating I send refresh, access token gotten from Simple JWT back to front end and remaining is same as before. It was really comfortable for me to do this … -
I want the data of the same row whose check box I will click.my table row is in for loop
I want the data of the same row whose check box I will click. my table row is in for loop and i want to display total price at end but it displaying all the boxes. And i have take the value by name in my views but here my form component are in for loop so if data is not there it should not come. here is my index.html: {% for j in package %} <tr class="valid-container"> <td style="cursor:pointer;"> <input type="checkbox" name="c1" id="c1">&nbsp; {{ j.visa_type }} </td> <td height="52"> <select class="custom-select processing_type" name="processing_type" data-id="{{ j.id }}" required> <option value="{{ j.price }}" selected>Normal</option> <option value="{{ j.express_price }}">Express</option> </select> </td> <td height="52"> <select class="custom-select no_of_person" name="no_of_person" data-id="{{ j.id }}" required> <option value="1" selected>1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> </td> <td width="190" height="60"> <div class="input-group date" data-date-format="dd.mm.yyyy"> <div class="input-group mb-2"> <input type="text" class="form-control" name="travel_date" id="date" placeholder="dd.mm.yyyy"> <div class="input-group-text"><i class="ti-calendar"></i></div> <div class="input-group-addon"> </div> <div class="input-group-prepend"> </div> </div> </div> </td> <td>{{ j.currency_type }}&nbsp;&nbsp; <output name="result">{{ j.price }}</output>.00</td> </tr> {% endfor %} and this is my package.js: $('.valid-container').ready(function() { var date = $(this).find('#date').attr('required',true); $('select').on('change', function() { var id = $(this).data("id"); var … -
what number of apps is too much for django
I am working on a Django project which might have 20 apps in the end. I wanted to know how many apps a Django project can have. I am concerned about the speed of the project as it grows. -
What is the is_admin in Django?? and how is it different from is_staff?
I'm trying to make a custom user model in Django and was looking through the documents in the Django website and had some queries that I wanted to ask. There are explanations for is_superuser and is_active, is_staff and etc. However, I couldn't find the explanation for the is_admin. What is this is_admin and how is this different from is_staff? I'm guessing that it's kind of similar to the is_staff. This is found in the https://docs.djangoproject.com/en/3.1/topics/auth/customizing/#a-full-example part, where you can see the user.s_admin=True -
How to import urls from apps in django main urls file
I have the following project structure. This is my INSTALLED_APPS array. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'climemanage.clients' ] Then I tried to add the clients.urls file in the parent urls file as the below. from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('clients/', include('clients.urls')) ] But I'm getting this error. ModuleNotFoundError: No module named 'clients' I can solve this by using the following path. include('climemanage.clients.urls') but I want to skip climemanage from the path. I have tried different ways as, import clients import climemanage.clients from climemanage import clients But nothing is working. -
Sending notification from Django Backend to Flutter application
I am implementing single device only login using django-rest-framework, but in order to log out the user from previously logged in device i want to send some notification from backend to frontend, in order to achieve this what would be the possible options present for django? -
DjangoRestFramework - How can I use 'pk' to filter a list?
I want to filter a list of BatchLog objects according to pk that I send through the request - which is their batch_id. Is there a way to access it on views.py file? I have this in my urls.py file path('feed/<int:pk>', GetFeedItemView.as_view()) And in my views.py file I want to access a BatchLog object by filtering its batch_id class GetFeedItemView(RetrieveAPIView): serializer_class = FeedSerializer def get_queryset(self): return BatchLog.objects.filter(batch_id=self.request.pk) This filter(batch_id=self.request.pk) doesn't work but I want to implement it in the same logic. How can I achieve this? Thanks a lot. -
How to add username to the filterset_fields in views Django Rest Framework where the user is the foreign key of the model?
I have below model in my models.py which has the django User model as the foreign key and I want to add username into the filterset_fields in my views in order to filter the user employment by username instead of user id. Any help would be great! Thank you! class UserEmployment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='employment') position = models.TextField(blank=True) company = models.TextField(blank=True) start_year = models.IntegerField(blank=True, null=True) end_year = models.IntegerField(blank=True, null=True) currently_work = models.BooleanField(default=False) Serializer class, class UserEmploymentSerializer(serializers.ModelSerializer): class Meta: model = UserEmployment fields = ['id', 'user', 'position', 'company', 'start_year', 'end_year', 'currently_work'] View class, class UserEmploymentViewSet(viewsets.ModelViewSet): queryset = UserEmployment.objects.all() serializer_class = UserEmploymentSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['user'] # I want this to be 'username' in order to filter employment list by username http_method_names = ['get'] Thank you! -
Pass anything in URL Django and return page
I want that if I pass anything in URL, Django will accept that path('user/username/update/<str:id>/', views.update_activities, name='update_activity_on_selected_user'), I want that everything that will passed on line username, it will return that function of updating. path('user/username/update/str:id/', views.update_activities, name='update_activity_on_selected_user'), -
DJANGO - how to run a standalone script in an app?
I would like to write a stand alone script to up-load a lot of stuff from an excel file, which will be uploaded on multiple models, thus using django-import-export would be a bit painful. this is my script : #! python3 # registry_people_contacts.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'GestionaleCogni.settings.dev') django.setup() from comuni_italiani.models import Provincia import openpyxl wb = openpyxl.load_workbook('upload_person_and_contacts.xlsx') sheet1 = wb['Sheet1'] .....doing other stuff with the excel file This is my project folder structure: ├── asgi.py ├── cogni_mixins.py ├── __init__.py ├── note_server.txt ├── __pycache__ │ ├── cogni_mixins.cpython-37.pyc │ ├── __init__.cpython-37.pyc │ ├── urls.cpython-37.pyc │ └── wsgi.cpython-37.pyc ├── settings │ ├── base.py │ ├── dev.py │ ├── __init__.py │ ├── production.py │ └── __pycache__ │ ├── base.cpython-37.pyc │ ├── dev.cpython-37.pyc │ ├── __init__.cpython-37.pyc │ └── production.cpython-37.pyc ├── urls.py └── wsgi.py I'm using a settings folder, to differentiate between production and development. Since I'm using pycharm I was think of opening the terminal directly on the folder and using the command " python3 registry_people_contacts.py ", but I get the error: "ModuleNotFoundError: No module named 'GestionaleCogni'" which is the project folder with the settings folder in it. I know there are custom commmands, but since I'm doing this operation only once, I'm … -
Django application Parallel processing, Memmory Error and longer response time
I have a Django application that is having the Spacy Custom NER Model which is hosted in a Dual-core server. When I performed the load test using JMeter, It happened to see that on every parallel API call, memory seems to build up slightly and also it has a longer response time. During this time When we try to call the same API from a different machine, it is taking a very long time to respond. So I have tried multiprocessing using sample code as below, import os import multiprocessing def main(): import gc pool = multiprocessing.Pool(processes=os.cpu_count() - 1) result_async = [pool.apply_async(<FUNCTION_NAME>, args=(<ARGS>,))] pool.close() pool.join() results = [r.get() for r in result_async] gc.collect() return Response(results, status=status.HTTP_200_OK) How ever this solved the problem of building memory, but a longer response time issue still exists. Also, some API fails due to memory errors Error is as follow, ERROR 2020-12-01 10:00:00,713 views 7667 140236856129280 [Errno 12] Cannot allocate memory Is there something wrong with my approach?? Is there any other better solution? -
Django: Google/Microsoft Sign In To Web App & Page Permissions
I have 2 Microsoft Azure Groups (synced with GSuite) I want to configure access for in my Django web app so that Team A can access Page A and Team B can access Page B only. I can add a Microsoft or Google Sign In button to my web app, but then how do I use that to determine what pages the user can access? I could use the Google Groups API to get the group information (https://cloud.google.com/identity/docs/how-to/query-memberships#python_1), but the problem there is that I either need to authenticate with a GSuite administrator account or add the Service Account as the group owner (and considering the groups have access to various resources on Google Cloud, that's not a very secure option). The only alternative I can think of is to use the Microsoft Azure Graph API instead to get the group information (https://docs.microsoft.com/en-gb/previous-versions/azure/ad/graph/api/groups-operations#BasicoperationsongroupsGetgroups). The latter option might work better as according to this question (Azure AD App Read Group membership) I should be able to grant the app read-only access without the need for an additional service account. Once I have the group information, is there a simple way to say within each Django View "If Authenticated User is a …