Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Making a queryset on the same attribute name across multiple models
I have a few models that I want to create a queryset on. The problem is that I have to keep specifying every time what model I want to search for that set attribute every time. Example: I have two models called computer and one called cord. Both share the attribute barcode. (Which Barcode is a foreign key to the Barcode table.) I want to be able to write something like. Computer_Cord.objects.filter(Q(barcode__icontains=barcode)) Instead of Computer.objects.filter(Q(barcode__icontains=barcode)) Really sorry if this already posted out in the stack overflow atmosphere but I am either having trouble finding it or asking the question. Any sort of help would be fantastic. -
how give a default value at username field of User class in python
sorry my english is not very god. That is my problem. i want give by default at username field the value of email field this is my model from django.db import models from django.contrib.auth.models import User class Member(User): class Meta: verbose_name_plural = 'Member' my serializer file thanks -
Cannot run unit-tests with pytest
I have an app with Python 2.7, Django 1.9 and pytest 3.2.5. I try to run unit-tests locally and I am getting that error: AssertionError: Query fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping. I run tests in common way, like: python pytest app_name/tests/test_tasks.py What can be wrong? -
How do to Turn QueryDict into Object?
How do to Turn QueryDict into Object? The result of POST QueryDict is not assembling a json object. You would need to convert this data to better handle. Thank you very much. html <input name="pesquisa[1]item[]"/> <input name="pesquisa[2]item[]"/> view def post(self, request): data = json.dumps(request.POST) return HttpResponse(data, content_type='application/json') Result { "csrfmiddlewaretoken": "txecn4TDkoYtFeS2a9LEKzI4X8MEUgUmgrGFDvOf54oJpV10mjW08aDAjLFgRzO0", "unidade_nome": "--", "pesquisa[1][item]": "", "pesquisa[2][item]": "" } Expected Result { "csrfmiddlewaretoken": "txecn4TDkoYtFeS2a9LEKzI4X8MEUgUmgrGFDvOf54oJpV10mjW08aDAjLFgRzO0", "unidade_nome": "--", { "pesquisa":{[ "item": "", "item": "", ]} } -
Django - Overriding labels is not working with forms ChoiceField
I found a workaround to this problem, but I'm asking it anyways because it was quite odd. I have a model field called agent_title under model Agent. I want to display it on my form as just Title. I need to display the field with ChoiceField. However when I modify the field to be a ChoiceField, the label override stops working. Any reasons why? This works... class AgentInfoForm(forms.ModelForm): class Meta: model = Agent labels = { 'agent_title': 'Title', } But this doesn't class AgentInfoForm(forms.ModelForm): agent_title = forms.ChoiceField(choices=AGENT_TITLE) class Meta: model = Agent labels = { 'agent_title': 'Title', } -
Model if logic not working correctly
Why won't my logic work to verify if a field in my custom user model named formattedusername is equal to a field my QvDatareducecfo model using the def cfo defined below. class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=140) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_cfo = models.BooleanField(default=False) USERNAME_FIELD = 'username' class Meta: app_label = 'accounts' db_table = "user" def save(self, *args, **kwargs): self.formattedusername = '{domain}\{username}'.format( domain='HCA', username=self.username) super(User, self).save(*args, **kwargs); def cfo(self): cfo = self.QvDatareducecfo.cfo_ntname if self.formattedusername == cfo: self.is_cfo = 1 else: self.is_cfo = 0 print (is_cfo) super(User, self).save(is_cfo) # REQUIRED_FIELDS = "username" def __str__(self): return "@{}".format(self.username) I defined the cfo_ntame field as a OneToOneField in the QvDatareducecfo model. I don't receive an error message on my logic and it looks like return is_cfo prints a 0, but if i update the cfo table to a 1 and re-login it doesn't update to a 0 and the user id i'm using isn't listed in the cfo table. -
Django : how to limit the open app?
I have several apps on my django project : DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'django.contrib.gis.db', ] LOCAL_APPS = [ #'cycliste' , #'logger' , 'position' , 'reseau' , 'station' , #'trajet' , #'useful_functions' , 'velo' , #'ville' , ] INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS My url file is : urlpatterns = [ url(r'^', include('reseau.urls')), url(r'^', include('station.urls')), url(r'^', include('velo.urls')), url(r'^', include('position.urls')), ] Now, each app is a rest server. I want to start a different app on each of the servers of my cluster. I see 2 ways to do that : I comment the LOCAL_APPS I don't want on the server I change the urls file, removing the url I don't want to accept The issue is that I have 6 or 7 apps. For each one of them I just want to be able to start a "station" server, or a "logger" server. So I need to dynamically change which app is included in LOCAL_APPS at runtime. I tried to do it through a --settings command, but had no luck. I tried to do it through a specific management.command but without succcess... Finally I think it should be simpler. Maybe a test on the settings … -
Is it possible to access userID of the current LoggedIn user in django.
if user in users_in_group: from django.contrib.auth.models import Group users_in_group = Group.objects.get(name="group name").user_set.all() -
Unable to import path from django.urls
Tried to run command: from django.urls import path Getting error: Traceback (most recent call last): File "< stdin >", line 1, in ImportError: cannot import name 'path' I am using django version (1, 11, 7, 'final', 0) -
serializer returning user_id violates null constraint
I'm trying to add a Invoice object from a json object, where two of the parameters is foreign keys (id's) to Currency and Account. however when i execute i keep getting null value in column "user_id" violates not-null constraint. why am i getting this error when im setting it as PrimaryKeyRelatedField? JSON {'currency': 2, 'task': 1, 'deposit_amount': 1.005, 'receive_amount': 62793.51, 'user': 23} Serializer class InvoiceSerializer(serializers.Serializer): deposit_amount = serializers.FloatField() receive_amount = serializers.FloatField() user = serializers.PrimaryKeyRelatedField(read_only=True) currency = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: """Meta class to map serializer's fields with the model fields.""" model = Invoice fields = ('currency', 'task', 'deposit_amount', 'receive_amount', 'user') read_only_fields = ('created_at', 'updated_at') def create(self, validated_data): return Invoice.objects.create(**validated_data) View class InvoiceViewSet(viewsets.ModelViewSet): lookup_field = 'user' queryset = Invoice.objects.all() serializer_class = InvoiceSerializer def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return (permissions.AllowAny(),) if self.request.method == 'POST': return (permissions.IsAuthenticated(),) return (permissions.IsAuthenticated(),) def create(self, request): request.data['user'] = request.user.id serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.validated_data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
Google Cloud Platform: "cloud_sql_proxy.exe' is not recognized as an internal or external command, operable program or batch file."
I'm currently trying to follow Google's guide for Running Django on App Engine Standard Environment: https://cloud.google.com/python/django/appengine I get to this set of instructions: Start the Cloud SQL Proxy using the connectionName from the previous step. cloud_sql_proxy.exe -instances="[YOUR_INSTANCE_CONNECTION_NAME]"=tcp:3306 Replace [YOUR_INSTANCE_CONNECTION_NAME] with the value of connectionName that you recorded in the previous step. I do this and end up with the message "cloud_sql_proxy.exe' is not recognized as an internal or external command, operable program or batch file." Does anyone know how to fix this? -
Django wagtail adding favicon to root page
I think adding a favicon field for all the page models is not a good way. How can we customize the settings/sites root page to have an image field for favicon? -
Getting started with django-restframework-gis on Windows 10
I have some experience with Python-Django including its REST framework, a reasonable understanding of geographic information (and what GIS is about) and about databases, and I would like to develop a "geo-aware" REST service on my Windows machine based on Django. The application shall be limited to the REST service; visual exploration and other stuff shall be developed independently. Side-remark: once my application is running, it will be ported onto a Linux machine and PostGIS will then be used instead of SpatialLite. After several hours of web-searching, I still haven't come up with a good "Quickstart" guide. There are many tutorials and docs about various aspects related to my task, but they either refer to Linux, or their installation instructions are outdated. Here is what I have done so far: 1) I use miniconda and Pycharm 2) I created a new virtual environment like so: conda create -n locations pip numpy requests activate locations conda install -c conda-forge django djangorestframework djangorestframework-gis 3) I set-up the new Django project and my application and performed a database migration: python [path-to..]\django-admin.py startproject locations cd locations python [path-to..]\django-admin.py startapp myapp cd .. python manage.py migrate 4) I added "rest_framework" and "myapp.apps.MyAppConfig" to the APPLICATIONS … -
Ordering of nested objects using a through model in DRF
i'm using Django rest framework and serialising child objects, but the ordering of the nested objects doesn't seem to be working for me. My models are: ``` class Policy(models.Model): labels = models.ManyToManyField(ClassificationLabel,through='PolicyMemberClassificationLabel') class PolicyMemberClassificationLabel(models.Model): label = models.ForeignKey(ClassificationLabel, related_name='memberLabels') policy = models.ForeignKey(Policy, related_name='parentPolicy') order = models.PositiveSmallIntegerField(blank=True) class Meta: ordering = ['order'] class ClassificationLabel(models.Model): #more model attributes I would like the ordering of the child objects to be based on the order attribute for that model. For example: [ { "displayName": "Policy1", "labels": [ { "displayName": "label1", <=order=1 }, { "displayName": "label2", <=order=2 }, { "displayName": "label3", <=order=3 } ], } ] This isn't working and i'm not getting any sensible ordering for them. I've tried ordering via the model's meta class, and have looked elsewhere on here (like here). I have also tried queries such as returnedPolicy = (Policy.objects.filter(groups__uniqueId__in=allGroups).distinct().order_by('policymemberclassificationlabel__order')[:1]) but these tend to throw FieldErrors. How can I get the returned object to have ordered nested objects based on the through model attribute if i'm querying via the Policy object? -
Push to Heroku failing (Django)
remote: /app/.heroku/python/lib/libpython2.7.a: error adding symbols: Bad value remote: collect2: error: ld returned 1 exit status remote: error: command 'gcc' failed with exit status 1 remote: remote: ---------------------------------------- remote: Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-PyPOxE/mod-wsgi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-Ya8Bxl-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-PyPOxE/mod-wsgi/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy.... remote: remote: ! Push rejected to testapp. remote: To https://git.heroku.com/testapp.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/testapp.git' I've been trying to push my Django website to Heroku for the past 2 days and this is the furthest I've gotten. I keep getting this error when running git push heroku master. I've looked at almost every single thread on SO and other websites regarding these errors and no luck. Any help is greatly appreciated! -
Can't get curl to work on windows properly when calling django
I am attempting to make curl work on windows using a bash script. I'm using the git unix tools to make this work. When I run the script, the token from the first request prints twice, and then the error runs: djangocurl.bash: line 15: -X: command not found LOGIN_URL="https://www.myapi.com/login/" FEEDBACK_URL="https://www.myapi.com/packagefeedback/" YOUR_USER="myemail" YOUR_PASS="mypassword" CURL_BIN1="curl -s $LOGIN_URL" CURK_BIN2="curl -s $FEEDBACK_URL" PACKAGE_ID=$1 FEEDBACK=$2 RATING=$3 RESPONSE=$($CURL_BIN1 -d "email_id=$YOUR_USER&password=$YOUR_PASS" -X POST "$LOGIN_URL" | jq -r '.token') ECHO "$RESPONSE" RESPONSE2=$($CURL_BIN2 -X POST "$FEEDBACK_URL" -H "Authorization: Bearer " + "$RESPONSE" -d "package_id=$PACKAGE_ID&feedback=$FEEDBACK&rating=$RATING") ECHO "$RESPONSE2" Is there something I'm doing wrong? -
Django forloop.counter0 to read a list
read a list in a list in the template with example: a_list = ['a', 'b', 'c', 'd'] new_list = [1, 2, 3, 4] how to access to new_list value in the template {% for value in a_list %} <h2>{{ a_new_list.forloop.counter.0 }}</h2> {% endfor %} i do this and It's not work! -
Django unmanaged model returns empty queryset whereas pgcli is not
I've created a view table in Postgres, which consists of fields (a,b_id,c: date, integer foreign key and decimal) Then I've created Django model: class model(Model): class Meta: managed = False db_table = 'table' a = models.DateField(primary_key=True) b = models.ForeignKey(<>) # also checked with b_id=IntegerField() c = models.DecimalField(max_digits=15, decimal_places=6) Problem is, when I query it via Django ORM, it returns an empty queryset. When I'm running the same exact query in pgcli, it returns the rows I need. I'm pretty much sure the database is the same (checked on other managed models of the app). How do I debug and fix this kind of issue? -
How do I host a Django project on Google Cloud Platform?
I've never seen anything so convoluted, tedious, and non-user friendly in my life...can anyone tell me how I can easily host my Django Project on Google Cloud Platform? Or just link me to a detailed video guide? Thanks. -
Trouble Serving Django Static Files
I'm having a lot of difficulty serving static files using runserver. I've included the configurations below, can someone help? STATIC_URL = '/static/' STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Here is the top of my base.html file: <!DOCTYPE html> {% load static %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> What I have done so far: I have already issued the 'python manage.py collectstatic' command, and only 'admin' static files where placed in the /staticfiles directory. When running the command 'python manage.py findstatic css/style.css --verbosity 3' I get the following results: C:\Users\john.doe\Desktop\sysnet>python manage.py findstatic css/style.css --verbosity 3 No matching file found for 'css/style.css'. Looking in the following locations: C:\Python27\lib\site-packages\django\contrib\admin\static C:\Users\john.doe\Desktop\sysnet> Why is it searching Python27\lib\site-packages\django\contrib\admin\static ? I'm guessing this is is why the collectstatic command did not place files from /static in the /staticfiles? I have included the directory structure below (minus the files), can anybody help? sysnet ├───.idea ├───chef │ ├───migrations │ └───templates ├───static │ ├───css │ ├───img │ └───js ├───staticfiles │ └───admin │ ├───css │ ├───fonts │ ├───img │ │ └───gis │ └───js │ ├───admin │ └───vendor │ ├───jquery │ └───xregexp └───sysnet … -
NoReverseMatch at / Reverse for 'product_list_by_category' with keyword arguments '{'slug': 'legume'}'
Everytime I run my django project, I get this error NoReverseMatch at / Reverse for 'product_list_by_category' with keyword arguments '{'slug': 'legume'}'. I want to list my products and to be honest, I don't even know what the problem is. Full trace: django.urls.exceptions.NoReverseMatch: Reverse for 'product_list_by_category' with keyword arguments '{'slug': 'legume'}' not found. 1 pattern(s) tried: ['(?P\w+)/$'] [29/Nov/2017 22:18:22] "GET / HTTP/1.1" 500 180670 My main URLS from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('shop.urls', namespace = 'shop')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) My Models.py page from django.db import models from django.core.urlresolvers import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=120 , db_index = True) slug = models.SlugField(max_length=200 , db_index = True , unique= True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', kwargs={'slug':self.slug}) class Product(models.Model): category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index = True) slug = models.SlugField(max_length=200, db_index = True) image = models.ImageField(upload_to='products/%y/%m/%d', blank=True) description = models.TextField(blank = True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now= … -
Django post_save: database not yet updated?
I'm writing a Django application for ordering stuff. All orders have a certain type Type. If Type.is_common == true, it needs to be included in a delivery no matter if a user orders this type or not. I'm using a post_save signal to check if my db already has a common order for a user for a certain delivery. Here is the code: @receiver(post_save, sender=Order) def create_common_order(sender, instance=None, created=False, **kwargs): """ This signal handler creates common orders (if delivery type definition contains any common types) for every first order of a user for a certain delivery. """ # Don't handle this if the order is not for a delivery if not created or not instance or not instance.delivery: return # Don't handle Order with common types if instance.type.is_common: return # Loop through all types in type definition of delivery for t in Type.objects.all(): # Look for a 'is_common' type if type.is_common: # Get or create an order with the respective values Order.objects.get_or_create( delivery=instance.delivery, user=instance.user, type=type, defaults={'count':1} ) My problem is the following: From time to time it happens that two common orders are created (if two new orders are created at almost the same time). But why? Is the db … -
Django arguments to run migration in different ways
In my app, I currently have a data migration which uses the Steam API, and takes a few hours to build the database: class Migration(migrations.Migration): def forward(apps, schema_editor): """ Generates Game and Tag entities from the SteamSpy and SteamStore APIs. Takes a long time. Testing should use --keepdb flag. """ print() Game = apps.get_model("game_finder", "Game") Tag = apps.get_model("game_finder", "Tag") multiplayer_tags = {'Multiplayer', 'Local Multiplayer', 'Co-Op', 'Co-op', 'Online Co-Op', 'Local Co-Op', 'Massively Multiplayer'} all_tags = {} print("Generating Games and Tags.") content = get_json_response("https://steamspy.com/api.php?request=all") if content: items_len = len(content.keys()) counter = 0 for appid, game_data in content.items(): counter += 1 game_tags = [] game_multiplayer_tags = [] if game_data['tags']: game_tags = game_data['tags'].keys() game_multiplayer_tags = game_tags & multiplayer_tags missing_tags = game_tags - all_tags.keys() # Creates tags as needed. for item in missing_tags: print("Creating Tag: {}".format(item)) if item in multiplayer_tags: tag = Tag(name=item, is_multiplayer=True) else: tag = Tag(name=item) tag.save() all_tags[item] = tag # Creates Games. game_name = game_data["name"] print("Creating Game: {} ({}/{})".format(game_name, counter, items_len)) if len(game_multiplayer_tags) > 0: price = get_price(appid) game = Game(appid=int(appid),title=game_name,price=price, is_multiplayer=True) game.save() else: game = Game(appid=int(appid), title=game_name) game.save() for key in game_tags: game.tags.add(all_tags[key]) game.save() def backward(apps, schema_editor): """ Deletes all Game and Tag entries. """ Game = apps.get_model("game_finder", "Game") Tag = … -
Django custom User model throwing SystemCheckError - The field 'username' clashes with the name 'username'
I'm writing a custom User model in Django, inheriting it from AbstractUser as is mentioned in the official Django tutorials. But this throws an error. django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: redditauth.RedditUser.username: (models.E006) The field 'username' clashes with the field 'username' from model 'redditauth.reddituser'. Here is the code I wrote for the custom user model. class RedditUser(AbstractUser): username = models.CharField(unique=True, primary_key=True, validators=[validate_reddit_username], max_length=20) token = models.CharField(max_length=256) USERNAME_FIELD = username REQUIRED_FIELDS = ['token'] def reddit(self): with open('secret.json', 'r') as f: secret = json.load(f) return praw.Reddit(client_id=secret['client_id'], client_secret=secret['client_secret'], refresh_token=self.token, user_agent='Plan-Reddit by /u/SkullTech101') I have tried renaming it to something other than username, thinking that maybe there was already field named username in AbstractUser, but that didn't solve the problem. -
Elasticsearch port 9300 django
I'm facing a strange issue, using Django Haystack and ElasticSearch so I can't rebuild_index. ElasticSearch is properly running on the machine : $ curl -X GET 'http://localhost:9200' { "status" : 200, "name" : "Ziggy Pig", "cluster_name" : "elasticsearch", "version" : { "number" : "1.7.2", "build_hash" : "e43676b1385b8125d647f593f7202acbd816e8ec", "build_timestamp" : "2015-09-14T09:49:53Z", "build_snapshot" : false, "lucene_version" : "4.10.4" }, "tagline" : "You Know, for Search" } But this is the log of ElasticSearch : [2017-11-29 18:25:22,723][INFO ][node] [Ziggy Pig] initialized [2017-11-29 18:25:22,724][INFO ][node] [Ziggy Pig] starting ... [2017-11-29 18:25:22,913][INFO ][transport] [Ziggy Pig] bound_address {inet[/127.0.0.1:9300]}, publish_address {inet[/10.142.0.2:9300]} [2017-11-29 18:25:22,937][INFO ][discovery] [Ziggy Pig] . elasticsearch/HWEvbIkAR3mFwcGeHIa7Cg [2017-11-29 18:25:26,710][INFO ][cluster.service] [Ziggy Pig] new_master [Ziggy Pig][HWEvbIkAR3mFwcGeHIa7Cg][stagelighted] [inet[/10.142.0.2:9300]], reason: zen-disco-join(elected_as_master) [2017-11-29 18:25:26,734][INFO ][http] [Ziggy Pig] bound_address {inet[/127.0.0.1:9200]}, publish_address {inet[/10.142.0.2:9200]} [2017-11-29 18:25:26,734][INFO ][node] [Ziggy Pig] started [2017-11-29 18:25:26,762][INFO ][gateway] [Ziggy Pig] recovered [1] indices into cluster_state [2017-11-29 18:26:22,946][WARN ][cluster.service] [Ziggy Pig] failed to reconnect to node [Ziggy Pig][HWEvbIkAR3mFwcGeHIa7Cg] [stagelighted][inet[/10.142.0.2:9300]] org.elasticsearch.transport.ConnectTransportException: [Ziggy Pig][inet[/10.142.0.2:9300]] connect_timeout[30s] at org.elasticsearch.transport.netty.NettyTransport.connectToChannels(NettyTransport.java:825) at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:758) at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:731) at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:216) at org.elasticsearch.cluster.service.InternalClusterService$ReconnectToNodes.run(InternalClusterService.java:584) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: java.net.ConnectException: Connection refused: /10.142.0.2:9300 at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717) at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.connect(NioClientBoss.java:152) at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.processSelectedKeys(NioClientBoss.java:105) at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.process(NioClientBoss.java:79) at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337) at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42) at org.elasticsearch.common.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) at org.elasticsearch.common.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) I installed JAVA and Elastisearch …