I'm trying to use Mezzanine cms (3.1.4) in a shared hosting at Dreamhost. I successfully created my first blog entry but strangely enough, I don't find the table associated with this entry. Phpadmin page at Dreamhost does show my mezzanine database (named hamlet) but there are only 10 tables in it :
auth_group, auth_group_permissions,auth_permission, auth_user, auth_user_groups, auth_user_user_permissions
django_admin_log, django_content_type, django_migrations, django_session
No blog table. Does someone have an explanation for this?
EDIT: Steps I did:
-Entered in my virtual environment env.mez
-Created the passenger_wsgi.py file:
import sys, os
INTERP = "/home/geantbrun/opt/python-2.7.7/bin/python"
#INTERP is present twice so that the new python interpreter knows the actual executable path
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
cwd = os.getcwd()
sys.path.append(cwd)
sys.path.append(cwd + '/mez') #You must add your project here
sys.path.insert(0,cwd+'/env.mez/bin')
sys.path.insert(0,cwd+'/env.mez/lib/python2.7/site-packages/mezzanine')
sys.path.insert(0,cwd+'/env.mez/lib/python2.7/site-packages')
os.environ['DJANGO_SETTINGS_MODULE'] = "mez.settings"
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
-Created on Dreamhost panel the database hamlet
-Created my mezzanine-project (mez)
-Parameters set in settings.py:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": "hamlet",
"USER": "(myusername)",
"PASSWORD": "(mypass)",
"HOST": "mysql.geantbrun.com",
"PORT": "3306",
}
}
-Static files collected
-Command syncdb :
python manage.py syncdb
Syncing...
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_redirect
Creating table django_session
Creating table django_site
Creating table south_migrationhistory
Creating table django_admin_log
Creating table django_comments
Creating table django_comment_flags
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 'geantbrun'):
Email address:
Password:
Password (again):
Superuser created successfully.
A site record is required.
Please enter the domain and optional port in the format 'domain:port'.
For example 'localhost:8000' or 'www.example.com'.
Hit enter to use the default (127.0.0.1:8000): (mysite.com)
Creating default site record: mysite.com ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
Synced:
> mezzanine.boot
> moderna
> django.contrib.auth
> django.contrib.contenttypes
> django.contrib.redirects
> django.contrib.sessions
> django.contrib.sites
> django.contrib.sitemaps
> django.contrib.staticfiles
> compressor
> filebrowser_safe
> south
> django.contrib.admin
> django.contrib.comments
Not synced (use migrations):
- mezzanine.conf
- mezzanine.core
- mezzanine.generic
- mezzanine.blog
- mezzanine.forms
- mezzanine.pages
- mezzanine.galleries
- mezzanine.twitter
(use ./manage.py migrate to migrate these)
-At this point, on Dreamhost panel, I see that 14 tables are now created in hamlet database (auth_, django_ and south_migrationhistory tables).
-Migrate command: python manage.py migrate
Running migrations for conf:
- Migrating forwards to 0004_ssl_account_settings_rename.
> conf:0001_initial
> conf:0002_auto__add_field_setting_site
> conf:0003_update_site_setting
- Migration 'conf:0003_update_site_setting' is marked for no-dry-run.
> conf:0004_ssl_account_settings_rename
- Migration 'conf:0004_ssl_account_settings_rename' is marked for no-dry-run.
- Loading initial data for conf.
Installed 0 object(s) from 0 fixture(s)
Running migrations for core:
- Migrating forwards to 0006_initial.
> core:0001_initial
(...other migrations)
> core:0006_initial
FATAL ERROR - The following SQL query failed: CREATE TABLE "core_sitepermission" ("id" integer NOT NULL PRIMARY KEY, "user_id" integer NOT NULL)
The error was: table "core_sitepermission" already exists
! Error found during real run of migration! Aborting.
Error in migration: core:0006_initial
Traceback (most recent call last):
File "manage.py", line 29, in <module>
execute_from_command_line(sys.argv)
(...other traces)
File "/home/geantbrun/mysite.com/env.mez/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 452, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: table "core_sitepermission" already exists
Note that file referred to at last line is .../backends/sqlite3/base.py. I realize that DATABASES parameter is maybe overridden by local_settings file. I removed the DATABASES parameter from local_settings and rerun the migrate command. Result:
Error in migration: core:0006_initial
Traceback (most recent call last):
File "manage.py", line 29, in <module>
execute_from_command_line(sys.argv)
File "/home/geantbrun/mysite.com/env.mez/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 124, in execute
return self.cursor.execute(query, args)
File "/home/geantbrun/mysite.com/env.mez/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "/home/geantbrun/mysite.com/env.mez/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
django.db.utils.OperationalError: (1050, "Table 'core_sitepermission' already exists")
No more mention to sqlite3 but same kind of error at the end ('core_sitepermission already exists'). Does the migrate command should be run with --fake parameter because the database is already created?
Related
I'm creating some tests in my django web app with selenium.
Django create a test database with all tables.
In my case however I have a model Users.
I want that django create also users table when I run this command in terminal
python3.9 manage.py test -v3
This command goes in error:
Running post-migrate handlers for application contenttypes
Adding content type 'contenttypes | contenttype'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Running post-migrate handlers for application sessions
Adding content type 'sessions | session'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Running post-migrate handlers for application pygiustizia
Adding content type 'pygiustizia | member'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
System check identified no issues (0 silenced).
test_login (pygiustizia.tests.test_views_topics.ViewsTopicsTestCase) ... nel costruttore model Users
ERROR
======================================================================
ERROR: test_login (pygiustizia.tests.test_views_topics.ViewsTopicsTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/nicola/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "/home/nicola/.local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 75, in execute
return self.cursor.execute(query, args)
File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/cursors.py", line 148, in execute
result = self._query(query)
File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/cursors.py", line 310, in _query
conn.query(q)
File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/connections.py", line 775, in _read_query_result
result.read()
File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/connections.py", line 725, in _read_packet
packet.raise_for_error()
File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1146, "Table 'test_civiledb.users' doesn't exist")
EDIT
I access to the table users that I want create manually for test by this model.
from django.db import models
from django.db import connection
import pymysql
class Users(models.Model):
firstname=models.CharField(max_length=100)
lastname=models.CharField(max_length=100)
username=models.CharField(max_length=50)
password=models.CharField(max_length=255)
admin=models.IntegerField()
createdAt=models.DateTimeField(db_column="created_at")
def __init__(self,*args, **kwargs):
super().__init__(*args, **kwargs)
print("nel costruttore model Users")
def getAdmin(self):
return self.admin
class Meta:
db_table = 'users'
def getUser(self,username):
cursor = connection.cursor()
cursor.execute('''SELECT id,
username,
password,
admin,
firstname,
lastname,
created_at
FROM users
WHERE username = %s''',[username])
result = cursor.fetchone()
return result
def setPassword(self,userId,password):
cursor = connection.cursor()
try:
cursor.execute('''UPDATE users
SET password = %s
WHERE id = %s''',[password,userId])
connection.commit()
except Exception as e:
print(e)
connection.rollback()
return False
finally:
connection.close()
return True
A solution is to create "sql create" schema run it in testcase in setUp and drop it on tearDown.
I think the concept you are looking for here are unmanaged models. By setting the appropriate Meta option you can tell Django that it shouldn't handle the table lifecycle for you.
To answer your question, using SchemaEditor on test setup and teardown seems like a particularly clean way to achieve what you are looking for.
I am learning django version 1.11.4 through tutorial on the official documentation. I am using python 3.6.5 and mysql8 for database. I also use mysql.connector.django to connect to mysql database. I tried to do the first Django app, part 2.
This is the link of the example I used
everything works fine except when I run the this command:
Question.objects.all()
I got the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 226, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __iter__
self._fetch_all()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 1118, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 62, in __iter__
for row in compiler.results_iter(results):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 839, in results_iter
for rows in results:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1284, in cursor_iter
sentinel):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1283, in <lambda>
for rows in iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)),
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/utils.py", line 101, in inner
return func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/cursor_cext.py", line 510, in fetchmany
rows.extend(self._cnx.get_rows(size))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 275, in get_rows
row[i])
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/conversion.py", line 205, in to_python
return self._cache_field_types[vtype[1]](value, vtype)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/django/base.py", line 119, in _DATETIME_to_python
dt = MySQLConverter._DATETIME_to_python(self, value)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/conversion.py", line 506, in _DATETIME_to_python
(date_, time_) = value.split(b' ')
AttributeError: 'datetime.datetime' object has no attribute 'split'
the code used in the models file :
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() -
datetime.timedelta(days=1)
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
the database setting:
DATABASES = {
'default': {
'NAME': 'mysite',
'ENGINE': 'mysql.connector.django',
'USER': 'root',
'PASSWORD': '********',
'OPTIONS': {
'autocommit': True,
},
}
}
any clue or help to fix this error will be appreciated.
I struggled for few hours to set up my Django project with python3 using MySQL DB on MacOS.
I was not able to install either mysqlclient and MySQL-Python by pip3 in a virtual environment created with virtualenv
error stacktrace was: something wrong due to configparser in python3
Jans-MacBook-Pro:~ jan$ /Library/Frameworks/Python.framework/Versions/3.3/bin/pip-3.3 install MySQL-python
Downloading/unpacking MySQL-python
Running setup.py egg_info for package MySQL-python
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/var/folders/lf/myf7bjr57_jg7_5c4014bh640000gn/T/pip-build/MySQL-python/setup.py", line 14, in <module>
from setup_posix import get_config
File "./setup_posix.py", line 2, in <module>
from ConfigParser import SafeConfigParser
ImportError: No module named 'ConfigParser'
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/var/folders/lf/myf7bjr57_jg7_5c4014bh640000gn/T/pip-build/MySQL-python/setup.py", line 14, in <module>
from setup_posix import get_config
File "./setup_posix.py", line 2, in <module>
from ConfigParser import SafeConfigParser
ImportError: No module named 'ConfigParser'
----------------------------------------
Command python setup.py egg_info failed with error code 1 in /var/folders/lf/myf7bjr57_jg7_5c4014bh640000gn/T/pip-build/MySQL-python
Storing complete log in /Users/jan/.pip/pip.log
Jans-MacBook-Pro:~ jan$
Now the SOLUTION which worked for me was
1) installing mysql with brew again
brew install mysql
2) upgrading mysql with brew to latest version (if required)
brew upgrade mysql
3) installing mysqlclient now with pip3 (installing globally without virtualenv)
pip3 install mysqlclient
4) now access virtualenv and instal the mysqlclient in it, it will install fine without any error for configparser
As can be seen in the bug report posted by #Alasdair, the solution is:
Set use_pure=True in DATABASES['default']['OPTIONS'].
I too went through this pain yesterday or 2 days ago and was able to get it running with the mysqlclient-1.3.12. I'm going from memory here so bear with me, I tried a lot of things but eventually I got it to work.
I installed mysql8 and mysql8connector from the mysql web site as you did but got no love. After much searching and many trial and errors I found an answer somewhere which I can't find my way back to but I ended up doing:
brew install mysql
pip install mysqlclient
I know that you already have mysql installed but brew install mysql seems to add client libraries that are used to compile the mysqlclient connector. Then my database in my settings file looks like:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'polls',
'USER': 'myuser',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'charset': 'utf8mb4',
'autocommit': True,
},
}
}
Note the ENGINE is different. I can replicate your exact error if I change my ENGINE to mysql.connector.django.
However, using django.db.backends.mysql I still get the following warning:
lib/python3.6/site-packages/django/db/backends/mysql/base.py:71: Warning: (3719, "'utf8' is currently an alias for the character set UTF8MB3, which will be replaced by UTF8MB4 in a future release. Please consider using UTF8MB4 in order to be unambiguous."
which I can't figure out, but as it is only a warning the Django tutorial seems to be working fine.
Let me know if this helps or if you have other questions and I'll do my best to help.
This is mysql-connector-python data conversion issue. You can get around this by setting the database options parameter with use_pure=true. This issue is not fixed in the current version 8.0.11,8.0.12, and 8.0.13.
"OPTIONS":{
"use_pure":True
}
This is just a temporary solution. Refer here for more information: https://bugs.mysql.com/bug.php?id=90541
When i run pwiz to generate a peewee modem from existing database it shows following error:
root#server:~# python -m pwiz -e mysql -P -H 127.0.0.1 mysql
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/usr/local/lib/python2.7/dist-packages/pwiz.py", line 202, in <module>
print_models(introspector, tables, preserve_order=options.preserve_order)
File "/usr/local/lib/python2.7/dist-packages/pwiz.py", line 47, in print_models
database = introspector.introspect(table_names=tables)
File "/usr/local/lib/python2.7/dist-packages/playhouse/reflection.py", line 440, in introspect
tables = self.metadata.database.get_tables()
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 3089, in get_tables
return [table for table, in self.execute_sql('SHOW TABLES')]
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 2459, in execute_sql
cursor = self.cursor(commit)
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 2445, in cursor
self.connect()
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 2411, in connect
self._state.set_connection(self._connect())
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 3083, in _connect
return mysql.connect(db=self.database, **self.connect_params)
AttributeError: 'NoneType' object has no attribute 'connect'
What is the problem? The username and password of database is correct.
PyMySql is not installed. Install it using pip or other available options:
pip install PyMySql
Unfortunately, peewee does not write `PyMySql1 module of python in its dependency list, so it should be installed separately.
I am getting this Attribute Error : 'No Type' objectives has no attribute 'split' when i tried to migrate sql db to mysql db in mysql workbench
these are the Log details :
Starting...
Connect to source DBMS...
- Connecting to source...
Connecting to Mssql#sa...
Opening ODBC connection to Driver=sa;DATABASE=;UID=sa;PWD=XXXX...
Connected to Mssql# 11.0.2100.60
Traceback (most recent call last):
File "/Applications/MySQLWorkbench.app/Contents/PlugIns/db_mssql_grt.py", line 147, in connect
_connections[connection.__id__]["version"] = getServerVersion(connection)
File "/Applications/MySQLWorkbench.app/Contents/PlugIns/db_mssql_grt.py", line 174, in getServerVersion
ver_parts = [ int(part) for part in ver_string.split('.') ] + 4*[ 0 ]
AttributeError: 'NoneType' object has no attribute 'split'
Traceback (most recent call last):
File "/Applications/MySQLWorkbench.app/Contents/PlugIns/db_mssql_grt.py", line 174, in getServerVersion
ver_parts = [ int(part) for part in ver_string.split('.') ] + 4*[ 0 ]
AttributeError: 'NoneType' object has no attribute 'split'
Traceback (most recent call last):
File "/Applications/MySQLWorkbench.app/Contents/Resources/libraries/workbench/wizard_progress_page_widget.py", line 65, in run
self.func()
File "/Applications/MySQLWorkbench.app/Contents/PlugIns/migration_source_selection.py", line 406, in task_connect
raise e
SystemError: AttributeError("'NoneType' object has no attribute 'split'"): error calling Python module function DbMssqlRE.getServerVersion
*** ERROR: Error during Connect to source DBMS: AttributeError("'NoneType' object has no attribute 'split'"): error calling Python module function DbMssqlRE.getServerVersion
Traceback (most recent call last):
File "/Applications/MySQLWorkbench.app/Contents/Resources/libraries/workbench/wizard_progress_page_widget.py", line 543, in update_status
task.run()
File "/Applications/MySQLWorkbench.app/Contents/Resources/libraries/workbench/wizard_progress_page_widget.py", line 80, in run
raise e
SystemError: AttributeError("'NoneType' object has no attribute 'split'"): error calling Python module function DbMssqlRE.getServerVersion
*** ERROR: Exception in task 'Connect to source DBMS': SystemError('AttributeError("\'NoneType\' object has no attribute \'split\'"): error calling Python module function DbMssqlRE.getServerVersion',)
Failed
i tried a solution (given below , taken from the link https://bugs.mysql.com/bug.php?id=66030&thanks=3¬ify=195). but it didn't help. I still get the same error. Please help me.
solution:
// We'll need some help from you to diagnose this one. With a text editor, open the /Applications/MySQLWorkbench.app/Contents/PlugIns/db_mssql_grt.py file
and around line 174 you'll find a line that looks like:
ver_string = execute_query(connection, "SELECT SERVERPROPERTY('ProductVersion')").fetchone()[0]
Change that to:
ver_string = execute_query(connection, "SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)").fetchone()[0]
Then save and retry. Thanks! //
I have a bash script that starts some python code, running on a RasPi under latest raspbian. It runs fine if I run it manually with sudo, but when it auto runs at boot I get a mysql error. The script is called from a line in /etc/rc.local
The script is
#!/bin/bash
/home/control/solar/v10_1/control.py >> '/home/control/solar/logs/control_X.X_start.log' 2>&1 &
echo "control started" >> '/home/control/solar/logs/control_X.X_start.log'
echo "UID is $UID , EUID is $EUID" >> '/home/control/solar/logs/control_X.X_start.log'
The output to the log after bootup is
UID is 0 , EUID is 0
Traceback (most recent call last):
File "/home/control/solar/v10_1/control.py", line 42, in <module>
import variables # global variables
File "/home/control/solar/v10_1/variables.py", line 13, in <module>
gv.db = MySQLdb.connect("localhost", "solar", "solar", db='solar') # database for logging
File "/usr/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
I have made all the paths absolute, the UID is 0 in both cases, what can cause the difference in behaviour?