Django - MongoDB: (could not connect to localhost:27017) Connection refused - django

I am having issues getting mongodb working with Django, my setup is Mac OS X 10.7. I followed the tutorial available here: http://django-mongodb.org/topics/setup.html . I have tried with both virtualenv and without (this is my first time installing django so I shouldn't have any conflicts).
In settings.py
DATABASES = {
'default' : {
'ENGINE' : 'django_mongodb_engine',
'NAME' : 'my_database'
}
}
In firstapp.models.py
from django.db import models
from djangotoolbox.fields import ListField
class Post(models.Model):
title = models.CharField()
text = models.TextField()
tags = ListField()
comments = ListField()
In my shell (python manage.py shell), I try running:
from mydjango.firstapp.models import Post
post = Post.objects.create();
But I keep getting the following: DatabaseError: could not connect to localhost:27017: [Errno 61] Connection refused (full traceback)
If I switch settings.py to the following:
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': 'my_database',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '27017',
'SUPPORTS_TRANSACTIONS': False,
},
}
I get this error in the shell: ImproperlyConfigured: port must be an instance of int

Did you setup MongoDB separately? The howto you link doesn't seem to go over the MongoDB configuration. It assumes the database is already running. In any case MongoDB seems down, or is at least listening somewhere else.
The last error ("...instance of int") is just because you specified '27017' (a string) instead of 27017 in the configuration dictionary. But even then it should be equivalent to the first, simpler configuration.

In case MongoDB is running but you still get this error while trying to connect from another machine, it may be due to Firewall running on the MongoDB server.
I was running into this exact same error on CentOS 6.5 running MongoDB 2.6.0. Disabling firewall on the machine resolved the issue for me.

If you are creating models at models.py then there is an example below
models.py
from mongoengine import *
class UserLocation(Document):
message = StringField(required=True, max_length=200)
You dont need the sqlite3 if you are not using it and only the mongodb then you have an optio to comment it
settings.py
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
Now in
views.py
from .models import UserLocation
def save_function(request):
msg = "shinto"
# saving the data to the database
data = UserLocation(message = msg)
data.save()
# reading the data
read_data = json.loads(UserLocation.objects().to_json())
print read_data
There is also another method and its very simple (you don't need to create models in models.py)
views.py
from pymongo import MongoClient
client = MongoClient(port=27017)
db = client.testing_db # use a database called testing_db
collection = db.files # inside that db a collection called files
def a_new_function():
fooman = {"name" : "shinto", "age" : 25}
collection.insert(fooman)
# if you need to display only the name "shinto
#cursor = collection.find({"name" : "shinto"})
# if you need to display all then empty
cursor = collection.find({})
for document in cursor:
print(document)
could not connect to localhost:27017 Connection refused or you see 111 is because you haven't either installed or opened mongodb in another terminal
For installation on ubuntu do the following
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
if Ubuntu 12.04 (deprecated) then in terminal
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
if Ubuntu 14.04 then in terminal
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
if Ubuntu 16.04 then in terminal
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
After do
sudo apt-get update
sudo apt-get install -y mongodb-org
After installation then start mongodb
sudo service mongod start
To stop mongodb do
sudo service mongod stop
To restart mongodb
sudo service mongod restart
Finally you can use
mongo --host 127.0.0.1:27017
which will solve the issue
Thank You

From your question it seems like you are trying to use Django with Mongodb. In which case why do you need Mongoengine?
The official Mongodb documentation talks about djongo. It works by translating SQL queries into query documents.
You don't need Mongoengine to run it.
All native Django contrib modules (eg. admin, user, session) work without any modification.
MongoEngine requires rewriting Django modules and last I checked, the native admin module didn't run on MongoEngine.
Your existing models run without any ORM translation as well.

Related

geo django The specified module could not be found

i'm trying to make location based web application with django and sub framework (geodjango) and postgresql - postgis , windows 10
i've also installed GDAL through GDAL-2.4.1-cp37-cp37m-win_amd64.whl,geos, and added this line to settings.py file
GDAL_LIBRARY_PATH = 'C:\\OSGeo4W64\\bin\\gdal111.dll'
and database
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': '...',
'USER':'....',
'HOST':'localhost',
'PASSWORD':'....',
'PORT':'5432',
}
}
but still getting this error while im trying to python manage.py makemigrations/migrate
OSError: [WinError 126] The specified module could not be found
and when i run python manage.py runserver i get this error
LookupError: No installed app with label 'admin'.
I put gdal300.dll as target and that worked.

setting database: postgresql in django 1.8 in heroku

