I've installed django-notifications via pip, added the app to my INSTALLED_APPS:
INSTALLED_APPS = (
'django.contrib.auth',
...
'notifications',
...
)
Updated my URLConf:
import notifications
urlpatterns = patterns('',
...
('^inbox/notifications/', include(notifications.urls), namespace='notifications'),
...
)
Since I have south installed, I migrate the schema:
$ python manage.py migrate notifications
...
...
$ python manage.py migrate --list
notifications
(*) 0001_initial
(*) 0002_auto__add_field_notification_data
(*) 0003_auto__add_field_notification_unread
(*) 0004_convert_readed_to_unread
(*) 0005_auto__del_field_notification_readed
(*) 0006_auto__add_field_notification_level
...
Now, I'm trying to manually create a notification via Django shell but I'm getting an IntegrityError:
[1]: from django.contrib.auth.models import User
[2]: from notifications import notify
[3]: recipient = User.objects.get(username="admin")
[4]: sender = User.objects.get(username="guest")
[5]: notify.send(sender, verb='A test', recipient=recipient)
...
...
...
IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`myapp`.`notifications_notification`, CONSTRAINT `recipient_id_refs_id_5c79cb54` FOREIGN KEY (`recipient_id`) REFERENCES `auth_user` (`id`))')
What's going on? Both, recipient and sender belong to auth_user table. Any help will be much appreciated.
Ok, I found the problem. For some reason south was using InnoDB storage engine as a default while all my tables have MyISAM as a default. This is how I fixed it:
Drop table notifications_notification
Delete all entries of notifications on south_migrationhistory table so you can migrate notifications again later
Add STORAGE_ENGINE to my database settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'database',
'USER': 'user',
'PASSWORD': 'pass',
'HOST': '',
'PORT': '',
'STORAGE_ENGINE': 'MyISAM',
}
}
Finally, migrate notifications again:
$ python manage.py migrate notifications
Related
I am developing a Django application and I have created a MySQL database (I am using Laragon to manage it) and connected it with the App. I am using the database for another Python script that inserts data in the database too. What I want it to see all the database data in my Django admin site, but for some reason, I can't manage to do it? Do I have to add the tables to the Django models? or what should I do?
My settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'nlpwords',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': 3306,
}
}
I am using that database that has some data in some of the tables, but when I enter localhost/admin in my Django app I can't manage to see all those tables. Help is much appreciated.
To see your Django apps in your admin portal, you need to register them in admin.py.
Example:
# admin.py
from django.contrib import admin
from .models import *
admin.site.register(ModelName)
Note: if you just made a new app and recently created models, make sure to run makemigrations and migrate so it gets registered to the db first.
We are a small team, trying to work with Django with a restricted access to a futurely unmanaged PostgreSQL database (i.e: only views and stored procedures ; no access to any tables) for security reasons.
We tried to give (within Postgre) the user external_test the rights to create any tables inside his own schema on external, and to use the following settings (settings.py):
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'external': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgre_db',
'USER': 'external_user',
'PASSWORD': 'password',
'HOST': 'integration.project.net',
'PORT': '5432',
'TEST': {
'NAME': 'test_db',
'USER': 'external_test',
'PASSWORD': 'password',
...
Using simple passing unit tests (project/app/tests/test_views.py):
...
class InternalTest(TestCase):
database = ['default']
def test_something(self):
pass
class StoredProcedureTest(TestCase):
databases = ['external']
def test_one_procedure(self):
with connections["external"].cursor() as cursor:
cursor.callproc("some_procedure", [42, ])
pass
...
If we try the first one with ./manage.py test app.tests.test_views.InternalTest
→ ok
If we try the other one with ./manage.py test app.tests.test_views.StoredProcedureTest
→ circular dependency issue
(ImproperlyConfigured: Circular dependency in TEST[DEPENDENCIES])
probably because it's skipping the configuration of default
If we try both tests with ./manage.py test app.tests.test_views:
→ permission denied
Creating test database for alias 'default'...
Creating test database for alias 'external'...
Got an error creating the test database: permission denied to create database
(Django try to create a database test_db as the user external_user)
We don't really get what Django is trying to do and how to properly configure it.
If we give the rights to external_user to create their own databases:
the database test_db is created by external_user
the schema of default (sqlite) is created in test_db of external (postgre)
the schema of external (postgre) is not created in test_db
Questions
Is django able to handle this ?
What are we doing wrong ?
What is the point of specifying a user external_user for TEST if in the end django is using the normal user external_user ?
Why does it write the schema of default in test_db ? Is there a way to create only models of some apps in it ?
Why isn't it able to create the schema of external in test_db ?
I hope it was described enough. Thank you in advance for your responses =)
I want to migrate from sqlite3 to MySQL in Django. First I used below command:
python manage.py dumpdata > datadump.json
then I changed the settings of my Django application and configured it with my new MySQL database. Finally, I used the following command:
python manage.py loaddata datadump.json
but I got this error :
integrityError: Problem installing fixtures: The row in table
'django_admin_log' with primary key '20' has an invalid foregin key:
django_admin_log.user_id contains a value '19' that does not have a
corresponding value in auth_user.id.
You have consistency error in your data, django_admin_log table refers to auth_user which does not exist. sqlite does not enforce foreign key constraints, but mysql does. You need to fix data and then you can import it into mysql.
I had to move my database from a postgres to a MySql-Database.
This worked for me:
Export (old machine):
python manage.py dumpdata --natural --all --indent=2 --exclude=sessions --format=xml > dump.xml
Import (new machine):
(note that for older versions of Django you'll need syncdb instead of migrate)
manage.py migrate --no-initial-data
Get SQL for resetting Database:
manage.py sqlflush
setting.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'asdf',
'USER': 'asdf',
'PASSWORD': 'asdf',
'HOST': 'localhost',
#IMPORTANT!!
'OPTIONS': {
"init_command": "SET foreign_key_checks = 0;",
},
}
python manage.py loaddata dump.xml
In my new Django project I set up a MongoDB database and use mongoengine module
but I can't properly access the dabase neither in shell nor in views.
"ConnectionError: You have not defined a default connection"
My settings.py includes the following:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DaTaBaSe',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
},
'tracking': {
'ENGINE': 'django.db.backends.dummy',
'NAME': 'analytics',
}
}
import mongoengine
SESSION_ENGINE = 'mongoengine.django.sessions'
mongoengine.connect(_MONGODB_NAME, 'localhost:27017')
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
In models.py:
import mongoengine
from mongoengine import *
from myproject.settings import _MONGODB_NAME
mongoengine.connect(_MONGODB_NAME, 'localhost:27017')
I have not tested this in-depth, but so far it worked for me:
mongoengine.connect('yourdb', alias='default')
In your settings.py file replace:
mongoengine.connect(_MONGODB_NAME, 'localhost:27017')
with the below code (notice the added 'host='):
mongoengine.connect(_MONGODB_NAME, host='localhost:27017')
To use django with MongoDB do not use the django package available on https://www.djangoproject.com and install other packages like mongoengine, if follow this process you will find lot of difficulties.
Rather you need to use the no#rel version of django that has been forked from djangoproject and added MongoDB support and I am sure it will make setup process and development process lot easier.
Follow this link to install and set up the django with MongoDB.
http://django-mongodb-engine.readthedocs.org/en/latest/topics/setup.html
One more thing you may find the error below, while setting up django.
"*Error on Django-nonrel and MongoDB: AutoField (default primary key) values must be strings representing an ObjectId on MongoDB (got u'1' instead). Please make sure your SITE_ID contains a valid ObjectId string.*"
Follow this link to fix.
https://gist.github.com/ielshareef/2986459
Please let me know if you need any more help on this.
As stated in the title, I am using django-mongodb-engine and I am attempting to configure the native Django authentication framework. I've read some comments online that it should work out of the box sans some features. However, I couldn't find any tutorials and, furthermore, I am getting errors on trying to set it up on my own. The issue I'm having most certainly has to do with database permissions. I have included the Django middleware and apps per the Django docs. However, when I issue the syncdb command it fails with an error.
$ python manage.py syncdb
OperationFailure: database error: not authorized for query on MyDB.system.namespaces
settings.py
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': 'MyDB',
'USER': 'mySuperUser',
'PASSWORD': 'mypass',
'HOST': 'XXX.XXX.XXX.XXX',
'PORT': '',
},
# some other DBs
}
Mongo User Permissions
myDB> db.system.users.find()
{ "_id" : ObjectId("..."), "user" : "mySuperUser", "pwd" : "...", "roles" : [ "readWriteAnyDatabase", "userAdminAnyDatabase", "dbAdminAnyDatabase", "clusterAdmin" ] }
I'm not sure what other permissions I can grant this guy, and/or where else I need to create this user.
Any ideas?
After playing around, here is the solution. You must use the native mongo admin database. Thus, the required changes:
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': 'admin',
'USER': 'mySuperUser',
'PASSWORD': 'mypass',
'HOST': 'XXX.XXX.XXX.XXX',
'PORT': '',
},
# some other DBs
}
The user mySuperUser must naturally exist on the admin database. To be safe regarding authentication actions such as adding and removing users, I gave it the userAdminAnyDatabase privilege in mongo. The privileges are probably excessive, but I'd have to play with it to determine the proper scope of the required permissions. Here are the permissions:
// mongo
admin> db.system.users.find()
{ "_id" : ObjectId("..."), "pwd" : "...", "roles" : [ "readWriteAnyDatabase", "dbAdminAnyDatabase", "clusterAdmin", "userAdminAnyDatabase" ], "user" : "mySuperUser" }
Next, we can finally run the syncdb command:
$ python manage.py syncdb
Creating tables ...
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'someUser'):
Email address: someUser#user.com
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installing indices for admin.LogEntry model.
Installing indices for auth.Group_permissions model.
Installing indices for auth.Group model.
Installing indices for auth.User_groups model.
Installing indices for auth.User_user_permissions model.
Installing indices for auth.User model.
Installing indices for sessions.Session model.
Installed 0 object(s) from 0 fixture(s)
$
The problem for me was that I had not specified a SITE_ID in my settings.py. I did this:
./manage.py shell
>>>from django.contrib.sites.models import Site
>>>Site().save()
>>>Site.objects.all()[0].id
u'5391dbc22ebd1212246d50c4'
If you aren't 'django.contrib.sites' then I'm not sure why this would be a problem. Unless you had been using that module and already installed the collection/table to the database. In either case, this is how I got MongoDB to start working correctly again.
I encountered the same issue. My Mongo DB is hosted on MongoLab and I don't find any solutions to solve this error. Although that my user already exists in my DB, I don't want to use the admin database. Someone else has encountered the same problem or find a solution ?