Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My code is working on codepen but not on my editor
My code is working on codepen but not on my editor (PyCharm). This is part of django project. By not working I mean I get a blank page, with no output (no text). I have tried to read a few answers addressing a similar issue but none of these solutions seem to be working for me/or I am not applying them correctly. Specifically adding the full URL path for getting ScrollWatch through CDN. Here is a sample of my code html { % load script % } <html lang="en"> <head> <meta charset="UTF-8"> <title>The Gradient Boost</title> <link rel="stylesheet" href="{% static 'second/css/app/book.css' %}"> <script src="https://cdn.jsdelivr.net/npm/scrollwatch@2.0.1/dist/ScrollWatch-2.0.1.min.js"></script> </head> <body> <h2><div data-scroll-watch>First Text</div></h2> <h2><div data-scroll-watch>Second Text</div></h2> <h3><div data-scroll-watch>Third Text</div></h3> <script src="{% static 'second/js/app/book.js' %}"></script> </body> </html> css location -> static\second\css\app\book.css .watch-container { font-size: 2em; width: 75%; height: 150px; padding: 20px; margin: 50px auto; background-color: #0681CD; color: #fff; overflow: auto; text-align: center; } div { text-align: center; font-size: 1em; margin: 200px 0; opacity: 0; transition: opacity 1s; font-weight: normal } div.scroll-watch-in-view { opacity: 1; } and javascript location -> static\second\js\app\book.js (function() { var addElements = function() { var txt = document.createTextNode('Testing'); var el; el = document.createElement('div'); el.appendChild(txt); document.body.appendChild(el); // If we want newly injected elements to … -
argument of type 'QuerySet' is not iterable Django error
In my webapp, I have a friends feature, but one of the if statements produces an error Here is my UserProfileInfo model class UserProfileInfo(models.Model): connection = models.ManyToManyField(User,blank=True,related_name='follow_profile') And now here is my view: def friend_actions(request,username=None): current_user = request.user.userprofileinfo user = request.user # username = get("username") username = User.objects.get(username=username) other_user = get_object_or_404(UserProfileInfo,user__username=username) # other_user = UserProfileInfo.objects.get(username=username) url = other_user.get_absolute_url() if other_user in current_user.connection.all(): current_user.connection.remove(other_user) else: current_user.connection.add(other_user) return HttpResponseRedirect(url) However, this produces the following error: argument of type 'QuerySet' is not iterable Full traceback Traceback: File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\interests-site\interests-drf\mainapp\views.py" in friend_actions 453. if other_user in current_user.connection.all(): Exception Type: TypeError at /mainapp/profile/donnellan0007/connect/ Exception Value: argument of type 'QuerySet' is not iterable I am wondering how I can stop this error from occurring. I have been stumped by it all day -
Django hosting trouble with django.wsgi
I registered everything as it is written in the instructions for django hosting provider (jino), but errors popped up, which I can't even come close to understanding. [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] mod_wsgi (pid=61341): Failed to exec Python script file '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] mod_wsgi (pid=61341): Exception occurred processing WSGI script '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] Traceback (most recent call last): [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] File "/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi", line 4, in <module> [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] exec(open(activate_this).read(), dict(__file__=activate_this)) [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] FileNotFoundError: [Errno 2] \xd0\x9d\xd0\xb5\xd1\x82 \xd1\x82\xd0\xb0\xd0\xba\xd0\xbe\xd0\xb3\xd0\xbe \xd1\x84\xd0\xb0\xd0\xb9\xd0\xbb\xd0\xb0 \xd0\xb8\xd0\xbb\xd0\xb8 \xd0\xba\xd0\xb0\xd1\x82\xd0\xb0\xd0\xbb\xd0\xbe\xd0\xb3\xd0\xb0: '/home/users/m/marselabdullin/projects/caparol_center_spb_decision/env/bin/activate_this.py' [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] mod_wsgi (pid=37979): Failed to exec Python script file '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] mod_wsgi (pid=37979): Exception occurred processing WSGI script '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] Traceback (most recent call last): [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] File "/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi", line 4, in <module> [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] exec(open(activate_this).read(), dict(__file__=activate_this)) [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] FileNotFoundError: [Errno 2] \xd0\x9d\xd0\xb5\xd1\x82 \xd1\x82\xd0\xb0\xd0\xba\xd0\xbe\xd0\xb3\xd0\xbe \xd1\x84\xd0\xb0\xd0\xb9\xd0\xbb\xd0\xb0 \xd0\xb8\xd0\xbb\xd0\xb8 \xd0\xba\xd0\xb0\xd1\x82\xd0\xb0\xd0\xbb\xd0\xbe\xd0\xb3\xd0\xb0: … -
Problems with django error handling with ajax
I want to create ajax error handling function for that. Problems can be in the JsonResponse part.Also how to implement that in the template? I tried to create ajax function before but it did't work.I want to create something like on signup page by default views.py def auth_join(request, room, slug): if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): room_pass = form_auth.cleaned_data.get('room_pass') password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return JsonResponse('error') else: user = CustomUser.objects.get(username=user) room = get_object_or_404(Room, slug=slug) if user.has_perm('pass_perm', room): return HttpResponseRedirect(Room.get_absolute_url(room)) else: messages.error(request,'You don\'t have access to this page') return JsonResponse('error') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) template <form method='post' class='ui form' id="form"> {% csrf_token %} <div class="ui middle aligned centered grid"> <div class="four wide column"> <h4 class="ui dividing teal header">Enter room password</h4> <div class="field"> <label>Password</label> {{form_auth.room_pass}} </div> <div class="field"> <label>Confirm password</label> {{form_auth.password2}} </div> <button type="submit" class="ui teal button">join</button> {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <div class="ui green message">{{message}}</div> {% else %} <div class="ui red message">{{message}}</div> {% endif %} {% endfor %} {% endif %} {% if form_auth.errors %} {% for i in form_auth %} <div class="ui red message"> {{i.errors}} … -
Call for model field validation in the serializer
I will try to make a check for the uniqueness of the field at the validation level in the serializer and can not understand why the validator is not called at all. models.py class Vendor(models.Model): active = models.BooleanField(default=False) ... class VendorContacts(models.Model): vendor = models.ForeignKey('Vendors', related_name='contacts', on_delete=models.CASCADE) email = models.CharField(max_length=80, blank=True, null=True) ..... serializer.py class VendorContactCreateSerializer(serializers.ModelSerializer): email = serializers.CharField(validators=[RegexValidator(regex=r'[^@]+@[^\.]+\..+', message='Enter valid email address')]) vendor = serializers.PrimaryKeyRelatedField(queryset=Vendors.objects.all(), required=False, allow_null=True) class Meta: model = VendorContacts fields = (..... ) def create(self, validated_data): ..... #some logic def validate_email(self, value): print('Start validation') exist_contact = VendorContacts.objects.filter(email=value) if exist_contact: vc = get_object_or_404(VendorContacts, email=value) v = vc.vendor if v.active: raise serializers.ValidationError('Email {} already exists'.format(value)) return value In the above serializer, I perform a check at the def validate_email() model field level. print('Start validation') is not called. I tried the same at the object level through def validate(): but it is not called either. -
Sending data to Django channels
I have an external Python script which generates JSON data every second; on the other side i have a Django application. I would like to stream that data on a webpage on my Django app. I already built a consumer with Django channels, but i don't know how to make Django have the data that i generate from the other Python script. Here is my basic consumer: class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): print("received", event) # Echo the same received payload async def websocket_disconnect(self, event): print("disconnected", event) Is there a specific way do this? Or am i supposed to use another service in the middle?Any advice is appreciated -
IS there any one help me for this errors
Hi evrey one I got this errors in image any help please -
How to download a .txt file from a django project
I find difficulty on how to download my .txt file after pressing the button which calls the view respnosible for that. My .txt file is created locally in the path where my manage.py file resides. snippet code of my view: file_name= open("example.txt","w+") file_name.write("\r\n\r\n%s%s%s%s%s" % (var1," ",var2," ",var3)) response = HttpResponse(file_name, content_type="text/plain,charset=utf8") response['Content-Disposition'] = 'attachment; filename={0}'.format(file_name) file_name.close() return response What i have to change to be able to download my .txt file? -
how to load bootstrap in Django?
so I tried loading Bootstrap to Django. But since I wanted to customize the styling with scss, instead of putting the CDN url in header, I replaced it with a separate css file which has all of the Bootstrap stylings. Here's the code. <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="/style/main.css"> <title>{% block title %}BASE{% endblock %}</title> </head> <body> <div class="container"> {% block content %} {% endblock %} </div> </body> </html> I have the correct /style/main.css file, I've checked it by ctrl+clicking it. As mentioned, the file has ALL of the Bootstrap stylings. @charset "UTF-8"; /*! * Bootstrap v4.4.1 (https://getbootstrap.com/) * Copyright 2011-2019 The Bootstrap Authors * Copyright 2011-2019 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ :root { --blue: #007bff; --indigo: #6610f2; --purple: #6f42c1; --pink: #e83e8c; ### AND SO ON ### However my Django page wouldn't reflect it. When I hit refresh I don't see any styling. But when I restore the CDN url, Bootstrap is normally applied. I have no idea what the problem is. I would very much appreciate your help. :) -
Stripe - Retrieve Customer PaymentIntent history
I am building a platform where I am using Stripe's concept of a parent "platform" account and Connected Stripe accounts that belong to this platform. (e.g. Lyft model) Following Stripe's documentation, when I create a new customer in Stripe, I create it under the main platform account and also store all the payment methods under that customer. When a customer buys something from the Connected account, I follow this doc, where I clone payment method and create a PaymentIntent that is attached to the specific Connected account. And it all works. However, when I try to get a history of customer's transactions (List of PaymentIntents), it returns an empty list because it runs it against the main platform account: stripe.PaymentIntent.list(customer='cus_FJDHFGSJHDF') When I specify a customer AND connected account id, it returns an empty list, because that customer doesn't exist in that Connected account, however, the paymentIntents are present in that Connected account. So, what is the right way to create a PaymentIntent for a customer for a Connected account and then get the history of payments for that customer PER Connected Stripe account? Here is how I clone PaymentMethod and create PaymentIntent: payment_method = stripe.PaymentMethod.create( customer=customer, payment_method=customer.invoice_settings.default_payment_method, stripe_account=stripe_connect_id, ) intent … -
Obtain the name of my columns from my django model
I want to show some tables in my templates from my models and I need to know what are the fields from they. Obtain the data is easy, class fleet_bbdd_view(ListView): template_name = 'data_app/info-bbdd.html' paginate_by = 20 model = info context_object_name = 'infoList' Or if I want to specify, def getData(request): data1 = info.objects.all() # Ex1, obtain all the data data2 = info.objects.order_by('id','-data_timestamp').distinct('id') # Ex2, obtain the last data from the distinct ids ctx = {'Data1':data1, 'Data2':data2} return JsonResponse(ctx) But, how can I obtain the name of my columns? Exists something like this? cols = info.objects.fields() I'm sure is not a pro question, but I really don't know what can I do. Thank you very much -
invalid literal for int() with base 10 in django?
I wrote this code : views.py: class IndexView(TemplateView): template_name = 'index.html' class SchoolListView(ListView): context_object_name = 'schools' model = models.School class SchoolDetailView(DetailView): context_object_name = 'school_detail' model = models.School template_name = 'nineapp/school_detail.html' class SchoolCreateView(CreateView): fields = ('name', 'principal', 'location') model = models.School models.py: class School(models.Model): #ppk = models.IntegerField(default=0 , primary_key=True) name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=256) age = models.CharField(max_length=256) school = models.ForeignKey(School, related_name='students', on_delete=models.CASCADE) def __str__(self): return self.name urls.py: urlpatterns = [ url(r'^$', views.SchoolListView.as_view(), name='list'), url(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail'), url(r'^createsc/(?P<pk>[-\w]+)$', views.SchoolCreateView.as_view(), name='createsc'), ] this program is working correctly but when i want to go the createsc/ I've got this error: invalid literal for int() with base 10: 'createsc' please help me. -
Django: Query `id__in` with UUIDs
In Django, we can use the id__in query with a queryset to filter down a queryset based on a list of IDs. However, by default this will fail if your IDs are UUIDs. So this will not work and throw the error: LINE 1: ...OM "items_character" WHERE "items_character"."id" IN (SELECT... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. def foos(self): """ Returns the user's owned foos. """ # Todo: Cache & Bust On Update content_type = ContentType.objects.get_for_model(Foo) owned = Ownership.objects.filter(user=self, content_type=content_type) return objects.filter(id__in=owned.values_list("object_id", flat=True)) However, the following will work, if we manually convert the entire thing to UUID. Is there a way to make this work without this iteration over the set? def foos(self): """ Returns the user's owned foos. """ # Todo: Cache & Bust On Update content_type = ContentType.objects.get_for_model(Foo) owned = Ownership.objects.filter(user=self, content_type=content_type) owned_ids = list(owned.values_list("object_id", flat=True)) test = [] for fid in owned_ids: test.append(uuid.UUID(cid)) return Foo.objects.filter(id__in=test) -
python manage.py runserver keeps reloading stating file has changed
I've been working on a django project with no issues. I've pulled updated code from the remote repository and now if i do python manage.py runserver in cmd, i keep getting error Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. D:\some_project\someapp\schemes\models.py changed, reloading. Watching for file changes with StatReloader Performing system checks... then Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. D:\some_project\someapp\schemes\views.py changed, reloading. Watching for file changes with StatReloader Performing system checks... it keeps looping through all the files and all the apps that have in my django project. it works if i try python manage.py runserver --noreload however, i'm curious as to what lead to the issue in the first place. -
Django Rest Framework: Passing Context in Viewsets
Viewsets are convenient because we can do stuff like this and get a fully working serializer: class StoreObjectViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): permission_classes = [IsAuthenticated] queryset = StoreObject.active_objects.all() serializer_class = serializers.StoreObjectSerializer Unfortunately, as far as I know– to pass the context into the serializer we need to do things like this: PostSerializer(data=request.data, context={'request': request}) Which means we need to manually override every convenient method provided by ViewSets (as far as I know). Is there a way to inject the context into every serializer while still keeping Viewsets convenient? -
Which template loaders is Django using?
In documenation to cached Loader is written This loader is automatically enabled if OPTIONS['loaders'] isn’t specified and OPTIONS['debug'] is False How to confirm that Django is really using cached Loader? How to check which template loaders is Django using? -
It is possible to run two apps on different ports in single Django project?
I want to run 2 django apps on different ports in single project. It is possible? If so, how do I do it? -
Django rest framework, trying to customize the browsable API
I have a Django rest framework and I'm trying to customize one of the API's browsable API but I can't seem to be able to refer to it in the HTML File. <!DOCTYPE html> {% load rest_framework %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Second GDT Options</title> </head> <body> <form action="{% url 'secondgdt' %}" method="post"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Save"> </form> </body> </html> secondgdt/urls.py: from django.urls import include, path from rest_framework.routers import DefaultRouter from .views import PointsViewSet router = DefaultRouter() router.register(r'secondgdt', PointsViewSet, basename='secondgdt') urlpatterns = [ path('', include(router.urls)), ] This code raises the following error when running the server: NoReverseMatch at /secondgdt/ Reverse for 'secondgdt' not found. 'secondgdt' is not a valid view function or pattern name. -
Ifequal in django templates
Models.py solution_req = models.CharField(max_length=250, default=0, choices=(('FLC', 'FLC'), ('FSC', 'FSC'), ('Crate', 'Crate'), ('PPBox', 'PP Box'))) HTML {% ifequal l.solution_req PPBox %} <a href="{% url 'emp:ppbox_form' l.pk %}" class="btn btn-primary">Create Solution</a> {% else %} <button class="btn btn-primary" disabled> Create Solution </button> {% endifequal %} The above are my models and django templates The problem is when the object has solution_req as PPBox it is still showing the disabled button instead of the link -
Django ORM query join unrelated tables on two fields
The problem I'm writing a program where I register treatments performed on patients in various medical places. Each treatment is performed on certain body part and each medical place can define their own way of naming those body parts. My models look like this: class Treatment(Model): medical_place = ForeignKey(to=MedicalPlace, on_delete=PROTECT, related_name='treatments') body_part = CharField(max_length=64, choices=BodyPart.choices(), db_index=True) ... (some other fields) ... class LocalProcedure(ProcedureBase): medical_place = ForeignKey(to=MedicalPlace, on_delete=PROTECT, related_name='procedures') identifier = CharField(verbose_name=_('Procedure number'), max_length=64, blank=False, null=False) description = CharField(verbose_name=_('Procedure description'), max_length=256, blank=True, null=False) body_part = CharField(max_length=64, choices=BodyPart.choices(), blank=False, db_index=True) class Meta: unique_together = (('body_part', 'medical_place', 'identifier'),) I need to retrieve list of "LocalProcedure" objects with annotated: count of related treatments count of related treatments performed up to X days ago (Treatments model has created datetime field I didn't show here) Solutions I have tried so far I can retrieve annotated list of LocalProcedures while using subqueries: related_treatments = Treatment.objects.filter( body_part=OuterRef('body_part'), medical_places=OuterRef('medical_place'), ).values( f'body_part', ) LocalProcedure.objects.annotate( treatments_count = Subquery(related_treatments.annotate(count=Count('pk')).values('count'), treatments_count = Subquery(related_treatments.filter(created__gt=now()).annotate(count=Count('pk')).values('count'), ) but this solution does indeed perform subqueries, whereas joining those two tables (when writing raw query) is much much faster. Any help appreciated. -
Displaying objects from a query inside a loop
I'm just a newbie in python and django, and I'm quite lost on my current issue, this problem somehow not new to some, hoping to get some guidance for me to solve this matter. I performed my first query to get a list of foreign key values and used a loop to pass the individual value and used it as a param to my second query. Technically I did my second query inside the iteration of the loop. Then I used and get the iterated values of my second query and pass it on the self.paginate_queryset in order for me to serialize it and produce the response on my get_paginated_response. As part of observing, I printed all the result of my second query inside the said loop earlier, and it worked properly, but when I tried to run it on postman, I noticed the response only produced one result from my series of results base on the given loop. What exactly do I need to do to produce all the needed results? Here is my function in views.py: def get(self, request, *args, **kwargs): global friend, request_queries self.pagination_class = PageNumberPagination friends = Friend.objects.filter(from_user=request.user.pk) for friend in friends: request_queries = GosamFriendProfile.objects.raw("""SELECT * … -
Related Field got invalid lookup: icontains (views.py)
I am trying to write a search field. It works for some of the module fields. My problem is when I use a ForeignKey field. show error [Related Field got invalid lookup: contains] I'm not sure where I did wrong. my models.py class Home(models.Model): type_home = models.CharField(max_length=255) def __str__(self): return self.type_home class Furniture(models.Model): name = models.CharField(max_length=255) type_home = models.ForeignKey(Home, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name my views.py class HomeListView(ListView): model = Home def get_queryset(self): qs = super().get_queryset() self.query = "".join( c for c in self.request.GET.get("query", "") if c.isalnum() or c.isspace() ).split() if self.query: name_qs = super().get_queryset() type_home_qs = super().get_queryset() for term in self.query: name_qs = name_qs.filter(Q(name__icontains=term)) type_home_qs = type_home_qs.filter( Q(type_home__icontains=term) ) qs = name_qs | type_home_qs return qs help me, please Thanks -
__str__ returned non-string (type Leads)
I am getting the following error and I am not able to figure it out: TypeError: str returned non-string (type Leads) class Pfep(models.Model): client = models.ForeignKey(Leads, on_delete=models.CASCADE, related_name='vendor_owner') receiver = models.CharField(max_length=250, default=0 ,blank=True, null=True) receiver_location = models.CharField(max_length=250, default=0 ,blank=True, null=True) def __str__(self): return self.client class PPboxSol(models.Model): box_length = models.IntegerField(default=0, blank=True, null=True) box_breadth = models.IntegerField(default=0, blank=True, null=True) box_height = models.IntegerField(default=0, blank=True, null=True) created_on = models.DateField(auto_now_add=True) pfep = models.ForeignKey(Pfep, on_delete=models.CASCADE, related_name='pfep_box_sol') created_by = models.ForeignKey("packsapp.Employee", on_delete=models.CASCADE, related_name='ppbox_createdby') Views.py class PpboxsolFormView(CreateView): model = PPboxSol form_class = Ppboxsolform template_name = 'pfep/PpboxsolForm.html' def get_initial(self): initial = super().get_initial() initial['pfep'] = Pfep.objects.get(pk=self.kwargs['pk']) return initial def form_valid (self, form): if self.request.user.employee.employee_role == 'admin': product = form.save(commit=False) product.created_by = Employee.objects.filter(user=self.request.user.id)[0] product.save() messages.success(self.request, 'The PP Box Solution was created with success!') return redirect('emp:ppbox_table') else: messages.success(self.request, "You don't have permission to create Solution!") return redirect('emp:ppbox_table') return redirect('emp:pfep_table') Urls.py path('ppboxsol/add/<int:pk>/', PpboxsolFormView.as_view(), name='ppbox_form'), Do I need to add def __str__(self): to model PPboxSol as well ? -
Djano/Google Sheets API Model/View Question
I'm very new to Python/Django: I've tested the Google Sheets API by itself and it works. Modifying it slightly, I've placed it in my model as follows: from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] # The ID and range of a sample spreadsheet. SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' SAMPLE_RANGE_NAME = 'Class Data!A2:E' def mainLoop(): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('sheets', 'v4', credentials=creds) # Call the Sheets API sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME).execute() values = result.get('values', … -
Implement Push notifications in DRF and ReactJS
I am a beginner so please forgive me if I sound silly. I am trying to make a Rest API using DRF and am using serializers for connecting the models and retrieving the data in ReactJS using the fetch method. I wanted to have the functionality of push notifications, and use the data of the different models in the notifications. Any suggestions?