Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framewrok: got KeyError when write test for creating (post) nested serializer
I'm try to write test for creating sales data keep getting KeyError: 'content' when running python manage.py test. the test is to ensure user can add/create sales data with its details (nested) with this as reference to create writeable nested serializers models.py # abstract base table for transactions class Base_transaction(models.Model): is_paid_off = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) pass class Meta: abstract = True # sales table to store surface level sales information # consist of sales_id as pk, customer_name, sub_total, discount, user_id, # total, is_paid_off, created_at, updated_at class Sales(Base_transaction): sales_id = models.BigAutoField( primary_key=True, unique=True ) customer_name = models.CharField(max_length=25, blank=True) customer_contact = models.CharField(max_length=13, blank=True) user_id = models.ForeignKey( User, on_delete=models.PROTECT, null=True, db_column='user_id' ) def __str__(self) -> str: return f'{self.sales_id} at {self.created_at} | Lunas={self.is_paid_off}' class Meta: db_table = 'sales' # sales_detail table store the detail of sales per sparepart # consist of sales_detail_id as pk, quantity, individual_price, total_price # sales_id class Sales_detail(models.Model): sales_detail_id = models.BigAutoField( primary_key=True, unique=True ) quantity = models.PositiveSmallIntegerField() is_grosir = models.BooleanField(default=False) sales_id = models.ForeignKey( Sales, on_delete=models.CASCADE, db_column='sales_id' ) sparepart_id = models.ForeignKey( 'Sparepart', on_delete=models.SET_NULL, null=True, db_column='supplier_id' ) def __str__(self) -> str: return f'{self.sales_id} - {self.sparepart_id}' serializers.py class SalesDetailSerializers(serializers.ModelSerializer): sparepart = serializers.ReadOnlyField(source='sparepart_id.name') class Meta: model = Sales_detail fields = ['sales_detail_id', … -
Can't send a post requests
Hi everyone, I'm trying to send a post request through my localhost, my data is a json object, and my following code is: result = df_yahoo.get_history_data() df_yahoo_json = result.to_json() # Convert the Dataframe to JSON headers = { "Content-Type": "application/json", } # Send the POST request with the JSON data response = requests.post('https://localhost:8000/api_yahoo', json=df_yahoo_json, headers=headers) I try to send the request, and then I got the following error: requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) I send the request through the views file in Django. After converting the Dataframe to JSON, I see that the Type of df_yahoo_json is str and not dict of JSON. I would appreciate your help, thank you. -
Django multiple sites using nginx and gunicorn
I am serving multiple websites using nginx and gunicorn and I would like to add another one. Sadly my lack of experience is limiting me, I have some experience with webdesign but always struggle on the server side...|-( (I am using Django because of my Python preference in scientific analysis). My problem: The new site seems to refer to the port used by another. Checking the gunicorn status I see that the site is running although nginx seems to be unable to refer to the correct Django folder. Could someone point me in the right direction? I have been looking around for the last hour or so... (I didn't include any code for now as I am not sure where the error might lie at this point...) -
Filter over jsonfiled with unknown keys in Django ORM
There is a model with JSONfield in Django model: class MyClass(models.Model): is_info = models.BooleanField() info = models.JSONField() The data inside table is like: is_info info false true {'key123':{'a':'1', 'b':'2', 'search_key':'text'},'key456':{'a':'1', 'b':'2', 'search_key':'another_value'}} And I need to filter somehow a query set to receive a set of rows where compound key 'search_key'='text' and not include in result values from 'info' field where 'search_key' has some other values. My keys of 'info' field (key123, key456 and etc.) are always different and I don't know the exact value. Please, help me!!!) I've tried: q = queryset.filter(info__icontains='text') but it return for me all the field info: {'key123':{'a':'1', 'b':'2', 'search_key':'text'},'key456':{'a':'1', 'b':'2', 'search_key':'another_value'}} when I need to receive only: {'key123':{'a':'1', 'b':'2', 'search_key':'text'}} -
How to use objects.filter for (one-to-many) releation
I have 3 tables: Job, Flight, and Image One job can have multiple flights and a flight can have only one job. And a flight can have many images. I get all flights related to the job using the query: flights = Flight.objects.filter(job_id=job_id) and now I want all images in those flights to call a function for all images but I couldn't implement it without a loop: for flight in flights: images = Image.objects.filter(flight=flight) data = process_images(images) I want something like: images = Image.objects.filter(flight=flights) so I call process_images only once, is that possible? -
Not able to retrieve variable in template in Django ajax call
I am trying retrieve counter value passed from view in the html template .It is coming as None, however in the view print and in ajax success log value it is coming correct. JS ajax func $(".pos").click(function(){ counter=counter+1; $(".add").html('add counter '+counter); $.ajax( { url :'page', type :'get' , data:{ quantity: counter }, success:function(response){ console.log(response); } } ); My view def page(request): counter=request.GET.get('quantity') print(counter) ## this is printing fine return render(request,'page.html',{'counter':counter}) html template <body> {{counter}} <button class="btn neg" name="neg-btn">-</button> <button class="btn add" name="add-btn" >add to box</button> <button class="btn pos" id="test" name="pos-btn">+</button> </body> getting this counter as None -
FileNotFoundError at / [Errno 2] No such file or directory while saving an image
I want to create a qr-code generator for hashed values. However, it works pretty strange, because sometimes everything works good, but sometimes it gives me an error: FileNotFoundError at / [Errno 2] No such file or directory. For example, it can save a few qr-codes and then throw that error. Here is the code: def qr_creator(request): for i in range(50): hash_uuid = uuid.uuid4 hash = Hasher.encode(self=Hasher(), password=hash_uuid, salt=Hasher.salt(self=Hasher())) data = f"{hash}" img = make(data) img_name = f"{hash}.png" img.save(str(settings.MEDIA_ROOT) + '/qr_codes/' + img_name) return HttpResponse("Done!") As I understand, the problem lies in img_name as if I change it for example, like this: img_name = f"{hash}.png", everything works as it should be. But I need my qr-codes to be named strictly as hash values. So my question is how can I fix this so I can save my qr-codes with its values? Thanks in advance -
Get serializer data by foreign key
I need to pass data from EmployeeSerializer to VacationSerializer as nested json. This is my serializer.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'first_name', 'surname', 'patronymic', 'birthday', 'email', 'position', 'phone_number') class VacationSerializer(serializers.ModelSerializer): class Meta: model = Vacation fields = ('pk', 'start_date', 'end_date', 'employee_id', 'employee') and my models.py: class Employee(models.Model): first_name = models.CharField("Name", max_length=50) surname = models.CharField("surname", max_length=50) patronymic = models.CharField("patronymic", max_length=50) birthday = models.DateField() email = models.EmailField() position = models.CharField("position", max_length=128) phone_number = models.CharField("phone", max_length=12, null=True) is_deleted = models.BooleanField(default=False) def __str__(self): return f'{self.surname} {self.first_name} {self.patronymic}' class Vacation(models.Model): start_date = models.DateField() end_date = models.DateField() employee_id = models.ForeignKey(Employee, related_name='employee', on_delete=models.PROTECT, default=-1) def __str__(self): return f'{self.start_date} - {self.end_date}' @property def date_diff(self): return (self.end_date - self.start_date).days in views.py I have this: @api_view(['GET', 'POST']) def vacations_list(request): if request.method == 'GET': data = Vacation.objects.all() serializer = VacationSerializer(data, context={'request': request}, many=True) return Response(serializer.data) I've tried this: class VacationSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(read_only=True, many=True) class Meta: model = Vacation fields = ('pk', 'start_date', 'end_date', 'employee_id', 'employee') but it doesn't show me even empty nested json, it shows me only VacationSerializer data. I easily can access VacationSerializer from EmployeeSerializer using PrimaryKeySerializer or any other serializer and get nested json where VacationSerializer data is nested in EmployeeSerializer data. … -
I am getting error on user login and registration in django
Hi, I have a project with django, database mysql, I'm getting an error in user login and registration process. Could it be from the database, do I need to code it differently because it's mysql? my codes and error message are attached ` `` ` ` def signupPage(request): if request.method == "POST": Formusername = 'username' in request.POST Formemail = 'email' in request.POST Formpassword = 'password' in request.POST Formrepassword = 'repassword' in request.POST if Formpassword == Formrepassword: if User.objects.filter(username=Formusername).exists(): return render(request,"signup.html",{"error":"username already taken","username":Formusername}) else: if User.objects.filter(email=Formemail).exists(): return render(request,"signup.html",{"error":"email already taken","email":Formemail}) else: user = User.objects.create_user(username=Formusername,email=Formemail,password=Formpassword) user.save() return redirect("signin") else: return render(request,"signup.html",{"error":"passwords do not match!"}) return render(request,"signup.html") def signinPage(request): if request.method == "POST": username = 'username' in request.POST password = 'password' in request.POST user = authenticate(request,username = username,password = password) if user is not None: login(request, user) return redirect("home") else: return render(request,"account/signin.html",{"error":"username or password wrong"}) return render(request,"signin.html") def logoutPage(request): return redirect("home") ` < `ValueError at /account/signup The given username must be set Request Method: POST Request URL: http://127.0.0.1:8000/account/signup Django Version: 4.1.3 Exception Type: ValueError Exception Value: The given username must be set Exception Location: C:\Users\merte\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\models.py, line 144, in _create_user Raised during: account.views.signUpUser Python Executable: C:\Users\merte\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.0 Python Path: ['C:\\Users\\merte\\Desktop\\İş-Güç\\Orders\\order', 'C:\\Users\\merte\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\merte\\AppData\\Local\\Programs\\Python\\Python311\\Lib', … -
403 Forbidden media file django, nginx, aws
The images are not displayed in my project. If the static files. This is how my nginx configuration looks server{ listen 80; server_name domain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /var/www/html/static/; } location /media/ { autoindex on; alias /home/user/project/var/www/html/media; } location / { include proxy_params; proxy_pass http://ip:8000; } my settings.py DEBUG = False MEDIA_ROOT ='var/www/html/media' MEDIA_URL = '/media/' the permmission this path: /home/user/project/var/www/html/media drwxrwxr-x 3 www-data www-data I need the images to be displayed to the user or other solutions with other services with aws. -
Django Models Reverse Lookup
I am trying to normalize my models in Django. I have three models as below from django.db import models class Province(models.Model): province = models.CharField(max_length=20, blank=False, null=False) def __str__(self): return province class District(models.Model): district = models.CharField(max_length=20, blank=False, null=False) province = models.ForeignKey('Province', related_name='district_province', on_delete=models.CASCADE) def __str__(self): return district class School(models.Model): school = models.CharField(max_length=20, blank=False, null=False) district = models.ForeignKey('District', related_name='school_district', on_delete=models.CASCADE) def __str__(self): return self.school When I query the school model I can get the District, My question is, is it possible to also get the province without adding it as a foreign key in the School model? if yes, how do I achieve that? The Use cases are: Query a school with all its properties including district and province. With: School.objects.all or School.objects.get/filter I can get all schools and the district details but I do not know how to reach the province model. Get all schools in a District With: School.objects.filter(district=x) I can get schools in a district with no problem here. Get all schools in a Province Say I have province ID as 2, how do I get all schools in province 2? Thanks for any help given. -
I want to upload folder and subfolder with files in Django
HTML CODE <div class="input-group"> <input type="file" id="folder-upload-newtask" onchange="selectFolder(event)" webkitdirectory mozdirectory msdirectory odirectory directory multiple name="folder_name" tabindex="2"/> <label for="folder-upload-newtask">Choose Files</label> </div> Folder MainFolder --- FirstSubfolder -- (1.xlsx, 2.xlsx) SecondSubfolder -- (1.xlsx, 2.xlsx, 3.xlsx) ThirdSubfolder -- (1.xlsx, 2.xlsx, 3.xlsx, 4.xlsx) And inside subfolder excel file name same with different content. so I want to save all data in MEDIA_ROOT with correct format. -
Django forms useless div tag
I am getting one problem while using django forms. Actually When I am using RadioSelect widget it is giving unnecessary div tags. Means each radio button is separated with individual div tag. And I don't want that. Please help Image of Div tags for each label How can I get those label and input tag i.e Radio Buttons in single div tag not these many index.html forms.py -
How to send email on smtp server in django?
here is m settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAL_HOST_USER = 'test.mailed.login@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 Google used to have a less-secure apps settings now that it is removed, I am using this alternatively I obviously went on a google and created a new app and filled it on the EMAIL_HOST_PASSWORD I also enabled two step authentication Obviously i changed my app password on the above code so no one can see it I imported send_mail and run the function but it still sending me this error error details This is exactly what I have done nothing more or nothing less Every youtube video that I check it is working for all of them, Am I missing an earlier step -
Getting valueError : invalid literal for int() with base 10:''
Environment: Request Method: GET Request URL: http://127.0.0.1:8000/store Django Version: 4.1.3 Python Version: 3.10.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\acer\PycharmProjects\Eshop\store\templates\index.html, error at line 40 invalid literal for int() with base 10: '' 30 : <div class="card mx-auto mb-3" id={{product.id}} style="width: 18rem;"> 31 : <img class="card-img-top" src="{{product.image.url}}" alt="Card image cap"> 32 : <div class="card-body"> 33 : <p class="card-title">{{product.name}}</p> 34 : <p class="card-text"><b>{{product.price|currency}}</b></p> 35 : 36 : </div> 37 : 38 : <div class="card-footer p-0 no-gutters"> 39 : 40 : {% if product|is_in_cart:request.session.cart %} 41 : <div class="row no-gutters"> 42 : <form action="/#{{product.id}}" class="col-2 " method="post"> 43 : {% csrf_token %} 44 : <input hidden type="text" name='product' value='{{product.id}}'> 45 : <input hidden type="text" name='remove' value='True'> 46 : <input type="submit" value=" - " class="btn btn-block btn-success border-right"> 47 : </form> 48 : <div class="text-center col btn btn-success">{{product|cart_quantity:request.session.cart}} in Cart</div> 49 : <form action="/#{{product.id}}" class="col-2 " method="post"> 50 : {% csrf_token %} Traceback (most recent call last): File "C:\Users\acer\PycharmProjects\Eshop\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\acer\PycharmProjects\Eshop\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\acer\PycharmProjects\Eshop\store\views\home.py", line 57, in store return render(request, 'index.html', data) File … -
502 bad gateway error with django , gonicorn in ubuntu server
i got these error 502 bad gateway when cheched error.log i got when i checked goicorn the nginex services is run but after check i got this error this is my code in nginx/site-avalable upstream keepalive-upstream { server 127.0.0.1:8000; keepalive 64; } server { listen 80; listen [::]:80; server_name qhse-erp.com www.qhse-erp.com; location / { proxy_http_version 1.1; proxy_set_header Connection ""; proxy_pass http://keepalive-upstream; proxy_redirect off; } } -
Django: objects.raw() resulting query but not records
I'm django newbie, I have one fundamental and one technical questions. I'm using Postgres DB. I used psycopg2 connection/cursor for fetching the data, there was some delay while establishing a connection. I read that, ORM takes care of low level activities such as establishing a connection, etc. If I use django, ORM will takes care of connection challenge ? 1.1. Can I expect same (low level activities) with raw() as well? objects.raw(sql) returning Query but not records from the table. I defined Student Model as below class Student(models.Model): firstname = models.CharField(max_length=100) surname = models.CharField(max_length=100) def __str__(self): return self.firstname While creating the view, def studentList(request): #posts = Student.objects.all() --> 1. working as expected (fetching all records firstname) cursor = connection.cursor() sql = "select * from api_student" cursor.execute(sql) posts = cursor.fetchone() --> 2. returning entire record #posts = Student.objects.raw(sql) --> 3. RETURNING SQL QUERY NOT RECORD FROM TABLE ??? print(posts) return render(request, 'output.html', {'posts':posts}) output: <QuerySet [<Student: Anil>]> <RawQuerySet: select * from api_student> --> this is the challenge, did I miss any ('Anil', 'kumar') -
Chart.js automatic background color selector on Django app
I'm working on a Django app with chart.js charts and I'm trying to use a function to automatically change the colors of all the labels. Although when I run the app it only colors one label and makes the other transparent. I tried changing it from labels to data and was getting the same result. It's difficult to share the code as it is pulling data from the app so I'll share what I can. Here is the random color generator code: const labels = ['Category Types']; const backgroundcolor = []; const bordercolor = []; for (i = 0; i < labels.length; i++) { const r = Math.floor(Math.random() * 255); const g = Math.floor(Math.random() * 255); const b = Math.floor(Math.random() * 255); backgroundcolor.push("rgba(" + r + ", " + g + ", " + b + ", 1)"); bordercolor.push("rgba(" + r + ", " + g + ", " + b + ", 1)"); } Here is the chart code: var categoryTypes = JSON.parse(document.getElementById('category_types').textContent) var transactionAmountSum = JSON.parse(document.getElementById('transactionAmountSum').textContent) console.log('categoryTypes', categoryTypes) console.log('transactionAmountSum', transactionAmountSum) $(document).ready(function() { var ctx = document.getElementById('myChart1').getContext('2d'); var myCategory = new Chart(ctx, { type: 'pie', data: { labels: categoryTypes, datasets: [{ label: 'Category Types', data: transactionAmountSum, backgroundColor: [backgroundcolor], borderColor: … -
Download TikTok mp4 on client-side in Django App
I am working on an app and want to download a TikTok video given a URL on the client's machine. I have tried the following to no avail. I would like to do this in as lightweight a manner as possible and with libraries that are popular and maintained, if possible. The issues I have gotten for the attempts are provided therein. Using https://github.com/davidteather/TikTok-Api While this works locally, it does not work when I deploy the application, as I get issues with the threading. I copied over the code from this library and messed around with the threading, but it still did not work fully. I would like to avoid this option as it is not super maintainable. Using requests/wget I get the following issue when trying to use wget: Error downloading video: 'ascii' codec can't decode byte 0xe2 in position 248: ordinal not in range(128) [11/Dec/2022 05:10:13] "GET /downloader/https://www.tiktok.com/@patrickzeinali/video/7143758925349784874?is_copy_url=1&is_from_webapp=v1&item_id=7143758925349784874&lang=en HTTP/1.1" 200 24 This is what the current files look like: downloader/urls.py from django.urls import re_path, path from . import views urlpatterns = [ path('<path:video_url>', views.download_video, name='download_video'), ]` downloader/views.py from django.http import HttpResponse import ENV_VARS import requests import wget def download_video(request, video_url): print(f'Received request for video at URL: {video_url}') # … -
getting Keyerror on updating nested serializer in DRF
I have two serializer AccountSerializer UserProfileSerializer. user in UserProfileSerializer is Foreingkey to AccountSerializer. When I try to update UserProfileSerializer I get key error confirm_password. That is actually validation in AccountSerializer. How to prevent this. #Serializer class AccountSerializer(ModelSerializer): confirm_password = CharField(write_only=True) class Meta: model = Account fields = ["first_name", "last_name", "email", "password", "confirm_password"] extra_kwargs = { "password": {"write_only": True}, } def validate(self, data): if data['password'] != data.pop("confirm_password"): raise ValidationError({"error": "Passwords donot match"}) return data def create(self, validated_data): user = Account.objects.create_user(**validated_data) return user class UserprofileSerializer(ModelSerializer): user = AccountSerializer() class Meta: model = UserProfile fields = "__all__" def update(self, instance, validated_data): user_data = validated_data.pop('user', None) print('user_data', user_data) account = instance.user account.first_name = user_data.get('first_name', account.first_name) account.last_name = user_data.get('last_name', account.last_name) account.email = user_data.get('email', account.email) account.save() return super().update(instance, validated_data) #Error -
How to declare type for related object in django
In views.py I am creating products based on queryset and I don't know how to assign type to wz_product to get hints of appropriate variables. product_qs: List[Product] = product.orderproduct_set.all() for product in product_qs: product_serializer = ProductModelSerializer( data={"og_product": product.wz_product.og_product.id}) In VSC it looks like this: (in the question, I changed the names of the variables to make it easier to understand) -
Django Channels await database_to_async method not working
I'm trying to build a notification application by using Django Channels. The problem I'm having is the following error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. consumers.py class NotificationConsumer(AsyncJsonWebsocketConsumer): @database_sync_to_async def get_notifications(self, user): new_messages = NotificationSerializer(Notification.objects.filter(content=1, users_notified__in=[user]), many=True) notifs = { "new_messages": new_messages } return notifs async def connect(self): user = self.scope["user"] if user: self.channel_name = user.username self.room_group_name = 'notification_%s' % self.channel_name # Error happens in the following line notification = await self.get_notifications(self.scope["user"]) print("Notification", notification) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.disconnect(401) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def notify(self, event): await self.send_json(event["content"]) I have used the exact same approach when I developed a Django Channels chat application that saves messages to the database as well. When trying to convert my approach to the Notification system, it doesn't anymore. As soon as I don't await the self.get_notifications method anymore, it works but I only get back a <coroutine object SyncToAsync.__call__ at ...> -
Password field does not migrate to db
I have my user app with the following fields in its models.py file: from django.db import models from django import forms # Create your models here. class User (models.Model): name=models.CharField(max_length=50, verbose_name='Name') surname=models.CharField(max_length=50, verbose_name='Surname') username=models.CharField(max_length=50, unique=True, verbose_name='Username') password=forms.CharField(widget=forms.PasswordInput()) email=models.EmailField(unique=True, verbose_name='Email') When I do the migrations with python manage.py makemigrations does not migrate the password field, am I defining it wrong with form.CharField? -
Django - Get specific columns with get_object_or_404()
Is there a way to only get specific columns from the database using the get_object_or_404()? This is my query for getting the thesis information from my database. But I only want to return the title , author, and published date instead of all the columns from that specific thesis. details = get_object_or_404(thesisDB, slug=slug, published_status='Approved') -
scheduler library is not working with function-based view in django
`I am working on functional based view in django and I want to schedule a task for every few minutes. I am scheduling task using "schedule" library [pip install schedule]. when i am executing the task i am getting an error as : TypeError: home() missing 1 required positional argument: 'request'. If i try to pass some string in request parameter I get error as : AttributeError: 'bool' object has no attribute 'META' what shall i pass in "request" parameter ?` from django.shortcuts import render import requests import json import schedule import time def home(request): print("Scheduler working") res = requests.get("https://jsonplaceholder.typicode.com/posts").json() return render(request, "home.html", {'res':res}) schedule.every(5).seconds.do(home) #TypeError: home() missing 1 required positional argument: 'request' #schedule.every(5).seconds.do(home(request=True) #AttributeError: 'bool' object has no attribute 'META' (if try to pass some parameter such as string or bool or int) while True: schedule.run_pending() time.sleep(1)