Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Template has_changed always true on page load with initial form value
I’m having an issue on understanding how to render a page with Django the correct way. I would like the initial page to load with the below form only. Then after posting and getting back data, display the results. The issue I’m having is when i add an initial end date, the page loads with anything in the if statement. forms.py class TrainingStatsForm(forms.Form): start_date = forms.CharField(label='Start Date', max_length=12, widget=DateInput()) end_date = forms.CharField(label='End Date', max_length=12, widget=DateInput(), initial=datetime.date.today) dog = forms.ModelChoiceField(queryset=k9Table.objects.all()) If I remove the initial=datetime.date.today. Then the page load correctly Views.py def trainingstats(request): if request.POST: date_data = TrainingStatsForm(request.POST) if date_data.is_valid(): start_date = date_data.cleaned_data['start_date'] end_date = date_data.cleaned_data['end_date'] dog = date_data.cleaned_data['dog'] requested_search_training = TrainingTable.objects.filter(date__gte=start_date, date__lte=end_date, dog=dog).order_by('-date') requested_search_detection = DetectionTable.objects.filter(date__gte=start_date, date__lte=end_date, dog=dog).order_by('-date') requested_search = sorted( chain(requested_search_training, requested_search_detection), key=lambda data: data.created, reverse=True else: date_data = TrainingStatsForm() requested_search_training = None requested_search_detection = None requested_search = None total_time = 0 content = { 'returned_data': returned_data, 'date_data': date_data, 'requested_search': requested_search, } return render(request, 'trainingstats.html', content) Template <form method="post"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-2 mb-0"> {{ date_data.dog|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ date_data.start_date|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ date_data.end_date|as_crispy_field }} </div> </div> <div class="form-row"> <input type="submit" value="Submit" class="btn btn-primary"/> </div> </form> {% … -
Django Rest Framework: XLSXRenderer -- How to check condition for queryset and return a Response
from rest_framework.viewsets import ReadOnlyModelViewSet from drf_renderer_xlsx.mixins import XLSXFileMixin from drf_renderer_xlsx.renderers import XLSXRenderer from .models import MyExampleModel from .serializers import MyExampleSerializer class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet): serializer_class = MyExampleSerializer renderer_classes = [XLSXRenderer] filename = 'my_export.xlsx' def get_queryset(self): start_date = self.request.query_params.get('start_date', None) end_date = self.request.query_params.get('end_date', None) queryset = MyExampleModel.objects..filter(created__range=[start_date, end_date]) Return queryset # What I want to do # If not queryset: # Return Response({"message": "Exporting Fail"}) # Is there a way to check if queryset is None and return a Error Message instead of an empty Excel # I think that I not allow return Response in the get_queryset function Currently, I am trying to build a function to export excel file. I just want to know is there a way to check if the queryset is None and then I can return a Response({"message": "Exporting Fail, Empty"}) If you know where can I research it would help me a lot. Thank you so much -
PasswordResetForm change default protocol from http to htttps Three questions
this is whats written in the documentation protocol: http or https this is the link to documentation https://docs.djangoproject.com/en/3.2/topics/auth/default/#django.contrib.auth.forms.PasswordResetForm this is the link to the source code https://github.com/django/django/blob/ac2e6e686906810e9c24ca6c39cae6234ab25557/django/contrib/auth/forms.py#L316 three questions: first question(main question): how do u change the default protocol from http to https, So that the user will click the https link instead of http in their email to reset their password ps: i am using django default class based views second question(technical question): the django default reset pass link does not work on safari browser, works on all other browsers why? and is there anything i can do for that? third question(fundamental question): after all these years being an amateur programmer for fun, Its video explanation and stockoverflow copy and paste or Me trying and guessing, doc never helped, i still have no idea how to read the docs, its all there, i have the source code, i have the doc, it does say protocol: http or https and in the source code it does say def save(use_https=False) BUT it does not say how to use it, it does not say where to put protocol:http/https or is it protocol=http/https or is it def protocol..., theres no example, no DO … -
Django Database Routing
I am having 3 databases defined in the Settings.py and routers for two apps in the respective app folders. When I try to run manage.py migrate --database="app_db" respectively for apps, it only runs default and second database list item. If I change the order of database list it won't perform the last one but only second one. Settings.py INSTALLED_APPS = [ # django apps "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # my apps "cred", "dms", # third party apps "rest_framework", ] DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "databases/db.sqlite3", }, "dms_db": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "databases/dms.sqlite3", }, "cred_db": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "databases/cred.sqlite3", }, } DATABASE_ROUTERS = [ "dms.routers.DMSRouter", "cred.routers.CredRouter", ] AUTH_USER_MODEL = "cred.User" CRED_DB_ROUTER = "cred_db" DMS_DB_ROUTER = "dms_db" if I put dms_db at list index 1 then it will migrate but cred_db won't. If I put cred_db at index 1 then it will migrate but dms_db won't. Cred.Router.py from django.conf import settings class CredRouter: route_app_labels = ["auth", "cred", "contenttypes"] def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return settings.CRED_DB_ROUTER return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return settings.CRED_DB_ROUTER return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label … -
Django 'NoneType' object has no attribute '_meta'
any solution for this error 'NoneType' object has no attribute '_meta' Request Method: GET Request URL: http://127.0.0.1:8000/api/register/ Django Version: 3.1.2 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute '_meta' Exception Location: /opt/anaconda3/envs/catermahalENV/lib/python3.8/site-packages/rest_framework/utils/model_meta.py, line 96, in _get_forward_relationships Python Executable: /opt/anaconda3/envs/catermahalENV/bin/python Python Version: 3.8.8 serializers.py class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'name', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user( validated_data['name'], validated_data['email'], validated_data['password']) return user views.py class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, 'token': AuthToken.objects.create(user)[1] }) -
Count branches in queryset
Django==3.2 At a breakpoint I have such queryset: <QuerySet [<UsingSemanticsLevelTwo: 2. Дубаец - 3. green_dubai_TR>, <UsingSemanticsLevelTwo: 2. Дубаец - 2. dubai_TR>, <UsingSemanticsLevelTwo: 1. Вас вызывает Дубай 1 - 4. dubai_COMP>]> Model: class UsingSemanticsLevelTwo(models.Model): branch = models.ForeignKey("clients.Branch", on_delete=models.PROTECT, blank=True, null=True, verbose_name=gettext("Branch"), related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ) Problem I want to count distinct branches in a queryset. queryset.annotate(Count("branch"), distinct=True) It blows up: {TypeError}QuerySet.annotate() received non-expression(s): True. Could you help me? -
How to access the related objects using select_related
I have 3 models as stated below - orders class Orders(BaseModel): created_by = models.ForeignKey(User, on_delete=models.PROTECT, null=False, blank=False) property = models.ForeignKey(Properties, on_delete=models.PROTECT, null=False, blank=False) .... .... properties class Properties(BaseModel): property_long_name = models.CharField(max_length=255, blank=False) property_trading_name = models.CharField(unique=True, max_length=255, blank=False) .... .... property owners class PropertyOwners(BaseModel): property = models.ForeignKey(Properties, related_name='property_owners', on_delete=models.PROTECT, blank=False, null=False) owner = models.ForeignKey(User, on_delete=models.PROTECT, blank=False, null=False) .... .... I am trying to query on Orders and want to put a lock on the rows it will return. I also want to lock the related row of Properties model. Furthermore, those properties will have one or many owners which is stored in model PropertyOwners. I want to lock those rows of ProprertyOwners which are related to the property of that order. So far I have tried to do it like this, but it did not work and returned me an error - Queryset Orders.objects.select_related('property__property_owners').select_for_update().exclude(created_by=created_by).values('id', 'property', 'units', 'created_by', 'sell_price_per_unit', 'order_status').filter(property=order_obj.property, order_type__name=SELL, order_status__in=[PARTIALLY_COMPLETED[1], OPEN[1]], sell_price_per_unit__lte=order_price).order_by('sell_price_per_unit') error - django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'property_owners'. Choices are: property_type, created_by, approved_by, property_manager All the order returned by the queryset will belong to just one property. A property may have one or more many owners. -
How to Debug Django Javascript within VSCode?
I was wondering if there is a solution to Debug Django Javascript with in VSCode. VScode Chrome Debuger seems very popular. Is it possible to use that together with Django server enviorment? untill now i tried following setting in my config: { "name": "Launch Chrome", "request": "launch", "type": "pwa-chrome", "url": "http://localhost:8080", "webRoot": "${workspaceFolder}/path/to/static/files" }, webRoot is the same path as my STATIC_ROOT constant from settings.py Any Ideas? For me the solution does not to be nessesarly the VSChrome-Debugger, I just dont want to debug JS in Chrome directly all the time ^^. Thanks!! -
How to edit custom field in django TabularInline
I have a following inline model under company management. i want to make editable those custom field under company detail page. anyone has a suggestion that how to make editable field 'email', 'name' and 'role'. I will send it to API while submitting. so it's not concern that how to save it. Following is my inline model class CompanyUserInfoTAB(admin.TabularInline): model = Userrolemapping fields = ['id', 'email', 'name','role'] extra = 0 can_delete = False verbose_name = 'COMPANY USERs' verbose_name_plural = verbose_name def email(self, obj): return obj.user.email def name(self, obj): return obj.user.name def role(self, obj): return UserType.objects.get(usr_type_id=obj.role_id).name def company_id(self, obj): return obj.company.id def get_queryset(self, request): qs = super(CompanyUserInfoTAB, self).get_queryset(request) return qs.exclude(mod_id="PSS") Thanks In Advance. -
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.