I have been struggling for this issue for the whole days while no solutions at all. so I post it here.
I am trying to set up a blog website in Heroku via Django 1.8 which uses Python 3.4.3. I follows the instructions from Heroku website here.
I use "foreman start" to run Django project in my Mac and I already installed all dependence.
Part of my setting.py file involving the database initially looks like:
import dj_database_url
DATABASES = {}
DATABASES['default'] = dj_database_url.config()
Then I got error: ImproperlyConfigured at /settings.DATABASES is improperly configured. Please supply the ENGINE value.
Then I modify the files by adding one line supplying the ENGINE value:
import dj_database_url
DATABASES = {}
DATABASES['default'] = dj_database_url.config()
DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql_psycopg2'
Based on this post answered by Or Arbel, it should work. But I got another error: ImproperlyConfigured at /settings.DATABASES is improperly configured. Please supply the NAME value.
What should I do next? Actually my Django project is very simple and does not involve any database operations(may need in the future). I just want to make it works on Heroku. Thanks!
Do I need to create a database to continue? I just want to make the webpage works.
Thanks for your guys help, specially souldeux.
Update:
I have fixed the issue by using souldeux's method by providing more informations about the database. Here I want to emphasis that it seems the code from the original Heroku tutorial does not work for Django 1.8:
import dj_database_url ####not working for my case
DATABASES = {}
DATABASES['default'] = dj_database_url.config()
Initially I did not create a database because I think it is not necessary for simple projects, based on my understanding obtained from Heroku tutorial. Actually it does need to create a database in Heroku to make it works. The tutorial is here. You need run "heroku config -s | grep HEROKU_POSTGRESQL" to get the database information. The format is like:
scheme://username:password#host:port/database
So you can get 'database', 'username', 'password', etc.
Afterwards, modify the 'settings.py' according to souldeux, then run following codes:
git add .
git commit -m "Ready to go to Heroku"
git push heroku master
heroku run python manage.py syncdb
Now it works. But other issues arise like my webpages do not show images... Anyway it solved. Please confirm my solutions, thanks.
I think you need to add more information to your database definition. For instance, here's what my own database entry looks like in my settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'redacted',
'PASSWORD': 'redacted',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
If you don't have a database user and password to enter in the fields marked redacted then you need to make sure you have the actual database created and psycopg2 installed.

Django Haystack ElasticSearch InvalidJsonResponseError: <Response [404]>

I'm using Django and the Haystack module to create a search engine. I want to use ElasticSearch. I have installed it and launched it with:
$ brew install elasticsearch
$ elasticsearch -f -D es.config=/usr/local/Cellar/elasticsearch/0.90.2/config/elasticsearch.yml
My settings seem correct and work:
# Haystack configuration
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://127.0.0.1:8000/',
'INDEX_NAME': 'haystack',
},
}
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
Here is my search indexes:
from haystack import indexes
from account.models import Profile
class ProfileIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
first_name = indexes.CharField(model_attr='first_name')
last_name = indexes.CharField(model_attr='last_name')
def get_model(self):
return Profile
and my profile_text.txt:
{{ object.first_name }}
{{ object.last_name }}
Everything seems correct I guess, I follow the documentation and this tutorial.
But now, when I'm triggering:
$ python manage.py rebuild_index
I get this error:
pyelasticsearch.exceptions.InvalidJsonResponseError: <Response [404]>
If someone knows why? :)
Thank you.
You're running the Elastic Search Server on the same port as the Django Server is running on.
Change the port from 8000 to something else, and then it'll work!

OperationalError could not connect to server

I put a Django app on Heroku recently. The home page looks fine, but when I try to go to a page that involves making a query (e.g. p = Photo.objects.get(title=title)), I get this error:
could not connect to server: Connection refused
Is the server running on host "localhost" and accepting
TCP/IP connections on port 5432?
In accordance with this answer, I did $ heroku pg:promote HEROKU_POSTGRESQL_GREEN_URL
Then in my settings.py:
DATABASES = {'default': dj_database_url.config(default=os.environ['DATABASE_URL'])}
Still got the same error, so I tried looking at the results of this (as this answer suggests):
$ heroku run python manage.py shell
>>> from django.conf import settings
>>> print settings.DATABASES['default']
{'TIME_ZONE': 'UTC', 'TEST_MIRROR': None, 'NAME': 'snorthway', 'OPTIONS': {},
'HOST': 'localhost', 'TEST_NAME': None, 'PASSWORD': '******', 'ENGINE':
'django.db.backends.postgresql_psycopg2', 'PORT': '', 'USER': 'snorthway',
'TEST_COLLATION': None, 'TEST_CHARSET': None}
At which point I realized I don't know what I should even be looking for in that. I still don't understand what the error means, so I am unsure how to go about debugging it.
You have not configured your django database correctly in settings.py. It thinks your database is on localhost. Sounds like you have a heroku postgres database so your host should be something like:
df3-64-304-50-250.compute-1.amazonaws.com
Heroku exposes a special database URL through an environment variable called:
DATABASE_URL
There is a very cool python package here called dj_database_url: https://github.com/kennethreitz/dj-database-url it converts that environment variable to what django expects.
you can install it with:
$pip install dj-database-url
I use the following in my settings.py
import dj_database_url
DATABASES = {
'default': dj_database_url.config()
}

django oracle inspectdb failure

i'm using django 1.3. i have an existing oracle database (10g) i would like to build Model's from using inspectdb.
'db': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'DBNAME',
'USER': 'me',
'PASSWORD': 'something',
}
so when run inspectdb i get:
$ python manage.py inspectdb --database db
cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle
so i add
$ export ORACLE_HOME=/usr/oracle/
$ TWO_TASK=DBNAME
i try logging on with sqlplus with the same credentials and everything looks good.
so... i run inspectdb again, but this time i get
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'
# into your database.
from django.db import models
(ie it's blank)
any ideas? i had no problems getting this to work on a mysql database.
From the official docs.
inspectdb works with PostgreSQL, MySQL and SQLite. Foreign-key detection only works in PostgreSQL and with certain types of MySQL tables.
There is currently not a bug listed for it in the Django tracker if you wanted to submit it.
I have a similar setup at the top of my settings.py to set my environment variables for my oracle driver (Oracle 11.2). Not sure if this will help in your specific case.
### SETTING UP THE ENVIRONENT FOR OUR ORACLE RPM
import os
os.putenv('ORACLE_HOME', '/.../oracle/11.2')
os.putenv('LD_LIBRARY_PATH', '/.../oracle/11.2/lib')
I have had no issues with manage.py inspectdb (Django 1.2.7 and Django 1.4) on Oracle 11.2.