Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How can I repeat a block within a template
My Django base template looks like this: #base.html <title>{% block title %} My Default Title {% endblock title %}</title> <meta property="og:title" content="{% block og_title %} My Default Title {% endblock og_title %}"> Then if I'd like to override the default title for specific page: #page.html {% extends "base.html" %} {% block title %} My page Title {% endblock title %} {% block og_title %} My page Title {% endblock _ogtitle %} How can I set the base.html block title once (like a variable) and use across my document? Then, if I need, I override the title once in the page.html and it gets populated across? -
UnboundLocalError at / local variable 'key' referenced before assignment
here is my code i am facing this error i am not able to find the error fix the error shoow def get_key(res_by): if res_by == '#1': key = 'transaction_id' elif res_by == '#2': key = 'created' return key thats the code -
Django formset model not being created correctly
My code: # forms.py class PopupForm(forms.ModelForm): class Meta: model = Popup exclude = () class LiveStreamForm(forms.ModelForm): class Meta: model = LiveStream exclude = ("date_created",) PopupFormSet = inlineformset_factory(LiveStream,Popup,exclude=(),extra=3) # models.py class Popup(models.Model): total_seconds_to_initiate = models.BigIntegerField() livestream = models.ForeignKey('LiveStream', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return "%s seconds, ls:%s" % (self.total_seconds_to_initiate, self.livestream) def get_absolute_url(self): return reverse("livestream_detail", kwargs={ 'pk': str(self.livestream.id),}) class LiveStream(models.Model): youtube_id = models.CharField(max_length=255, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return "%s (%s)" % (self.youtube_id, self.id) def get_absolute_url(self): return reverse("livestream_detail", kwargs={ 'pk': str(self.id),}) # views.py class LiveStreamCreateView(CreateView): model = LiveStream form_class = LiveStreamForm template_name = 'livestream/livestream_create.html' def get_context_data(self, **kwargs): context = super(LiveStreamCreateView, self).get_context_data(**kwargs) context['popup_form_set'] = PopupFormSet return context # livestream_create.html <form method="POST"> {% csrf_token %} Enter the Channel ID of the Livestream Here. {{form}}<br> {{ popup_form_set.management_form }} {{ popup_form_set.non_form_errors }} {% for popup_form in popup_form_set %} {{popup_form}}<br> {% endfor %} <input type="submit" value="Save"> </form> I want users to be able to create Popup objects on the same page they create Livestream objects. At the moment the form looks like it should work: there's a Livestream Youtube ID field, and 3 Popup total_seconds_to_initiate fields. What should happen is, I enter a youtube ID, then an arbitrary number (=<3) of popups, and I get … -
SPA How to remove the # in the URL when visiting new page?
I'm using Django and vanilla JavaScript, on my localhost when I click on a button to display a New page my URL turns to localhost:8000/# How to not show the #? I'm trying to add a URL to the pages using history.pushState(null, ' ', "all_posts"); for example and now my URL shows http://localhost:8000/all_posts# -
How to get the shape drawn by leaflet and pass it to Geodjango for further calculation
I have a question is that how to get the shape drawn on map and pass it to geodjango to do calculation with database. [ -
Local windows - Server Ubuntu, git push live no putty
I've a django app, i'd like to set-up with git remote with git push live command pushing onto AWS EC2 all methods mentioned use putty which isn't able to config it I've set up a bare repository with edits(https://gist.github.com/noelboss/3fe13927025b89757f8fb12e9066f2fa) done to using this as a reference all works fine until I need to hit $ git remote add production demo@yourserver.com:project.git this line, as ssh was through putty, I faced issues here -
Need Help Deploying Celery Beat and a Celery Worker for Django on Azure App Services with Azure Cache for Redis using Systemd and a Startup Script
I am trying to deploy a django webapp to azure with a celery beat and worker instance running in the background. I've tried using a config file, a startup script, and systemd to deploy the celery instances. But I've been having problems getting the .services files to run. Here are my systemd .service files; celerybeat.service [Unit] Description=Celery Beat Service After=network.target [Service] Type=simple User=celery Group=celery EnvironmentFile=/etc/conf.d/celery_config WorkingDirectory=/home/site/wwwroot/celery ExecStart= /bin/sh -c '${CELERY_BIN} -A ${CELERY_APP} beat \ --pidfile=${CELERYBEAT_PID_FILE} \ --logfile=${CELERYBEAT_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL}' Restart=always [Install] WantedBy=multi-user.target celeryworker.service [Unit] Description=Celery Worker Service After=network.target [Service] Type=simple User=celery Group=celery EnvironmentFile=/etc/conf.d/celery_config WorkingDirectory=/home/site/wwwroot/celery ExecStart= /bin/sh -c '${CELERY_BIN} -A ${CELERY_APP} worker \ --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL}' Restart=always [Install] WantedBy=multi-user.target The celery config file is the following, celery_config; # Name of nodes to start # here we have a single node CELERYD_NODES="w1" # or we could have three nodes: #CELERYD_NODES="w1 w2 w3" # Absolute or relative path to the 'celery' command: CELERY_BIN="/home/site/wwwroot/celery" #CELERY_BIN="/virtualenvs/def/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="kinduwa" # or fully qualified: #CELERY_APP="proj.tasks:app" # How to call manage.py CELERYD_MULTI="multi" # Extra command-line arguments to the worker CELERYD_OPTS="--time-limit=300 --concurrency=8" # - %n will be replaced with the first part of the … -
Django 3.2 authentication with social auth
About project - Django Rest API django==3.2.2 djangorestframework==3.12.4 I need to implement authentication in Django, including the social auth, permission at the role level. I am referencing the django doc https://www.django-rest-framework.org/api-guide/authentication/ But, I am confused when it says use third party library - Questions - Does Django rest framework does not provide auth and social auth? Is it mandatory to use a third-party library? Which library would I use with the latest Django version? I researched a bit and found most of the libraries are not maintained anymore. Django OAuth Toolkit - supports latest Django REST framework OAuth - not supported for django 3.2, last release 2019 JSON Web Token Authentication - last release 2020 HTTP Signature Authentication - last release 2015 Djoser - does not support Django 3.2 django-rest-auth - last realease 2019 / dj-rest-auth - supports latest Django-rest-framework-social-oauth2 - last release 2019 Django-rest-knox - last release 2020 Which one should I choose for my requirement? I explored deep into Djoser docs only, I found it useful and pretty good, but later found that it is not for Django 3.2. Correct me if I am wrong. If anybody has already used any of these libraries, please help me out! … -
Empty AJAX PUT request body; Django Rest API
I'm mimicking StackOverflow's template of voting on a Question/Answer. Upon clicking an upvote/downvote button, a PUT request is sent to the API. However, DRF doesn't find any data attached to the request body as request.data == {} in the respective view. How should I go fixing the client API call or the API itself for there to be a request body? vote_button.addEventListener("click", function(event) { voted_post = this.id.split("_") const _question = voted_post[0]; q_id = _question[_question.length - 1] vote = voted_post[-1] const headers = new Headers({ "Accept": "application/json", "Content-Type": "application/json", "X-CSRFToken": csrftoken }); const request = new Request( `http://localhost:8000/api/v1/questions/${q_id}/`, { "method": "put", "headers": headers, "body": JSON.stringify({ "vote": vote }) } ); fetch(request).then((response) => { if (response.ok) { return response.json() } }).then((data) => { let vote_tally = document.getElementById(`question${q_id}_tally`); vote_tally.textContent = data['vote_tally'] }) REST_FRAMEWORK = { 'TEST_REQUEST_DEFAULT_FORMAT': 'json', 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser' ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication' ], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.ScopedRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'voting': '5/minute' } } class UserQuestionVoteView(APIView): throttle_scope = "voting" def put(self, request, id): account = UserAccount.objects.get(user=request.user) question = get_object_or_404(Question, id=id) if account == question.user_account: return Response(data={ 'vote': "Cannot vote on your own question" }, status=400) try: stored_vote = QuestionVote.objects.get( account=account, question=question ) serializer = … -
How to store large JSON FILE data in django using models. ( using HTML, CSS, Javascript and Django)
I'm using Django as storage, and HTML, CSS for the frontend. So, I have successfully created models for Products, Categories, Carts, and Users. I can store data and fetch the data too but adding one row at a time is time-consuming. I have 2000 + data (Stored in .JSON) in one category (Since making an e-commerce website). So how, I will get rid out of it. What are the codes needed? -
Django default value in in input field
I need to set a placeholder/default value for the input field below (the first field in the form) I need to send the data ex_name.id in order to validate the form, which it does, but I want the information displayed in the field to be ex_name.exercise. I was able to accomplish this in the option fields (fields 2 and 3), but not for the input field. If I make the input field an option field, it doesn't send the data when I submit it because the field is readonly and it has to stay readonly. value must be ex_name.id/ex_name.pk, but I don't want to display a number to the end user. How to I display different text there while still retaining value="{{ex_name.id}}"? <div class="form-group col-lg-4 col-md-6 col-sm-12"> <form action="" method="post"> {% csrf_token %} <label for="exercise">Exercise</label> <input class="form-control" id="id_exercise" type="text" name="exercise" value="{{ex_name.id}}" required="" readonly> <label for="unit">Select Unit</label> <select class="form-control" id="id_unit" name="unit" value=""> {% for unit in unit_list %} <option value="{{unit.id}}">{{unit.unit_name}}</option> {% endfor %} </select> <label for="location">Location</label> <select class="form-control" id="id_location" name="location" value=""> {% for loc in locations %} <option value="{{loc.id}}">{{loc.location}}</option> {% endfor %} </select> <label for="quantity">Pax</label> <input class="form-control" id="id_quantity" type="text" name="quantity" value="" required=""> <input class="btn btn-primary mt-3" type="submit" value="Submit"> </form> </div> -
Updating records within a modal
We have taken on a project where the front end admin dashboard has been created using Bootstrap Modals. When we go to update a record from the ASP modal we have used JSON outputs and JQuery to populate the data within the form, as from what we found this could not be done by Django alone. The issue we have is that we can add new records using the populated JSON data but I cannot edit existing records. Even though JQUERY and JSON brings the correct data when we click submit it cannot associate to the record within the database. How could we update the correct record? One other method we tried was passing the ID (related to the booking) through the URL but this kept redirecting the page and not staying on the modal. Just so I don't add to much, below is the related code to the issue. I am not great with programming so hope this makes some sense what we are trying to achieve, thanks in advance for any help we can get with this issue. View Code class admin_booking(View): def get(self, request): # check whether the user is logged in. context = initialize_context(request) token = … -
Any way to translate a field in my django model already downloaded to my PostgreSQL database through a fixture?
I've been reading about internationalization/location in Django and have been stuck in a deadlock-kinda situation: I need to translate a charfield from English to Spanish, but such data is uploaded to my proyect implementing a fixture. I can't use the native tools from django.utils.translations since this data isn't recognized by the makemessages command. Also, I've found that making a custom django.po message file for such uploaded strings is a bad practice: https://code.djangoproject.com/ticket/6952. On the other hand I found the package django-modeltranslation (https://django-modeltranslation.readthedocs.io/en/latest/index.html) but this doesn't solve my issue since I need the string in my charfield to be a customized locale, I must provide specific translations for each as a requirement and I only see that this tool can only translate based on the standard localizations. Any ideas? Here is my model for further information: class Triague_Question(models.Model): question_text = models.CharField(_("question"), max_length=255) is_critical = models.BooleanField(_("is a critical question"), default=False) is_medical = models.BooleanField(_("is a medical question"), default=False) -
I've been trying to use asyncio to speed up this loop with api requests and dictionary making but it seems to remain so slow, taking over 2 seconds
... over 2 seconds just for a total of 4 data requests to the exchange and dictionary making function. if someone has any suggestions it would be a big help. async_tasks = [] async def sigBuy(count): bot_dict = Bot.to_dict(activeBots[count]) sigSettings_dict = Bot.to_dict(activeBots[count].sigSettings) # Binance API and Secret Keys Bclient = Client(sigSettings_dict['API_key'], sigSettings_dict['API_secret_key']) p = round(float(percentage(7, bot_dict['ct_balance']) / (float(bin_asset_price['price']) / 1)), 8) # Round and Asign the asset_amount asset_amount = round(p, 2) # shouldILog = await makeBuy(market, asset_amount, Bclient, sigSettings_dict['base_currency']) shouldILog = 2 if shouldILog == 2: asset_amount = int(asset_amount) last_trade = Bclient.get_all_orders(symbol=market + sigSettings_dict['base_currency'])[-1] print(last_trade) asset_price = float(last_trade['cummulativeQuoteQty']) / float(last_trade['executedQty']) buyInPrice = float(last_trade['cummulativeQuoteQty']) for otrade in activeBots[count].opentrades.all(): trade = Bot.to_dict(otrade) del trade['id'] otradesUpdate.append(trade) openTrades_dict = {'bot_ID': bot_dict['id'], 'date': date, 'market': market, 'trade_mode': 'Buy', 'price': asset_price, 'amount': asset_amount, 'amount_in_base_currency': buyInPrice, 'result': 0} otradesUpdate.append(openTrades_dict) BotsUpdate.append(bot_dict) SigSettingsUpdate.append(sigSettings_dict) for count, bot in enumerate(activeBots): async_tasks.append(loop.create_task(sigBuy(count))) loop.run_until_complete(asyncio.gather(*async_tasks)) -
link multiple database models in django by unrelated fields
In sql if there are two table which have fields that have data with resemblance but do not have connection together you can links them up like this select tab1.name, tab1.gender, tab1.occupation, tab2.location , tab2.biz_time ,tab3.address from staffdata tab1, sales tab2, address tab3 where tab1.user_id=tab2.user_id and tab3.location_id=tab2.location_id this would link them up to produce results from the 3 tables I have tried subquery, annotate with values but was getting wrong result this is what i have tried code_subquery = SalesRecord.objects.filter(staff__username__iexact=request.user, user_id=OuterRef('user_id')) timetablevalues= StaffData.objects.filter(staff=request.user, user_id=Subquery( code_subquery.values( 'location', 'biz_time', 'item')))\ .values('name','gender', 'location', 'biz_time', 'item') Although this is for 2 tables but I might do that of 3 tables later on Please how can I go about it -
How to filter a list JSONField exactly?
I have a model that essentialy boils down to this: class Model: json_field = ArrayField() Where json_field is essentially a list of strings. So let's say I have two Model objects ModelA and ModelB that have their json_field as ["1","2","3"]and ["1","2","4"] respectively. How can I filter to the json_field exactly? Specifically: What is the search value? What is the query that filters by the search value? value = ["1","2","3"] # Doesn't work value = "1","2","3" # Also doesn't work # Not even sure if this is the correct approach Model.objects.filter(json_field__iexact=value) I'm actually using django-filter to manage this search function for a DRF backend. (e.g. /api/v1/models/?json_field=) Unfortunately, there doesn't seem to be an ArrayFilter or a JSONFilter so this is what I'm working with: class ModelFilter(django_filter.FilterSet): class Meta: model = Model field = "json_field" # Not even sure if this should be a CharFilter json_field = django_filters.CharFilter(method="json_field_filter") def json_field_filter(self, queryset, name, value): return queryset.filter(json_field__iexact=value) # doesn't work where value = ["1","2","3"] # also doesn't work where value = "1","2","3" I can find solutions online (from which I've worked to the above) for dictionaries but nothing for lists. Would appreciate any help/pointers. -
ElasticSearch, FarmHaystack, Django connection Refused
I'm trying to make this https://haystack.deepset.ai/docs/latest/tutorial5md into a Dockerized Django App, the problem is when I impliment the code locally it works but when I make a dockerized version of it it gives me a connection refused, my guess is that the two docker images can't find they'r ways to each other. This is my docker-compose.yaml file version: '3.7' services: es: image: elasticsearch:7.8.1 environment: - xpack.security.enabled=false - "ES_JAVA_OPTS=-Xms512m -Xmx512m -Dlog4j2.disable.jmx=true" - discovery.type=single-node - VIRTUAL_HOST=localhost ports: - "9200:9200" networks: - test-network container_name: es healthcheck: test: ["CMD", "curl", "-s", "-f", "http://localhost:9200"] retries: 6 web: build: . command: bash -c "sleep 1m && python manage.py migrate && python manage.py makemigrations && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app networks: - test-network ports: - "8000:8000" depends_on: - es healthcheck: test: ["CMD", "curl", "-s", "-f", "http://localhost:9200"] retries: 6 networks: test-network: driver: bridge and this is my apps.py from django.apps import AppConfig import logging # from haystack.reader.transformers import TransformersReader from haystack.reader.farm import FARMReader from haystack.preprocessor.utils import convert_files_to_dicts, fetch_archive_from_http from haystack.preprocessor.cleaning import clean_wiki_text from django.core.cache import cache import pickle from haystack.document_store.elasticsearch import ElasticsearchDocumentStore from haystack.retriever.sparse import ElasticsearchRetriever from haystack.document_store.elasticsearch import ElasticsearchDocumentStore class SquadmodelConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'squadModel' def ready(self): document_store = ElasticsearchDocumentStore(host="elasticsearch", username="", password="", index="document") … -
AUTH_USER_MODEL refers to model 'auth_app.AuthAppShopUser' that has not been installed
I am trying to implement shopify authentication via using this library from github: https://github.com/discolabs/django-shopify-auth However, after assigning the following value in "settings" and completing other related steps, getting the following error: AUTH_USER_MODEL refers to model 'auth_app.AuthAppShopUser' that has not been installed views.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shopify_auth', ] AUTH_USER_MODEL = 'auth_app.AuthAppShopUser' auth_demo/models.py: from django.db import models from shopify_auth.models import AbstractShopUser class AuthAppShopUser(AbstractShopUser): pass -
Login not redirecting to the specified url on django
I want to be redirected to the dashboard page in the website but I'm being redirected to a different url which is not specified in django url and as a result I'm getting page not found error. I don't know why django is not redirecting me to the login_url_redirect that is specified in the settings.py. settings.py AUTH_USER_MODEL = 'account.UserBase' LOGIIN_REDIRECT_URL = '/account/dashboard' LOGIN_URL = '/account/login' urls.py url.py(in the main django app) urlpatterns = [ path('account/', include('account.urls', namespace='account')), ] urls.py (for the given app) urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='account/registration/login.html', form_class=UserLoginForm), name='login'), path('register/', views.account_register, name='register'), path('dashboard/', views.dashboard, name='dashboard'), ] template <form class="account-form p-4 rounded" action="{% url 'account:login' %}" method="post"> {% csrf_token %} <h3 class="mb-4">Sign In</h3> {% if form.errors %} <div class="alert alert-primary" role="alert"> Error: Username or Password not correct! </div> {% endif %} <label class="form-label">{{ form.username.label}}</label> {{ form.username}} <label class="form-label">{{ form.password.label}}</label> {{ form.password}} <div class="d-grid gap-2"> <input type="hidden" name="next" value="{{ next }}"> <button class="btn btn-primary py-2 mb-4 mt-5 fw-bold" type="submit" value="Log-in">Sign in </button> </div> <p class="text-center pb-3"> <a href="{% url "account:register" %}">Create an account</a> </p> </form> I want someone to help me pinpoint the reason why I'm not redirected to this url specified in settings.py LOGIIN_REDIRECT_URL = '/account/dashboard' -
Python type annotation for list of potential return values
Can a Python function be annotated with a list of potential return values? RAINY = 'rainy' SUNNY = 'sunny' CLOUDY = 'cloudy' SNOWY = 'snowy' TYPES_OF_WEATHER = [RAINY, SUNNY, CLOUDY, SNOWY] def today_is_probably(season) -> OneOf[TYPES_OF_WEATHER]: if season is 'spring': return RAINY if season is 'summer': return SUNNY if season is 'autumn': return CLOUDY if season is 'winter': return SNOWY -
I got 500 server error whenever I try to sign in, sign up.... I think this is someting to do with google social account
I used to have 'https' but my web application went wrong so I had to get new ip address. so now same domain but different ip address. I tried to get 'https' for new ip address and got the new one but 'https' is not working. finally I got message from google cloud, OAuth consent screen on the credential page saying "Changing publishing status from 'Testing' to 'In Production' is restricted to projects using HTTPS URLs only." Now the login and signup by emails is not even working at all. just got server error 500. I went to google page and was told me to be here to ask quesitons and help -
Why am I not getting the Following Records on my page
I am building a followers System on my Django Blog Here is the model: class Followers(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) another_user = models.ManyToManyField(User, related_name='another_user') def __str__(self): return self.user.username Here is my view Method: def profile(request, user_name): user_obj = User.objects.get(username=user_name) session_user = User.objects.get(username=request.session['user']) session_following, create = Followers.objects.get_or_create(user=session_user) following, create = Followers.objects.get_or_create(user=session_user.id) check_user_followers = Followers.objects.filter(another_user=user_obj) is_followed = False if session_following.another_user.filter(username=user_name).exists() or following.another_user.filter(username=user_name).exists(): is_followed=True else: is_followed=False param = {'user_obj': user_obj,'followers':check_user_followers, 'following': following,'is_followed':is_followed} if 'user' in request.session: return render(request, 'users/profile2.html', param) else: return redirect('index') Here is my template: <h1>Followers</h1> <hr> {% if user_obj.username == request.session.user%} <h4>Name: {{user_obj.username}}</h4> <span>Followers: {{followers.count }}</span> <br> <span>Following: {{session_following.another_user.count }}</span> {% else %} <h4>Name: {{user_obj.username}}</h4> <span>Followers: {{followers.count }}</span> <br> <span>Following: {{user_following.another_user.count }}</span> <h4>Profile is Private.</h4> {% endif %} <br><br> {% if user_obj.username != request.session.user%} {% if is_followed %} <a href="{% url 'follow' user_obj.username %}" style="border: 1px solid; background: red; padding:10px; color: white;">Unfollow</a> {% else %} <a href="{% url 'follow' user_obj.username %}" style="border: 1px solid; background: yellow; padding:10px; color: black;">Follow</a> {% endif %} {% endif %} I am not getting the following count on my page I am using the code from following website:https://dev.to/madhubankhatri/follow-unfollow-system-using-django-simple-code-3785 -
Source Code Relation between class-based views and its Models
According to Django official URL, **## models.py** from django.db import models class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) ... **## views.py** from django.views.generic import ListView from books.models import Publisher class PublisherList(ListView): model = Publisher **## urls.py** from django.urls import path from books.views import PublisherList urlpatterns = [ path('publishers/', PublisherList.as_view()), ] In the template, a variable called object_list that contains all the publisher objects. {% extends "base.html" %} {% block content %} <h2>Publishers</h2> <ul> {% for publisher in object_list %} <li>{{ publisher.name }}</li> {% endfor %} </ul> {% endblock %} I have been deep diving into source code of django to find out exactly where Django explicitly put all objects of the Publisher Model into the template context (object_list). But no luck so far, Can anyone share some insights please? -
Optimize a Django query where it uses prefetch_related on a select_related
I'm trying to figure out how to optimize a Django query. I have an queryset that contains a foreign key to exercises. That table makes ManyToMany references to a number of other tables. If selecting exercises, I'd use prefetch_related to include them in the query, but I can't figure out how to do that in this case, since I'm doing it from a different table. Currently, it's being selected as super().get_queryset(request).select_related('exercise') But I can't figure out how to attach prefetch_related to that. Looking at SO, I found a solution that led me to this: return super().get_queryset(request).select_related( Prefetch( 'exercise', queryset=Exercise.objects.prefetch_related('equipments', 'inuries') ) ) But it fails with 'Prefetch' object has no attribute 'split', which I traced through the source, and it looks like select_related can't work with Prefetch. -
Need help making 1000's requests as fast as possible., python, django
I'm deep in the middle of coding a full web application in Django, but am venturing into new territory trying to send 1000's of API Trading Requests to an exchange as fast as possible. I want it so that each time it iterates through the loop ( each bot ), it sends the trading signal to the exchange, collects some data from the exchange and logs all the data in the databse. But since it has to wait each time it sends or receives data to/from the exchange, I am trying to figure out how to make the code asynchronus. So that it would get to each waiting point then start the next loop, and start sending the next signal. Then come back and finish collecting the data and saving it to the databse when it can. Because obviously if it has to wait each time on 1000's of bot's then it will take ages. I'm getting confused trying to figure it out online and wondered if someone could help/answer some things for me. I also wondered that since I'm trying to run the code async and the variable names are the same in each iteration of the loop, would …