Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I generate Python graphs on web using Django?
My project is Salary Prediction System which predicts salary of an employee on the basis of their experience. Linear regression ML model is used. I am making interface of this project.I am facing difficulty in generating graphs of python on web using Django. The idea is user will upload it's csv file and on the basis of which graphs are generated on the web. Can anyone help ? -
error: failed to push some refs to 'https://github.com/E-wave112/myadmissionportalsite2.git'
I am trying to push my django files and folders to my git repository through git on the command line the steps i took to push my files are: git init git add --all git commit -m "my message" git remote add origin (remote url) and finally git push -u origin master and i then get this error: ! [rejected] master -> master (fetch first) error: failed to push some refs to 'https://github.com/E-wave112/myadmissionportalsite2.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. itried possible solutions but i got nothing how can i fix this problem? -
Django test runner not respecting unittest.TestCase?
For one of my functional tests, I decided to use unittest.TestCase instead of a Django test class because it was convenient when cleaning up the test to have direct access to my local development database in the test itself. Running the test in isolation like so passes as I'd expect: $ python manage.py test functional_tests.test_functionality System check identified no issues (0 silenced). ... ---------------------------------------------------------------------- Ran 3 tests in 0.040s OK When I try to run all tests at the same time, however, that test specifically errors out, complaining that an object DoesNotExist, as though it were using the Django test database: $ python manage.py test functional_tests Creating test database for alias 'default'... System check identified no issues (0 silenced). ..................E.. ====================================================================== ERROR: some_functional_test (functional_tests.test_functionality.FunctionalTest) ---------------------------------------------------------------------- Traceback (most recent call last): ... etc. app.models.Object.DoesNotExist: Object matching query does not exist. ---------------------------------------------------------------------- Ran 21 tests in 0.226s FAILED (errors=1) Destroying test database for alias 'default'... I assume the error is with my trying use Object.objects.latest('created') when no Objects exist in Django's test database. Is there some way to prevent Django from wrapping all tests in whatever it is about the test runner that prevents my test from accessing an Object directly? -
WebSocket disconnect received unexpectedly by using Django Channels
Using Django channels to update the user on the current status of a potentially long running task, I'm facing a WebSocket DISCONNECT that I would like to trace down. The setup looks pretty straight forward. settings.py defines the channel layer: ASGI_APPLICATION = "config.routing.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } In routing.py we basically follow the default suggestion from the Channels doc (the pattern is simply matching a UUID, which we use as public facing identifier): from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.conf.urls import url from lektomat.consumers import analysis application = ProtocolTypeRouter({ # (http->django views is added by default) "websocket": AuthMiddlewareStack( URLRouter([ # Use a regex to match the UUID as the Django version with its '<uuid:analysis_id>' does not work for Channels. url(r"^ws/analysis/(?P<analysis_id>[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12})/$", analysis.AnalysisConsumer), ])), }) The consumer does not much more than sending some initial data via a newly established websockets connection and logging info all over the place: import logging import json from channels.db import database_sync_to_async from uuid import UUID from typing import Tuple from django.utils import timezone from channels.generic.websocket import AsyncWebsocketConsumer from myapp.models import AnalysisResult logger = logging.getLogger(__name__) class AnalysisConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, … -
Getting Date Widget to Display American Dates for American Users
I can use this code to detect if the user is in America ip, is_routable = get_client_ip(request) ip2 = requests.get('http://ip.42.pl/raw').text if ip == "127.0.0.1": ip = ip2 Country = DbIpCity.get(ip, api_key='free').country widgets.py If the user is American I want to pass information to the template bootstrap_datetimepicker.html. I am really unsure how to add information about the users country to the below code (which I got from another website). class BootstrapDateTimePickerInput(DateTimeInput): template_name = 'widgets/bootstrap_datetimepicker.html' def get_context(self, name, value, attrs): datetimepicker_id = 'datetimepicker_{name}'.format(name=name) if attrs is None: attrs = dict() attrs['data-target'] = '#{id}'.format(id=datetimepicker_id) # attrs['data-target'] = '#{id}'.format(id=datetimepicker_id) attrs['class'] = 'form-control datetimepicker-input' context = super().get_context(name, value, attrs) context['widget']['datetimepicker_id'] = datetimepicker_id return context bootstrap_datetimepicker.html I want to run a different JQuery function for American users. {% if America %} <script> $(function () { $("#{{ widget.datetimepicker_id }}").datetimepicker({ // format: 'DD/MM/YYYY/YYYY HH:mm:ss', format: 'MM/DD/YYYY', changeYear: true, changeMonth: false, minDate: new Date("01/01/2015 00:00:00"), }); }); </script> {% else %} <script> $(function () { $("#{{ widget.datetimepicker_id }}").datetimepicker({ // format: 'DD/MM/YYYY/YYYY HH:mm:ss', format: 'DD/MM/YYYY', changeYear: true, changeMonth: false, minDate: new Date("01/01/2015 00:00:00"), }); }); </script> {% endif %} -
FOREIGN KEY constraint failed, why am I getting this error?
I'm creating a blog and right now I'm working in the comments section, I'm working in the edit comments, everything works right, but the problem is the following, whenever I update the view I want to redirect to the blog post were I commented, but whenever I do this, I receive the error in the title here's the code: models.py Here I want to redirect the same way how I do it in the Post Model, which redirects to the article details class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank = True, upload_to = 'images/') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank = True, null = True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name = 'blog_posts') def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('app1:article-detail', args=(self.id,)) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) def get_absolute_url(self): return reverse('app1:article-detail', args=(self.id,)) views.py In both of these views, is were I want to redirect to the article details were all the comments … -
Scheduling Weekly Django Commands for AWS ECS Docker Deployment
I have a Django project in a Docker container that is being deployed to AWS Elastic Container Service. I would like to have a Django command execute on a weekly basis, but I am unsure what is the best practice for doing this. Is this something I can/should set up as part of the Docker/Django project itself? Would I be better using something like AWS Lambda or Batch to schedule this? If so, which service would be better for this purpose and how can I execute the command from within the Docker container? -
'WSGIRequest' object has no attribute 'user' Django 3.0
I'm trying to upload my application to Heroku but I got an error 500. So I enabled the DEBUG = True to see the error and it is 'WSGIRequest' object has no attribute 'user' This is my middleware configuration MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] and this is my wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rwaapi.settings') application = get_wsgi_application() By the way, I already tried changing MIDDLEWARE to MIDDLEWARE_CLASSES and it didn't work either. If you need to know anything else, please let me know. -
Returning Django template variables to HTML in other ways than in a template?
I have the following function in my views.py: def get_html(request, id): text = callAPI(request) return HttpResponse(text) and in urls.py path('get_html/', get_html) If the text that is returned in the view is text = callAPI(request) print(text) --> "<html><body>{{ request.user }}</body></html>" Why when I pull up "example.com/get_html/ does it show the text "{{ request.user }}" and not the users username? Do Django variables referenced using "{{ x }}" only appear if they are in a render() function? I ask this question not because I want this functionality, but rather for security purposes and whether someone can include a {{ x }} pattern in an HTML to leak information. Unvalidated HTML is not to be trusted for other reasons, but I would like to know about this potential vulnerability in particular. -
localstorage size expected problem on saving large data
iam developing a music site with django and react which you can save your songs and playlists i want to save the playlist which was playing before the refresh...iam saving the current song(name,file,id,image) only in the localstorage so the question is ,will be any problems saving all of the playlist in localstorage ? or there is another way to handle it? const handleEnd=()=>{ let songId=props.currentSong.id || localStorage.getItem('id') let currentIndex=props.songs.findIndex(track=>track.id===songId) if (props.songs[currentIndex] === props.songs.length-1 ){ currentIndex=0 props.setCurrentSong(props.songs[currentIndex].id) } else{ const next=currentIndex+1 if(next >= props.songs.length-1){ currentIndex=-1 } else{ props.setCurrentSong(props.songs[next].id) } } } const handleNextPrev=(np)=>{ let songId=props.currentSong.id || localStorage.getItem('id') let currentIndex=props.songs.findIndex(song=>song.id===songId) if(np==='next') { if (currentIndex === props.songs.length-1 ) { currentIndex=0 props.setCurrentSong(props.songs[currentIndex].id) }else{ const next=currentIndex+1 props.setCurrentSong(props.songs[next].id) } } else if(np==='prev') { if (currentIndex === 0 ) { console.log(currentIndex); props.setCurrentSong(props.songs[props.songs.length-1].id) } else { console.log(currentIndex); const previous=currentIndex-1 props.setCurrentSong(props.songs[previous].id) } } } those two functions which i use to loop through the playlist if i refresh i lose all data but the current track only -
How Do I Bring up a page that shows only the items associated with a specific group from a sidebar
I have a sidebar with dynamically generated items of a specific group. "Sidebar" Active Directory Analytics Databases when the sidebar item is selected you are taken to the template for the group groups_list/(id#) Right now when ever I am taken to groups_list/(id#) it shows me all of my queried items but I want it to only show the items associated with that specific group. I have tried playing around with the primary keys and for loop to no success I cannot seem to figure out how to target only the group id from the Empowerment Model. Any help would be appreciated. models.py class Group(models.Model): group = models.CharField(max_length=200, null=True) def __str__(self): return self.group def get_absolute_url(self): return reverse('groups_list', args=[str(self.id)]) class Publisher(models.Model): publisher = models.CharField(max_length=200, null=True) def __str__(self): return self.publisher class Empowerment(models.Model): title = models.CharField(max_length=200, null=True) group = models.ForeignKey(Group, null=True, on_delete= models.SET_NULL, help_text='select a group for this Empowerment') publisher = models.ForeignKey(Publisher, null=True, on_delete= models.SET_NULL, help_text='select a Publisher for this Empowerment') overview = models.TextField(max_length=1000, help_text='Enter a brief overview of the Empowerment', null=True) problem_to_solve = models.TextField(default='', help_text='Enter the problem this Empowerment helps to solve', null=True) empowerment_benefits = models.TextField(default='', help_text='Enter the benefits of this Empowerment', null=True) empowerment_Image = models.ImageField(default='', upload_to='images/') def __str__(self): return self.title def get_absolute_url(self): … -
How to be sent to another html page if a click a link in home page
i am creating a website that in home page will have some gif images, and when one of those images is clicked i want to be sent to another html page with the details of clicked picture. Details are stored in django database in 4 def or functions(entry,middle,finish, and the gif).I can create 9 html pages containing details of the picture but i know there is a shorter way. -
How to annotate queryset with number of common IDs in ManyToManyField
I've got following models: class Ingredient(models.Model): id = models.CharField(primary_key=True, max_length=24) name = models.CharField(max_length=100) class Recipe(models.Model): id = models.CharField(primary_key=True, max_length=24) name = models.CharField(max_length=100) ingredients = models.ManyToManyField(to=Ingredient) and a list with valid Ingredients IDs, like for example: ing_id_list = ['5d481cf3abe2d800150de7b6', '5c8c05bee3f3391eda4320b2', ...] I'm stuck in building a queryset with an annotated field that enriches recipes with the number of common related Ingredients IDs and the IDs in the list: annotated_recipe_queryset = Recipe.objects.annotate(no_of_common_ings=Count(##PLEASE HELP##)) Can anyone help? -
React is adding / before query string
My URI and query string has the below format, and as you can see this morning it was working. [api-deployment-dev-6b4f758c54-8rwxt api] [10/Aug/2020 10:44:22] "GET /survey/129/results/advanced_query?startingPage=12&dataView=By%20Position HTTP/1.1" 200 2 For some reason it quit working despite these being the only two files I've changed today and I haven't been able to get it working again. I now keep getting the following: [api-deployment-dev-7cf59c8b8-b6p4k api] Bad Request: /api/survey/129/results/advanced_query/ [api-deployment-dev-7cf59c8b8-b6p4k api] [10/Aug/2020 12:38:54] "GET /survey/129/results/advanced_query/?startingPage=12&dataView=By%20Position HTTP/1.1" 400 0 It seems like react is adding the / before the query string. Why, I'm not sure because it wasn't doing it this morning. How do I prevent this from happening? import React, { useState } from "react"; import { Button, InputGroup, InputGroupText, InputGroupAddon, Input, } from "reactstrap"; import axios from "axios"; const AdvancedQuerySurveyDataView = ({ surveyDataView }) => { const [startingPage, setStartingPage] = useState(null); const [option, setOption] = useState(); const handleClick = async () => { const result = await axios({ url: `/api/survey/${sessionStorage.getItem( "survey_id" )}/results/advanced_query?startingPage=${startingPage}&dataView=${option}`, method: "get", headers: { "Content-Type": "application/json", Authorization: "Bearer " + sessionStorage.getItem("token"), }, }); }; return ( <div className="results-position-list"> <h5> <b>Select Survey Data View to Print</b> </h5> <select onChange={(e) => setOption(e.currentTarget.value)} id="position-list" className="form-control" > <option></option> {surveyDataView.map(({ surveydataview, min }) => ( <option … -
How to solve "(index):1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 1"?
I'am working on a Ecommerce problem and am stuck in this error for long ang tried every little aspect to solve the problem but couldn't find any clue to solve this problem. This is a a catagory from JQuery in Django "cart.js" that i have showing below: var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser'){ console.log('User is not authenticated') }else{ **updateUserOrder(productId, action)** } 16 }) 17.} 18. 19.function updateUserOrder(productId, action){ 20. console.log('User is authenticated, sending data...') 21. 22. var url = '/update_item/' 23. 24. fetch(url, { 25. method:'POST', 26. headers:{ 27. 'Content-Type':'application/json', 28. 'X-CSRFToken':csrftoken, 29. }, 30. body:JSON.stringify({'productId':productId, 'action':action}) 31. }) 32. .then((response) => { 33. return response.json(); 34. }) 35. .then((data) => { 36. location.reload() 37. }); 38.} In my browser's (chrome) Console catagory, the error is pointing out in 14 and 35th line that im unable to find syntatic error. Please help me out of this. And my ide is vscode. -
cant get html form to communicate with post method in django DRF APIView
I could use some help with a integrating django rest API. I'm stuck trying to get raw HTML forms to communicate to APIView in django and also need help figuring out how to integrate an encrypting API to fields to secure credit card number, exp date and cvv. i cant get the HTML page to invoke the post method in views.py views.py ''' from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import get_object_or_404, render, redirect from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.renderers import TemplateHTMLRenderer, JSONRenderer from rest_framework import status from rest_framework.decorators import api_view from rest_framework.decorators import APIView from . models import creditCardInfo from . serializers import creditCardInfoSerializer import requests from django.views.decorators.csrf import csrf_exempt from django.template import loader def post(self, request): if request.method == "POST": a = request.POST.get('tag', 'default') print("printing", a) print(request.POST) return HttpResponse("Hello") class index(APIView): def get(self, request): return render(request, 'index.html') class creditCardList(APIView): def get(self, request): creditCard1 = creditCardInfo.objects.all() serializer = creditCardInfoSerializer(creditCard1, many=True) return Response(serializer.data) def post(self, request): creditCard1 = creditCardInfo.objects.all() serializer = creditCardInfoSerializer(data=creditCard1) if serializer.is_valid(raise_exception=True): serializer.save(response) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) '''''' Outbound connection ''' os.environ['HTTPS_PROXY'] = 'https://USi6vXVNrcsBYnpCMB7GciTg:2da52565-6e72-4a46-b419-245764f128ae@tntzrhiqrtg.SANDBOX.verygoodproxy.com:8080' res = requests.post('https://echo.apps.verygood.systems/post', json={'add_message': message}, verify='/full/path/to/cert.pem')''' index.html ''' {% extends "base.html" %} {% block content … -
Handling session-based authentication between Node.js and Django
This may edge upon a "best practice" type of question, but I'd like to explain my approach, list out my hypotheses and get constructive feedback. Currently my setup consists of two servers; Node.js frontend server running Sapper/Svelte on localhost:3000 and a Django (not DjangoRestFramework), backend running on localhost:8000. My Django sessions are being cached using django.contrib.sessions.backends.cached_db to a locally running Redis instance. I am handling my User model using views and urls I've defined in a Django app. While building authentication; I am following the approach Run a fetch() POST'ing to locahost:8000/login or signup, using Django's authenticate, login, and User.* to create sessions. Then I return the session_key and email to the front-end which then sends these in the body for any request which may require authentication. In the backend, I match the session_key to the user_id using the e-mail sent to me in the request body to check if the session is valid. Now since I have always used Django Templating, I hadn't had to ever maintain a separate session instance or had to think about sharing sessions. I feel this approach could be more python-ic? At this stage, I've also had all the models, migrations done, this approach … -
git push heroku master in django working fine yet app crashed Code in Django
The whole project is available in this drive link This projects works perfectly fine when I executed it on my local host When trying to deploy on heroku I get app crashed and when I run (heroku logs -- tail) the following error message was displayed as shown below . (Note I didnt change the secret key because I felt it wasn't Important in the current state of the project as this is only for the educational/development purpose so please kindly take that into consideration ) . Kindly help ! 2020-08-10T17:58:57.717239+00:00 app[web.1]: [2020-08-10 17:58:57 +0000] [10] [ERROR] Exception in worker process 2020-08-10T17:58:57.717284+00:00 app[web.1]: Traceback (most recent call last): 2020-08-10T17:58:57.717286+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-08-10T17:58:57.717288+00:00 app[web.1]: worker.init_process() 2020-08-10T17:58:57.717288+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-08-10T17:58:57.717288+00:00 app[web.1]: self.load_wsgi() 2020-08-10T17:58:57.717289+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-08-10T17:58:57.717289+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-08-10T17:58:57.717291+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-08-10T17:58:57.717291+00:00 app[web.1]: self.callable = self.load() 2020-08-10T17:58:57.717291+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-08-10T17:58:57.717291+00:00 app[web.1]: return self.load_wsgiapp() 2020-08-10T17:58:57.717292+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-08-10T17:58:57.717292+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-08-10T17:58:57.717292+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app 2020-08-10T17:58:57.717292+00:00 app[web.1]: mod = importlib.import_module(module) 2020-08-10T17:58:57.717292+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/importlib/init.py", line 127, in … -
How do I secure a static HTML file in Django? (Make login required before redirecting)
I am using Django Admin interface to allow the admin to upload html files, which will then be stored in 'static/notebooks/file_name'. With the code below I am able to redirect, however how do I make login required and check for user permissions before redirecting? I can't use login required decorator since the static html file does not have a view or template associated with it. <button type="button" class="btn btn-secondary btn-lg btn-block" style="margin: 1rem;"onclick="location.href='{% static 'notebooks/BrightspaceGradebookUsage.html' %}'">Python notebooks</button> -
LookupError: No installed app with label 'communication'
While running django server i am getting this error. LookupError: No installed app with label 'communication' -
Environment variables in django and heroku, how safe are they?
I'm new to web-dev and especially to security, so I'm wondering, after reading article after article about using environment variables in django + heroku-projects, how safe are they really? Can someone unauthorised get a hold if these variables? If so, how can we avoid exposing sensitive information included in an app? -
(django)TemplateDoesNotExist at /
urls.py from django.urls import path, include urlpatterns = [ path('', include('calc.urls')), path('admin/', admin.site.urls), ] views.py from django.shortcuts import render def home(request): return render(request, 'tmpl/home.html') settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'tmpl')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, folder It looks like your post is mostly code; please add some more details. -
Django - querying 2 tables with a many to many mapping table
If i have two tables people and fruits with a third table that maps a many to many relationship between the two. PEOPLE TABLE id person 1 bob 2 alice FRUITS TABLE id fruit 1 apple 2 pear 3 orange 4 grapes PEOPLE_FRUITS_MAP id person_id fruit_id 1 1 1 2 1 3 3 1 4 4 2 1 How would I get a Django QuerySet containing the names of all the fruits related to bob for example. I guess in SQL it would be something like: SELECT fruits.id AS fid, fruits.name AS fn, FROM people LEFT JOIN people_fruits_map ON people.id = people_fruits_map.person_id LEFT JOIN fruits ON fruits.id = people_fruits_map.fruit_id WHERE person.id = 1; result of query fid fn -------------- 1 apple 3 orange 4 grapes -
Django Mysql Data Processing Method
I have a django Mysql Application using rest frame work and front end as Angular with mobile Application .. My System Work flow Service Providers will register through our webapplication and they can add their services to our web application .. Mobile Application is for the customers , they can request service through online .. Service providers can view customers request and process and send the status back ... It is working good with 12k+ Downloads and more than 600 service providers registered. I want to add new requirement to enter their daily activity and accounts to integrate with this. Is it possible to manage their data request through single mysql db? or any structure suggestion.. I am hosted in digital ocean cloud vps. I thought to create a individual db for each service provider and dynamically change during the login time .. But is it a good idea to do mutiple db configuration in django or is it possible to host this much db ? or is it bad idea? we need to expect 200+ daily entry from one service provider ... -
Elastic search bool query sort by date if status is true
I have a json like as follows in elastic search index. How to sort data if advertisement does not expire and status is true then sort them as desc. How can I achieve this? I tried using end_date sort but it did work. Also i need to show all expired data which end_date are expired. advertisement = [ { "id": 1, "name": "test", "status": True, "start_date": "2020-08-09", "end_date": "2020-09-09", }, { "id": 2, "name": "test2", "status": False, "start_date": "2020-08-09", "end_date": "2020-08-09", }] This is my elastic search method. def elastic_search(category=None): client = Elasticsearch(host="localhost", port=9200) query_all = { 'size': 10000, 'query': { "bool": { "filter": [ { "match": { "name": "test" } }] }, }, "sort": [ { "end_date": { "type": "date", "order": 'desc' } } ] } resp = client.search( index="my-index", body=query_all ) return resp