Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.11 - Attempting to populate models with fake data using Faker
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() ##fake pop script import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t= Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): #get topic for entry top = add_topic #create fake data fake_url = fakegen.url() fake_Date = fakegen.date() fake_name = fakegen.company() # create the new webpage entry webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] # create a fake acess record for taht Webpage acc_rec = AccessRecord.objets.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print('populating script!') populate(20) print('populating complete') Hello, so I am working on a Django course, it is using Django 1.11 as the question mentioned, and while trying to populate my models with fake data using Faker, I am getting some errors coming from the Django packages i believe, below are the command line errors i received, thanks in advanced! enter code here (MyDjangoEnv) D:\Coding Projects\DjangoCourse\first_project>python populate_first_app.py populating script! Traceback (most recent call last): File "populate_first_app.py", line 44, in populate(20) File "populate_first_app.py", line 37, in populate webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\manager.py", l ine 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", lin e 464, in get_or_create return self.get(**lookup), False File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", lin e 371, in get clone = self.filter(*args, … -
Uncaught TypeError: Cannot set property 'innerHTML' of null Django
I know there are many similarly to this question but I can't find a way. I have a table and when I click edit in row table the modal should show and I want to pass data from table to modal and display some data in modal that comes from my table .When the button click it always error and the modal didn't show.I been using Django.Please see the image below. Below is my current code. Can you help me please? Error accounts.html {% extends 'navigation.html' %} {% block content %} <script> function exampleModal(firstName,lastName){ document.getElementById('firstNameValueId').innerHTML = firstName document.getElementById('secondNameValueId').innerHTML = lastName $("#exampleModal").modal('show'); } </script> <!-- mytable --> <div class="tabs-animation"> <div class="card mb-3"> <div class="card-header-tab card-header"> <div class="card-header-title font-size-lg text-capitalize font-weight-normal"><i class="header-icon lnr-laptop-phone mr-3 text-muted opacity-6"> </i>Accounts Information </div> <div class="btn-actions-pane-right actions-icon-btn"> <div class="btn-group dropdown"> <button type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="btn-icon btn-icon-only btn btn-link"> <i class="pe-7s-menu btn-icon-wrapper"></i> </button> <div tabindex="-1" role="menu" aria-hidden="true" class="dropdown-menu-right rm-pointers dropdown-menu-shadow dropdown-menu-hover-link dropdown-menu"> <h6 tabindex="-1" class="dropdown-header">Header</h6> <button type="button" tabindex="0" class="dropdown-item"> <i class="dropdown-icon lnr-inbox"> </i><span>Menus</span> </button> <button type="button" tabindex="0" class="dropdown-item"> <i class="dropdown-icon lnr-file-empty"> </i><span>Settings</span> </button> <button type="button" tabindex="0" class="dropdown-item"> <i class="dropdown-icon lnr-book"> </i><span>Actions</span> </button> <div tabindex="-1" class="dropdown-divider"></div> <div class="p-3 text-right"> <button class="mr-2 btn-shadow btn-sm btn btn-link">View Details</button> <button class="mr-2 … -
Provision product with strip and dj-stripe
I'm using stripe with DRF and on top of that, I've implemented the library dj-stripe. Everything works so far but I'm not really sure how to provision my product now. I do have access to the subscription and customer object for every user but these objects are quite complicated / big. I can't really do something like if user.subscription -> do this since the subscription could be e. g. deleted, inactive. I also need a more granular solution since I need to apply limits like: if subscription.plan.product === "Entry Plan": # allow user to only create 5 instances I can't really find information on how to do this elegantly and consistently for an entire app. -
How to add a number range of items per page in custom pagination django rest framework
I have created some serialized data using django rest framework. I am in the process of building a custom pagination, since there is a lot of data that is being serialized. I have managed to add the required key, value pair needed in the custom pagination. The page_size is set to 200. So it currently displays like this : { "totalPages": 11, "totalData": 2065, "currentPage": 2, "nextPage": "http://localhost:8000/cluster/37/tasks?page=3", "previousPage": "http://localhost:8000/cluster/37/tasks", "results": [...] } I want to also display additional data in the custom pagination, I want to display the range of the starting data (firstDataNumber) and the final data (lastDataNumber) in the page. For example in page 1 : { "totalPages": 11, "totalData": 2065, "currentPage": 1, "firstDataNumber" : 1, #first data on page "lastDataNumber" : 200, #last data on page ... } same for page 2, which should be : { "totalPages": 11, "totalData": 2065, "currentPage": 2, "firstDataNumber" : 201, #first data on page "lastDataNumber" : 400, #last data on page ... } How do I achieve this insertion of a range of data number in the custom pagination? Thanks. This is my code on custom pagination so far : class LargeResultsSetPagination(PageNumberPagination): page_size = 200 page_size_query_param = 'page_size' max_page_size = … -
Django TextField does not enforce blank=False
I can't get django.db.models.TextField(blank=False) to enforce non-blank. It seems to ignore the constraint and only enforces not-null. Example: import django.core.exception import django.db.models import unittest class Mymodel(django.db.models.Model): id = django.db.models.AutoField(primary_key=True) text = django.db.models.TextField(blank=False) with self.assertRaises(django.core.exception.ValidationError): Mymodel.objects.create() # <--- should raise validation exception The above code creates a new Mymodel instance with the text field set to a blank string, but instead it should raise a ValidationError -
How do you pass data like this (Shown in the question body) as form data in postman for django rest framework api?
Hey guys I have data like this to be passed on to the form-data in postman or insomnia, but the problem is I am getting this error all the time if I use form-data to send. { "product_variation": [ "This field is required." ] } This is the data I am sending. "product_variation": [ { "size-colour": "1", "size_name": "small", "colour_name": "Green", "price": "100", }, { "size-colour": "2", "size_name": "medium", "colour_name": "Blue", "price": "100", } ] Also, I am not able to send images if I try to send the data as raw json data. Can anyone tell me how to properly send this? Thanks -
How to change default empty representative in forms CharField?
I use an unbound form with BooleanField and CharField None are required but when empty, value in database is a representative empty string for Charfield and 0 for BooleanField I would like NULL value instead but don't find how to set this. class CreateForm(forms.Form): def __init__(self, request, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) self.fields["field1"] = forms.BooleanField(label = "", required = False, initial=None) self.fields["field2"] = forms.CharField(label = "", required = False, initial=None) -
I created an extra table extra table in one to one relation with User table. how to show phone field in User registration
I am trying to create a simple API to get a user register. I am using the default User table for authentication purpose, created another table called "phone" with one to one relation with User. I am trying to add "phone" field just above the password. (I hope the image attached is visible). ** Serializer.py class UserRegisterSerializer(serializers.ModelSerializer): class Meta: model = UserDetailsModel fields = ('phone', 'user') class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=68, min_length=6, write_only=True) class Meta: model = User fields = ('username','first_name', 'last_name','email','password') read_only_fields = ('id',) ** models.py<< ** class UserDetailsModel(models.Model): phone = models.IntegerField() balance = models.DecimalField(max_digits=10, decimal_places=2, default=0) user = models.OneToOneField(get_user_model(),primary_key='email' , on_delete=models.CASCADE) def __str__(self): return str(self.user) ** views.py ** class RegisterView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data return Response(user_data,status=status.HTTP_201_CREATED) class DetailsRegisterView(generics.GenericAPIView): serializer_class = UserRegisterSerializer def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data return Response(user_data,status=status.HTTP_201_CREATED) ** urls ** urlpatterns = [ path('',RegisterView.as_view()), path('details', DetailsRegisterView.as_view()) ] ** -
Post.get in django and html form method
what will be form method in html if i use post.get[] . I tried post and get but it gave me 'method' object is not subscriptable error . -
Docker build getting errors after I tried to install pip install -r requirements.txt file
This is the error I get after I installed RUN pip install -r requirements.txt RROR: Service 'web' failed to build: The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 ➜ django-docker pip install psycopg2 Defaulting to user installation because normal site-packages is not writeable Collecting psycopg2 Using cached psycopg2-2.8.6.tar.gz (383 kB) ERROR: Command errored out with exit status 1: command: /usr/bin/python3.6 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-7xuxd9cm/psycopg2/setup.py'"'"'; file='"'"'/tmp/pip-install-7xuxd9cm/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-uon18vv4 cwd: /tmp/pip-install-7xuxd9cm/psycopg2/ Complete output (23 lines): running egg_info creating /tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info writing /tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
How to copy information from a table in one project to another project in Django sqlite
I have to projects. They have different Databases. But one table - Brands - is the same. I need to add new brands from one project to another. What is the best way to do it. I tried to do it with the help of dumpdata and load data. But it doesn't work for me. maybe I was doing something wrong. The dumpdata worked well. I've got the json with all the data. But I cannot add this data to my existing table in another database. I solved this problem by parsing json. But I have more tables to copy. And I think there must be a better solution for this. Can someone help with this? -
AttributeError: 'NoneType' object has no attribute 'history_change_reason'
I am saving change history on every change in django model by using django-simple-history. that what I tried: class MyModel(models.models): field1 = .. ... history = HistoricalRecords( history_change_reason_field=models.TextField(null=True) ) name = 'xyz' for doc_id, status in my_data: reporting , _ = Reporting.objects.get_or_create( doc_id=doc_id, user=self.request.user ) reporting.is_accepted = status reporting.save( update_fields=['is_accepted] ) update_change_reason( instance=reporting, reason=f'Change request done by {name}' ) and I got below error. AttributeError: 'NoneType' object has no attribute 'history_change_reason' -
can someone explain me this django views part
def download(request , path): file_path = os.path.join(settings.MEDIA_ROOT , path) if os.path.exists(file_path): with open(file_path , 'rb') as file: response = hr(file.read(),content_type="application/admin_upload") response['Content-Disposition'] = 'inline;filename='+os.path.basename(file_path) return response raise Http404 i saw one on how to upload a img by the admin and the code works fine but i dont understand this part :/ -
How to login as an existing user in django shell
In django shell, I want to debug a specific api call, and for the resource to work, one should be logged in. from django.test import Client from urllib.parse import urlsplit, parse_qsl client = Client() client.login(username='my_username', password='my_password') # I also tried client.force_login() without success url_data = urlsplit(url) r = client.get(path=url_data.path, data=parse_qsl(url_data.query)) # r is <HttpUnauthorized status_code=401, "text/html; charset=utf-8"> How do I login properly? -
repeat watermark only once per page when printing the html page
I'm using pdfkit with Django to convert a html template into pdf. The template is 3 page long when printed and I need to display a "Cancelled" watermark on each page of the document when printed. Currently, it only gets printed once in the first page, but i need it to be printed at the center of the page, once on all the pages <style> #watermark { display:block; z-index: 99999; width: 86%; position:fixed; } #watermark img { opacity: 0.2; filter: alpha(opacity=15); } </style> <div id="watermark"> <img src="/media/images/policy_cancel.png" style=" width: 650px; height: 414px;"> </div> -
My models do not display in production template Django/nginx/postgre
I have a little issue I am unable to resolve. Live website doesnt display the faq template as it would be if my index.html doesnt recieve anything in the context. In localhost it displays everything properly and shows models in admins. In production it has all the models in admin, but doesnt display anything. (The only difference between local and production-I dont use postgre, instead using sqlite)...But again I can CRUD models on live server through python manage.py shell or www.website.com/admin panel. Any suggestions? For extra code look source code at https://github.com/Eakz/engyschool My index.html <div id="faq"> {% for i in faqsdown %} <div class="question down"> <div class="dropdown"> {% if i.question|length > 28 %} <div class="trigger" style="font-style: italic;">{{i.question|slice:":28"|add:"..."}}</div> <div class="content"> <p style="font-style: italic;">{{i.question|slice:"28:"}}</p> <hr> {{i.answer}} </div> {% else %} <div class="trigger">{{i.question}}</div> <div class="content"> <hr> {{i.answer}} </div> {% endif %} </div> </div> {% endfor %} {% for i in faqsup %} <div class="question up"> <div class="dropdown"> {% if i.question|length > 28 %} <div class="trigger" style="font-style: italic;">{{i.question|slice:":28"|add:"..."}}</div> <div class="content"> <p style="font-style: italic;">{{i.question|slice:"28:"}}</p> <hr> {{i.answer}} </div> {% else %} <div class="trigger">{{i.question}}</div> <div class="content"> <hr> {{i.answer}} </div> {% endif %} </div> views.py import os from django.conf import settings from django.shortcuts import render from django.templatetags.static import … -
Django RelatedObjectDoesNotExist error related in foreign key
my model : class Problem(models.Model): ... prob_id = models.IntegerField(null=False, unique=True) #autofield?, (unique=True) ... def __str__(self): return str(self.prob_id) def prob_path(instance, filename): return 'upload/{0}/{1}'.format(instance.problem, filename) class Testcase(models.Model): problem = models.ForeignKey(Problem, on_delete=models.CASCADE) input_data = models.FileField(upload_to=prob_path) output_data = models.FileField(upload_to=prob_path) def __str__(self): return str(self.problem) views.py : def problem_write_foruser(request): if request.method == "GET": form = ProblemForm() form_t = TestcaseForm() if request.method == "POST": form = ProblemForm(request.POST) form_t = TestcaseForm(request.POST, request.FILES) if form.is_valid(): user = CustomUser.objects.get(username = request.user.get_username()) new_problem = Problem( ... prob_id = form.cleaned_data['prob_id'], ... ) new_problem.save() if form_t.is_valid(): form_t.problem = new_problem form_t.input_data = Testcase(input_data = request.FILES['input_data']) form_t.output_data = Testcase(output_data = request.FILES['output_data']) form_t.save() return redirect('koj:problemset') context = {'form':form, 'form_t':form_t} return render(request, 'koj/problem_write_foruser.html',context) forms.py class ProblemForm(forms.ModelForm): ... prob_id = forms.IntegerField() ... class Meta: model = Problem fields = ['prob_id', 'title', 'body', 'input', 'output', 'time_limit', 'memory_limit'] class TestcaseForm(forms.ModelForm): input_data = forms.FileField() output_data = forms.FileField() class Meta: model = Testcase fields = ['input_data', 'output_data'] when i submit this form in website, RelatedObjectDoesNotExist error is occured i think 'form_t.problem = new_problem' in views.py and relation of Problem model and Testcase model Testcase has no problem. Request Method: POST Request URL: http://127.0.0.1:8000/problem_write_foruser/ Django Version: 3.0.8 Exception Type: RelatedObjectDoesNotExist Exception Value: Testcase has no problem. Exception Location: /home/dsyun/grad/venvs/mysite/lib/python3.6/site- packages/django/db/models/fields/related_descriptors.py in get, line … -
How to upload Multiple images using Django Rest Framework using foreign key?
i can not upload multiple image using Django rest framework.i have Searched this and i Found that using ForeignKey we can upload multiple images.for that We have to make two models.But i dont know how to use Foreign key for multiple image upload.i have tried many Code but did not Worked.can any one help me with this Issue? i have following code, In My models.py class UserModel(models.Model): username= models.CharField(max_length=255) user_images= models.ImageField(upload_to='images/') In My Forms.py from django import forms from user_register.models import UserModel #user_register is my app name class UserForm(forms.ModelForm): class Meta: model = UserModel fields = "__all__" My serializers.py is from user_register.models import UserModel #user_register is my app name from rest_framework import serializers class userSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = "__all__" And This is My views.py @api_view(['POST','GET']) def userfunction(request): if request.method=='POST': form = UserForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponse('Data Inserted') else: return HttpResponse('form is invalid') i Want my all images to be saved in 'images' folder.Can any one help me with this Issue? i would appreciate if anyone can help me. -
Creating React-Django project
I have confusion on creating react django project.I found two type of approaches of creating react-django project. First creating django project and the integrate react on it.(using npm run build) Creating react project and django project seprately Which approach is best?and which to use when? -
I am unable to install Django in my machine, It is showing error and I don't know what exactly I am doing wrong
Hello I tried installing Django in my laptop, but due to some reason it is not installing properly. i don't know what to do please help me. I have Python 3.8.5 installed in my computer, and I am using Windows 10 operating system. I tried installing django using pip install django It is giving me this error C:\Users\DELL>pip install django Collecting django Downloading Django-3.1.1-py3-none-any.whl (7.8 MB) |▌ | 143 kB 8.0 kB/s eta 0:16:01ERROR: Exception: Traceback (most recent call last): File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_vendor\urllib3\response.py", line 437, in _error_catcher yield File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_vendor\urllib3\response.py", line 519, in read data = self._fp.read(amt) if not fp_closed else b"" File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 62, in read data = self.__fp.read(amt) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\http\client.py", line 458, in read n = self.readinto(b) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\http\client.py", line 502, in readinto n = self.fp.readinto(b) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\ssl.py", line 1241, in recv_into return self.read(nbytes, buffer) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\ssl.py", line 1099, in read return self._sslobj.read(len, buffer) socket.timeout: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_internal\cli\base_command.py", line 228, in _main status = self.run(options, args) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_internal\cli\req_command.py", line 182, in wrapper return func(self, options, args) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_internal\commands\install.py", line 323, in run … -
KeyError at /api/stores/product/create/ 'product_variation' in Postman while testing Django rest framework api
Hey guys i am getting this KeyError at /api/stores/product/create/ 'product_variation' in Postman while testing Django rest framework api. What has gone wrong with my code? Please do help. serializer class ProductCreateSerializer(serializers.ModelSerializer): images = serializers.ListField(child=serializers.ImageField()) #limit the number of images to 5 product_variation = ProductVariationSerializer(many=True, required=False) def create(self, validated_data): image = self.context['request'].FILES.get('image') images = self.context['request'].FILES.getlist('images') images_data = validated_data.pop('images') variations_data = validated_data.pop('product_variation') product = Product.objects.create(user= self.context['request'].user, **validated_data) for image in images_data: ProductImage.objects.create(product=product, **image) for variation in variations_data: ProductVariation.objects.create(product=product, **variation) return product views class ProductCreateAPI(generics.CreateAPIView): serializer_class = ProductCreateSerializer permission_classes = [IsAuthenticated] authentication_classes = (TokenAuthentication,) def create(self, request, *args, **kwargs): serializer = ProductCreateSerializer(data=request.data, context={'request':request,}) if serializer.is_valid(): serializer.save() return Response({'response':'Product listed successfully.'}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is how I give in postman, the product_variation as key and [{ "size-colour": "1", "size_name": "small", "colour_name": "Green", "price": "100", }, { "size-colour": "2", "size_name": "medium", "colour_name": "Blue", "price": "100", }] and this as the value, but still it shows the error. What can be the reason? Thanks -
How to launch this command mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql on Xampp Ubuntu
Hello i'm writing a website in django but I've this error: *Database returned an invalid datetime value. Are time zone definitions for your database installed?* People say that to solve this, i want to run this code: mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql The problem is that, I can't run this command because I'm using MySql from Xampp. How can I launch this command using Xampp's MySql? -
How do I create a custom view that doesn't depend on a model in the Django admin site?
Is it possible to have the Django admin site have a link to a custom view that isn't actually a model alongside the models? That custom view will have an add functionality that adds to every model in my existing database. -
Python Django: Filled in form field always throws error "This field is required" on POST
I have a form where I just included one textbox and a submit button. Everytime when I fill in the textbox and try to submit the form validation fails and the error message "This field is required" gets thrown. add_stock.html {% extends 'base.html' %} {% block content %} <h1>Add Stock</h1> <form action="{% url 'add_stock' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input class="form-control" type="text" id="ticker"> <button type="submit" class="btn btn-primary">Add</button> </form> {{ form.errors }} {% endblock %} views.py def add_stock(request): if request.method == 'POST': form = StockForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, ('Stock has been added')) return redirect('overview') return render(request, 'add_stock.html', {'form':form}) return render(request, 'add_stock.html', {}) models.py from django.db import models class Stock(models.Model): ticker = models.CharField(max_length=10) #trade_date = models.DateField(blank=True, default='') #quantity = models.IntegerField(blank=True, default='') #unit_price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, default='') #brokerage = models.DecimalField(max_digits=3, decimal_places=2, blank=True, default='') def __str__(self): return self.ticker forms.py from django import forms from .models import Stock class StockForm(forms.ModelForm): class Meta: model = Stock fields = ["ticker"] #fields = ["ticker", "trade_date", "quantity", "unit_price", "brokerage"] Error message -
How to fetch Google Meet participants using Google Api - Python
Hey we are creating Google Meet links using Calendar Api. No we have requirement to fetch participants in a meeting. We are able to see the participants from Gsuite Audit Report. We tried using Admin SDK Reports API. But we have getting Access denied googleapiclient.errors.HttpError: <HttpError 401 when requesting https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet?alt=json&maxResults=10 returned "Access denied. You are not authorized to read activity records."> SCOPES = ['https://www.googleapis.com/auth/admin.reports.audit.readonly'] def main(): creds = ServiceAccountCredentials.from_json_keyfile_name('srv.json', scopes=SCOPES) service = build('admin', 'reports_v1', credentials=creds) results = service.activities().list(userKey='all', applicationName='meet', maxResults=10).execute() print(results) We are using python (Django)