Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to get the user's id on the url path or in the address of the page
i have a url on my page that is "http://127.0.0.1:8000/affiliation/link/10006/". In the above url I want to add the user id along so that it looks like :"http://127.0.0.1:8000/affiliation/link/01/10006/" something like this, whereas '01' is the user id of the user who uploaded the product. Below are the files. views: #Display individual product and render short links for all using pyshorteners def link_view(request, uid): results = AffProduct.objects.get(uid=uid) slink = "http://127.0.0.1:8000/" + request.get_full_path() shortener = pyshorteners.Shortener() short_link = shortener.tinyurl.short(slink) return render(request, 'link.html', {"results": results, "short_link": short_link}) models: #Product details uploaded class AffProduct(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='foo') product_title = models.CharField(max_length=255) uid = models.IntegerField(primary_key=True) specification = models.CharField(max_length=255) sale_price = models.IntegerField() discount = models.IntegerField() img1 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") img2 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") promote_method = models.TextChoices terms_conditions = models.CharField(max_length=255, null=True) promote_method = models.CharField( max_length=20, choices=promote_choices, default='PPC' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) urls: urlpatterns = [ path('link/<int:uid>/', views.link_view, name='link_view') ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to redirect to another page in vanilla JavaScript on submitting HTML form with Django backend?
I have just started working on Django. What I need is to link a js file to my HTML file with a form and save form data. Then go to next screen, click a picture and POST the form data along with the picture. I have linked the JS file. I have created an input type button instead of submit as I wanted to use JS. My use case is of register and login. The first page to open is login then on clicking signup button I am taken to register page where I want the functionality that after user fills form and submits he is taken to face capture page. I am not able to redirect to capture face page from JavaScript. I am using Vanilla JS. When I am using window.location.href = "camera_capture.html" all I am getting is a url appended to the current url and no change in the current page. Something like register/capture_face.html Is there a way I can do what I am trying to achieve and is it a good method to do it like this? or is there a better way I can do it? -
REST API for Django User Authentication and Private Profile View
I'm new with django and react so basically I've been working with django viewsets, which have been of great help as they provide a simple api to communicate b/w django and react, what i now want is to create a register a user. after user logins I then want to present a few details to fill which only that user will be able to view after filling the form. But all I've been able to find on the internet is info with django forms, I don't want to use django forms. I'm using simple models, serializers and models, viewsets. Login/signup form(react) -> after filling form -> react transfers data to django -> django authenticates -> returns authenticated data or error -> react shows authenticated data and option to update info something like this -
How to save a list of dictionaries as each object in a Django database model's field?
I got this dictionary sample_dict = [ {'sale_id': 14, 'name': 'Macarena', 'fecha': datetime.date(2021, 3, 11), 'debe': 500.0}, {'sale_id': 14, 'name': 'Macarena', 'fecha': datetime.date(2021, 4, 11), 'debe': 500.0}, {'sale_id': 15, 'name': 'Yamila', 'fecha': datetime.date(2021, 4, 14), 'debe': 2000.0} ] And I would like to store it in the Django DataBase (SQLite3) like this: BUT before append this dict to the DB I would like to clear the Database and avoid duplicated values (or remove duplicates after append the dict to the db) And when I remove duplicates, I should remove duplicates from the "sale_id", "name", "fecha" and "debe" columns, not only from "sale_id" because I got many "sale_id" with the same number but with different dates ("fecha"). I've tried this but every time I run the "objects.create" I got duplicated values in the DB: class Creditos1(models.Model): sale_id = models.IntegerField(default=0) name = models.CharField(max_length=150) fecha = models.DateTimeField(default=datetime.now) debe = models.IntegerField(default=0) for i in range(0,len(h)): Creditos1.objects.create(name=h[i]['name'], sale_id=h[i]['sale_id'], fecha=h[i]['fecha'], debe=h[i]['debe']) Thanks a lot! -
django image src is not working , I send the image location using django context object
Here is my code: views.py: def adminlogin(request): return render(request,'hospital/login.html',context={ "usertype":"Admin", "image":"images/admin.png" }) HTML code: <div class="image"> images/admin.png <img src="{%static '{{image}}' %}" alt=""> </div> HTML output: <div class="image"> images/admin.png <img src="/static/%7B%7B%20image%20%7D%7D" alt=""> </div> image src doesn't work. How to solve this problem? Regards. -
The information is not stored in the database. Django
There is code in models.py: class Product(models.Model): name = models.CharField(max_length=255) state = models.CharField(max_length=255) b_info = models.CharField(max_length=255) def save(self, *arg, **kwarg): r = requests.get(f'https://system-one.uno/api/cli/bln_check/?card={self.name[:6]}') if r.status_code == 200: _r = r.json() self.b_info = _r.get('reason') in it, part of the number is separated and sent to the checker(connected via API), which sends information to this number. And this information is stored in the same database table as the product number. when adding a new line to the database through the admin panel, this line is not saved in the database table. Why and how to fix this problem? -
In inlineformset_factory, can't change widget of primary model (django 3.0)
NOTE: This question is asked in this SO post. I applied the solution but its not working as expected. Maybe because I'm in Django 3.0? Problem: I am using an inlineformset_factory. I can modify the "child" form (aka formset) but not the "parent" form. You can see an illustration of the problem here: https://www.dropbox.com/s/won84143o16njhr/dj007_inlineformsetfactory_unable_to_modify_primary_form.jpg?dl=0 Here is following code so far: # FORMS.PY class Invoice_AJAX_Form(forms.ModelForm): model: Invoice_AJAX class Meta: model: Invoice_AJAX widgets = { 'ref_num': forms.TextInput(attrs={ 'class': 'form-control', }), 'customer': forms.TextInput(attrs={ 'class': 'form-control', }) } class Invoice_Inventory_JAX_Form(forms.ModelForm): class Meta: model: Inventory_Invoice_AJAX widgets = { 'price': forms.NumberInput(attrs={ 'class': 'form-control cls_price', 'placeholder': 'Price', }), 'inventory': forms.Select(attrs={ 'class': 'form-control cls_inventory', }), 'amount': forms.NumberInput(attrs={ 'class': 'form-control cls_amount', }), 'quantity': forms.NumberInput(attrs={ 'class': 'form-control cls_quantity', }), 'ref_num': forms.NumberInput(attrs={ 'class': 'form-control', }), 'discount': forms.NumberInput(attrs={ 'class': 'form-control cls_discount', }) } form=Invoice_Inventory_JAX_Form, fields = '__all__', can_delete = False) inventory_AJAX_formset = inlineformset_factory(Invoice_AJAX, Inventory_Invoice_AJAX, form=Invoice_Inventory_JAX_Form, fields = '__all__', can_delete = False) # MODEL.PY class Invoice_AJAX(models.Model): ref_num = models.CharField(max_length=100) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, default=1) date = models.DateField(default=datetime.date.today(), null=True, blank=True) def __str__(self): return str(self.ref_num) class Inventory_AJAX(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=9, decimal_places=2) invoice = models.ForeignKey(Invoice_AJAX, on_delete=models.CASCADE) def __str__(self): return self.name class Inventory_Invoice_AJAX(models.Model): inventory = models.ForeignKey(Inventory_AJAX, on_delete=models.CASCADE) invoice = models.ForeignKey(Invoice_AJAX, on_delete=models.CASCADE) price = models.DecimalField(max_digits=9, … -
Django Terminal 404 warning - how to find the root cause
I am creating a forum as part of a larger web project to aid my Django development. I am trying to display a user-created 'topic'(article) that allows users to comment on the article. Anyway been on it a couple of days and got the users set up, some models for articles and comments with bootstrap templates to display it all. I wish for comments to be added without leaving for an external page. I have achieved it and the functionality is as I wanted. However, in the terminal, I keep getting the message Not Found: /forum_topic/1/... [06/Jul/2021 14:29:26] "GET /forum_topic/1/... HTTP/1.1" 404 3682** With the functionality working as expected how do I trace what is trying to generate the url "/forum_topic/1/..." (i've assumed its a url?)? Should I even be worried about it? @Urls urlpatterns = [ path('forum/', ForumViewHome.as_view(), name="forum-home"), path('forum/DevArea/<str:dev_area_name>', ForumDevAreaTopics, name="forum-dev-area"), path('forum_topic/<int:pk>/', ForumTopicView, name="forum-topic-view"), #<int:pk> references the specifc blog path('forum_topic/new/', ForumTopicNew.as_view(), name="forum-topic-new"), path('forum_topic/edit/<int:pk>', ForumTopicEdit.as_view(), name="forum-topic-edit"), path('forum_topic/delete/<int:pk>', ForumTopicDelete.as_view(), name="forum-topic-delete"), ] @Views def ForumTopicView(request, pk): topic = get_object_or_404(Post,id=pk)# comment_form = ForumTopicCommentForm(request.POST or None)# template_name = "forum_topic_view.html" if request.method == "GET": topic_comments = Comment.objects.filter(on_post=pk) # For splitting comments into groups of 3 allowing them to be # displayed in seperate tabs. … -
Using cms_shiny in a django project error "cannot import name 'six' from 'django.utils'..."
I am trying to create a web app using django and I would like part of it to show a shiny dashboard. Recently I have been trying to use djangocms-shiny-app 0.1.3 package to accomplish this; however, after following the setup guide for the package, I am running into an error File "C:\Users\rdkbh\AppData\Local\Programs\Python\Python39\lib\site-packages\cms_shiny\models.py", line 2, in <module> from filer.fields.image import FilerImageField File "C:\Users\rdkbh\AppData\Local\Programs\Python\Python39\lib\site-packages\filer\fields\image.py", line 4, in <module> from .. import settings File "C:\Users\rdkbh\AppData\Local\Programs\Python\Python39\lib\site-packages\filer\settings.py", line 11, in <module> from .utils.loader import load_object File "C:\Users\rdkbh\AppData\Local\Programs\Python\Python39\lib\site-packages\filer\utils\loader.py", line 13, in <module> from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (C:\Users\rdkbh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\__init__.py) If anyone knows what is causing the error (Based on the error message I believe it is something to do with cms_shiny) and how to fix it or if there are any better packages for integrating a shiny app into Django I would greatly appreciate it. Thanks in advance! -
SMTPAuthenticationError after deployment even with recognized activity
hello after deployment of my site I have the problem that google blocks the email I recognized the activity normally there like heroku and local host it works but in the host it sends me more email let's say that the activity is blocked but they also do not send the verification email error "" "Google blocked the application you were trying to use because it does not meet our security standards. Some apps and devices use less secure sign-in technology, which makes your account more vulnerable. You can disable access for these apps (recommended) or enable it if you want to use them despite the risks involved. Google automatically turns this setting off if it is not used. "" " -
Django/Python: how to analyzing financial stock data (daily/monthly etc.)
I would like to do a lot of analysis/performance/statistics on my stock portfolio, which I plan to track with my app. E.g.: Week performance Month performance Year performance Best performer and a lot of other things I can't imagine right now... Where I'm struggling right now: - What is a good/the best way to archive this? - Also to show this info on a dashboard --> I think I should store this information somehow... But how to do this on a daily/weekly/whatever basis? --> I don't see a way to do such things while runtime? --> furthermore I need to know, when do do such thinks... It's end of the week so do weekly performance calculations... --> Maybe there is also an MVP solution, that can evolve into a top-notch solution? My models are locking like this at the moment - The position is the clamp around my orders and my EOD data. Right now I'm working with yfinance to get range financial data + finnhub API to get real time prices: class Position(models.Model): name = models.CharField(max_length=100) shares = models.FloatField(default=0.0) symbol = models.CharField(max_length=100, default="") transaction_fee_sum = models.FloatField(default=0.0) profit = models.FloatField(default=0.0) average_price = models.FloatField(default=0.0) cost_value = models.FloatField(default=0.0) last_price = models.FloatField(default=0.0) position_value … -
html2pdf with python : How to set footer and header on each page and control page cut
I use the app html2pdf with python on django framework. I use the html way and convert it in pdf by : pdf = render_to_pdf('front/bill.html', {'order': self, 'ligns': self.orderlign_set.all(), 'paiements':self.orderpayement_set.filter(paid__isnull=False)}) I have few questions : 1/ How to repeat the same header on each page ? I have used <page_header></page_header> in bill.html without effect 2/ How to repeat the same footer on each page AND stuck it on the bottom of the page ? I have used <page_footer></page_footer> in bill.html without effect. 3/ How to control where xhtml2pdf cut the text for write the next page ? its an invoice/bill, i can't split the text anywhere. 4/ How to display a page counter on each page ? Like page_number/total_page Thanks for your time -
Shared global variables among apps
Suppose I have two apps: data and visual. App data executes a database retrieval upon starting up. This thread here and this doc advises on how and where to place code that executes once on starting up. So, in app data: #apps.py from django.apps import AppConfig global_df #want to declare a global variable to be shared across all apps here. class DataConfig(AppConfig): # ... def ready(self): from .models import MyModel ... df = retrieve_db() #retrieve model instances from database ... return df In the code above, I am looking to execute ready() once on starting up and return df to a shared global variable (in this case, global_df). App visual should be able to access (through import, maybe) this global_df. But, any further modification of this global_df should be done only in app data. This thread here advised to place any global variable in the app's __init__.py file. But it mentioned that this only works for environmental variable. Two questions: 1 - How and where do I declare such a global variable? 2 - On starting up, how to pass the output of a function that executes only once to this global variable? -
Where to set the author as request.user
Problem In my model I have the field author which I want to enter as a ForeignKey with the UserModel with the user who has authenticated himself via JWT Token. My API and JWT authentication works fine, but I don't know where to set the author = request.user in the backend. My Code: apis.py class AlarmstichworteCreateApi(ApiErrorsMixin, APIView): permission_classes = [IsAuthenticated] class InputSerializer(serializers.ModelSerializer): author = UserListAPI.OutputSerializer(source='UserListAPI_set', many=True) created = serializers.DateTimeField() updated = serializers.DateTimeField() name = serializers.CharField(max_length=100) class Meta: model = AlarmstichworteConfig fields = ( '__all__' ) def post(self, request, *args, **kwargs): serializer = self.InputSerializer(data=request.data) #! serializer = self.InputSerializer(data=request.data, author=request.user) # Try 1 serializer.is_valid(raise_exception=True) create_alarmstichwort(**serializer.validated_data) #! create_alarmstichwort(**serializer.validated_data, author=request.user) # Try 1 return Response(status=status.HTTP_201_CREATED) services.py def create_alarmstichwort( *, author: ForeignKey, created: datetime, updated: datetime, name: str, ) -> AlarmstichworteConfig: if AlarmstichworteConfig.objects.filter(id=id).exists(): raise ValidationError('Alarmstichwort existiert bereits') alarmstichwort = AlarmstichworteConfig.objects.create( author=author, created=created, updated=updated, name=name, ) alarmstichwort.full_clean() alarmstichwort.save() return alarmstichwort I would be happy if anyone could help me. Many thanks in advance! -
Webpack/babel not compiling ReactDOM.render
Objective: I am trying to get webpack/babel to compile JSX so that I can make a website with react front end, and django rest api backend. I have gone through many tutorials and Stackoverflows, but never gotten JSX to compile to make combo work. I debugged for a LONG time, and found that the crux of the JSX problem seems to be centered around reactDOM.render. If I use react components without reactDOM.render, it all works, with is breaks down with errors such as "App.js:12 Uncaught ReferenceError: ReactDOM is not defined" or the one I get most often, "Module parse failed: Unexpected token (13:12) You may need an appropriate loader to handle this file type" here is the code-- my .babelrc file: { "presets": [ "@babel/preset-env", "@babel/preset-react" ] } webpack.config.js: module.exports = { module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } }; packages.json: { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --entry ./src/index.js --output-path ./static/frontend", "build": "webpack --mode production --entry ./src/index.js --output-path ./static/frontend" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.14.6", "@babel/preset-env": "^7.14.7", "@babel/preset-react": "^7.14.5", "babel-loader": "^8.2.2", "react": "^17.0.2", "react-dom": "^17.0.2", "webpack": … -
I just want to pull only value datas from a sql ResulSet
Here is my output value when I print test variable in my code: ResultSet({'('device_frmpayload_data_Sayac', None)': [{'time': '2021-07-03T15:50:00.359986Z', 'application_name': 'TrashTest', 'dev_eui': '45405201a0000009', 'device_name': 'sayac-001', 'f_port': '4', 'value': 338.0}, {'time': '2021-07-03T15:48:56.204781Z', 'application_name': 'TrashTest', 'dev_eui': '45405201a0000009', 'device_name': 'sayac-001', 'f_port': '4', 'value': 338.0}]}) I do not know the type of this variable and can not check because it gives an error: typeerror 'builtin_function_or_method' object is not subscriptable .it has 0 attributes btw when I checked it. Here is my code: def amChartsDbData(request): client = InfluxDBClient(host=lora_host, port=####) client.switch_database('loradb') sayac = client.query("SELECT * From device_frmpayload_data_Sayac WHERE time > now() - 5d ORDER BY time DESC LIMIT 2") sayactimeLuna = client.query("SELECT elapsed(value,1s) FROM device_frmpayload_data_Sayac WHERE dev_eui='######201a0000009'") sycLuna = list(sayac.get_points(tags={'dev_eui': '#######1a0000009'}))[-1:] sycBaylan = list(sayac.get_points(tags={'dev_eui': '######1a0000010'}))[-1:] lunaTable = list(sayac.get_points(tags={'dev_eui': '#####a0000009'}))[-3:] baylanTable = list(sayac.get_points(tags={'dev_eui': '########a0000010'}))[-3:] timeLuna = list(sayactimeLuna.get_points())[-1:] test = sayac Finally, I also want the time value in proper format as: YYYY-MM-DD-HH-MIN-SEC. Thanks a lot. -
Java library for building Django Q and F queries
A Java/Spring project I work on builds a lot of Q and F queries manually to make requests to an external API. Is there a Java library out there for building Django REST queries, or maybe something just considered a best practice for this use case? -
Django searching a function for a string within it
I am attempting to setup a database driven search for the User Guide of a system. Overall I am writing a Django command that loops over the URLs in the User Guide, from that I need to also gather the Template that is being rendered by Django at the URL so I can render it to HTML and naturally search it, but gathering the Template is seeming to be quite difficult. Here is my current code: import importlib from django.core.management.base import BaseCommand def get_user_guide_urls_as_dict(): """ Used to return the list of url names and urls found in the application. { url_name: url } :return: """ from django.apps import apps list_of_all_urls = list() class UserGuideConfig: def __init__(self): pass for name, app in apps.app_configs.items(): # only gather user guide stuff if 'user_guide' in app.name: mod_to_import = f'apps.{name}.urls' urls = getattr(importlib.import_module(mod_to_import), "urlpatterns") list_of_all_urls.extend(urls) for url in list_of_all_urls: # the function/ callback should have the template name I need, # how do I get it rendered as a string print(url.callback.__wrapped__) class Command(BaseCommand): """ Used as a method to generate user guide searchable items in db """ help = "" def handle(self, *args, **options): # loop urls url_dict = get_user_guide_urls_as_dict() The best way I can … -
Installing Django dev environment - Errno 13
I am trying to set up my dev environment. I am supposed to install pipenv but am getting an error: [pipenv.exceptions.InstallError]: ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: [pipenv.exceptions.InstallError]: Check the permissions. ERROR: Couldn't install package: psycopg2 I am on a mac and I used pipx to install pipenv, the other options didn't work for me. I have tried the following: pipenv install psycopg2 pipenv run pip install psycopg2 pipenv install psycopg2-binary -
How do I get rid of this !!!!! (Django) [closed]
enter image description here please someone show me how to get rid of that 'This field is required' li tag (see image) Thanks note: I've tried blank=True, null=True -
Using Postgres roles and privilege in Django project
I am using Django Rest Framework with postgres. From the beginning of the project we used django-guardian to provide opportunity of using object permissions. But django-guardian can slow down all of the app when we have large amount of users, groups and permissions to them. What about of using postgres roles in django project? What about of storing each user as postgres role? What difficulties can we face? We will have a large number of users and roles, can it give problems to us if we will use postgres? -
wagtail admin list_editable fields
Is there an analogue of list_editable (django) in wagtail admin indexview (listview)? I have an integer field that I want to be able to edit from the list of records page (without going to the specific record edit page). -
Unable to load environment variable (.env) in Django App
I am trying to launch a Django project and am unable to do so because it seems my local environment is disconnected from my .env file in the root directory. I've never had this problem before and assume there is an easy fix but I can't seem to figure it out. When I run basic commands like runserver I get the following error: RATE_LIMIT_DURATION = int(os.environ.get("RATE_LIMIT_DURATION")) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' In my .env file, I have defined the variable as: RATE_LIMIT_DURATION = 10 I have already confirmed that my database is setup and I am pretty sure my settings are in good shape otherwise. DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get("DB_NAME"), "USER": os.environ.get("DB_USER"), "PASSWORD": os.environ.get("DB_PASSWORD"), "HOST": "localhost", "PORT": 8000, } } -
PayPal: Is it possible to pay for an order just by the order id/details
I am trying to create the order on the backend and then pass the order id to the smart button's javascript so that i can execute the order without allowing the user to edit the order. i have successfully done this before with a subscription by creating a plan and then passing in the plan id to execute the payment but i don't know what button action to use to do this with orders. How should i do this? Here is how i am doing this on the backend: headers = { "Content-Type": "application/json", "Authorization": bearer_token, } data = { "intent": "CAPTURE", "purchase_units": [ { "amount": { "currency_code": "GBP", "value": str(order.credits) } } ] } response = requests.post('https://api-m.sandbox.paypal.com/v2/checkout/orders', headers=headers, json=data).json() order_id = response["id"] context = { 'order_id': order_id, } and here is what i have tried on the frontend: paypal.Buttons({ style: { size: 'responsive', }, createOrder: function(data, actions) { return actions.order.create({ "id": "{{ order_id }}" }); }, onApprove: function(data, actions) { } }).render('#paypal-button-container'); / -
django get coroutine object data using sync_to_async way
def compute_topics_to_eventabis() -> Dict: "Loop through all contracts in our DB and compute topics to ABI mapping" topics_to_event_abis = {} contracts = sync_to_async(EthereumContract.objects.all)() print(contracts) for contract in contracts: # we could use contract.web3_objects().events as well for entity in contract.abi: if entity["type"] == u"event": topics = construct_event_topic_set(entity, get_infura_server().codec) for topic in topics: topics_to_event_abis[topic] = entity return topics_to_event_abis Task exception was never retrieved future: <Task finished name='Task-2' coro=<get_new_heads() done, defined at watcher.py:145> exception=TypeError("'coroutine' object is not iterable")> Traceback (most recent call last): File "watcher.py", line 173, in get_new_heads process_block(formatted_result['blockNumber'], File "watcher.py", line 142, in process_block return replay_block(block_id, get_infura_server()) File "watcher.py", line 132, in replay_block return process_each_log_and_spawn_event(logs) File "watcher.py", line 117, in process_each_log_and_spawn_event for event in process_each_log_and_yield(logs): File "watcher.py", line 105, in process_each_log_and_yield TOPICS_TO_EVENT_ABIS = compute_topics_to_eventabis() File "watcher.py", line 93, in compute_topics_to_eventabis for contract in contracts: TypeError: 'coroutine' object is not iterable /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/events.py:81: RuntimeWarning: coroutine 'SyncToAsync.__call__' was never awaited self._context.run(self._callback, *self._args) RuntimeWarning: Enable tracemalloc to get the object allocation traceback Here when i am using sync_to_async it is throwing above error How to read and loop over contracts ? Am i doing it correctly ? Please take a look. How can i solve it .