Integrity Error: using primary_key=True - django

This is my Models:
from django.db import models
from django.contrib.auth.models import User
class Bookmark(models.Model):
id = models.PositiveIntegerField(primary_key=True)
name = models.CharField(max_length=50)
url = models.URLField()
isPublic = models.BooleanField(default=True)
dateTimePosted = models.DateTimeField(auto_now=True,verbose_name="posted at")
user = models.ForeignKey(User, on_delete=models.CASCADE)
This is my 0001_initials.py:
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Bookmark',
fields=[
('id', models.PositiveIntegerField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=50)),
('url', models.URLField()),
('isPublic', models.BooleanField(default=True)),
('dateTimePosted', models.DateTimeField(auto_now=True, verbose_name='posted at')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
When I am inserting values using:
python manage.py shell:
>>from django.contrib.auth.models import User
>>user = User.objects.create_user('test', 'test#abc.com', 'test#123')
>>from bookmark.models import Bookmark
>>bookmark = Bookmark.objects.create(name='First Bookmark', url='example.com', user=user)
this error occurs:
Traceback (most recent call last):
File "", line 1, in
File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 394, in create
obj.save(force_insert=True, using=self.db)
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 806, in save
force_update=force_update, update_fields=update_fields)
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 836, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 922, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 961, in _do_insert
using=using, raw=raw)
File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 1063, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python34\lib\site-packages\django\db\models\sql\compiler.py", line 1099, in execute_sql
cursor.execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\utils.py", line 94, in exit
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python34\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: bookmark_bookmark.id
how to tackle this error
I have deleted database (db.sqlite3)and pycache folder unapplied migrations and then created again using:
python manage.py makemigrations
but still error occurs

You are not passing the primary key value (id) when you are creating your BookMark object.
Change your create as follows,
bookmark = Bookmark.objects.create(name='First Bookmark', url='example.com', user=user, id=<some_int_which_hasnt_been_used>) # Use an id that you know you hasn't been used.
Now the reason you have to do this is because you have defined your own Primary Key, so Django will not automatically create it for you.
When you do not specify a primary key, Django uses an "id" field which is of type "models.AutoField", and automatically increments the value (without you needing to specify the value for id).
In case you are interested in knowing how it works internally you can read up on Sequences in databases (what Django does internally is create a sequence in your database for the table, and your database has a default value for your id column)
I'm not sure why you have overridden the id field that Django provides automatically (because your id is PositiveIntegerField, and AutoField would generate only positive values anyway), so if there is no specific reason for you defining the PK, I suggest you go with what Django creates for you.

Related

How to specify SQLAlchemy ForeignKey with specific schema name?

I have a Flask / Flask-User app that I am trying to convert from Python 3.6 to Flask / Flask-Security-Too under Python 3.10. There have been a lot of changes in the world since 3.6 and I am playing whack-a-mole trying to figure them out. In this particular case I am redoing the database tables since nothing from the old app needs to transfer to the new version. I am using the latest version of PyCharm and all of the latest versions of the libraries that Flask and Flask-Security-Too require.
Things to note: the target database is an MS SQL Server instance. There is an existing "database" that I must use and a specific "schema name" under which any tables I create must live.
I have successfully run flask db init and am trying to run the first flask db migrate but get the error:
(venv) PS C:\Users\me\PycharmProjects\MyProject\UserInterface\MyApp> flask db migrate
INFO [alembic.runtime.migration] Context impl MSSQLImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
Traceback (most recent call last):
File "C:\Python310\lib\runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Python310\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\Scripts\flask.exe\__main__.py", line 7, in <module>
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask\cli.py", line 988, in main
cli.main()
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask\cli.py", line 579, in main
return super().main(*args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 1055, in main
rv = self.invoke(ctx)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\decorators.py", line 26, in new_func
return f(get_current_context(), *args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask\cli.py", line 427, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask_migrate\cli.py", line 104, in migrate
_migrate(directory, message, sql, head, splice, branch_label, version_path,
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask_migrate\__init__.py", line 98, in wrapped
f(*args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask_migrate\__init__.py", line 155, in migrate
command.revision(config, message, autogenerate=True, sql=sql,
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\command.py", line 229, in revision
script_directory.run_env()
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\script\base.py", line 569, in run_env
util.load_python_file(self.dir, "env.py")
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\util\pyfiles.py", line 94, in load_python_file
module = load_module_py(module_id, path)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\util\pyfiles.py", line 110, in load_module_py
spec.loader.exec_module(module) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\MyApp\migrations\env.py", line 104, in <module>
run_migrations_online()
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\MyApp\migrations\env.py", line 98, in run_migrations_online
context.run_migrations()
File "<string>", line 8, in run_migrations
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\runtime\environment.py", line 853, in run_migrations
self.get_context().run_migrations(**kw)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\runtime\migration.py", line 611, in run_migrations
for step in self._migrations_fn(heads, self):
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\command.py", line 205, in retrieve_migrations
revision_context.run_autogenerate(rev, context)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\api.py", line 526, in run_autogenerate
self._run_environment(rev, migration_context, True)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\api.py", line 573, in _run_environment
compare._populate_migration_script(
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\compare.py", line 55, in _populate_migration_script
_produce_net_changes(autogen_context, upgrade_ops)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\compare.py", line 89, in _produce_net_changes
comparators.dispatch("schema", autogen_context.dialect.name)(
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\util\langhelpers.py", line 267, in go
fn(*arg, **kw)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\compare.py", line 125, in _autogen_for_tables
[(table.schema, table.name) for table in autogen_context.sorted_tables]
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 1113, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\api.py", line 443, in sorted_tables
result.extend(m.sorted_tables)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\schema.py", line 4697, in sorted_tables
return ddl.sort_tables(
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\ddl.py", line 1213, in sort_tables
for (t, fkcs) in sort_tables_and_constraints(
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\ddl.py", line 1291, in sort_tables_and_constraints
dependent_on = fkc.referred_table
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\schema.py", line 3808, in referred_table
return self.elements[0].column.table
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 1113, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\schema.py", line 2507, in column
raise exc.NoReferencedTableError(
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'roles_users.role_id' could not find table 'role' with which to generate a foreign key to target column 'id'
The User and Role models look like (pruned for length):
### USER
#
import uuid
from flask_security import UserMixin
from sqlalchemy import Column, Integer, String, Boolean, Unicode, DateTime, func
from sqlalchemy.orm import relationship, backref
from app.database import Base
class User(Base, UserMixin):
__tablename__ = 'user'
__table_args__ = {"schema": "ExistingSchemaName"}
id = Column(Integer,primary_key=True)
email = Column(Unicode(255),nullable=False,server_default=u'',unique=True)
...
# Flask-Security-Too fields
fs_uniquifier = Column(String(255), unique=True, nullable=False)
confirmed_at = Column(DateTime())
last_login_at = Column(DateTime())
current_login_at = Column(DateTime())
last_login_ip = Column(String(100))
current_login_ip = Column(String(100))
login_count = Column(Integer)
# Relationships
child_roles = relationship('Role',back_populates='parent_user')
import uuid
### ROLE
#
from flask_security import RoleMixin
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from app.database import Base
class Role(Base, RoleMixin):
__tablename__ = 'role'
__table_args__ = {"schema": "ExistingSchemaName"}
id = Column(Integer(),primary_key=True)
name = Column(String(64),nullable=False,server_default=u'',unique=True)
description = Column(String(255),nullable=False,server_default=u'')
# Have also tried adding schema name to ForeignKey without success, as in:
# user_id = Column(Integer,ForeignKey("ExistingSchemaName.user.id"))
user_id = Column(Integer,ForeignKey("user.id"))
parent_user = relationship("User",back_populates="child_roles")
The app.database.py file looks like:
from .settings import SQLALCHEMY_DATABASE_URI
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine(SQLALCHEMY_DATABASE_URI)
db = scoped_session(
sessionmaker(
autocommit=False,
autoflush=False,
bind=engine
)
)
Base = declarative_base()
Base.query = db.query_property()
def init_db():
import app.models
Base.metadata.create_all(bind=engine)
I think that I have set the one-to-many relationships correctly but I do not know what I am missing.

Why is Django's factory-boy trying to create a factory when I'm not asking it to?

I'm trying to use Django's factory-bot module to create factories for my models. I'm also using pytest. I have created these factories ...
import factory
from maps.models import CoopType, Coop
from address.models import AddressField
from phonenumber_field.modelfields import PhoneNumberField
from address.models import State, Country, Locality
class CountryFactory(factory.DjangoModelFactory):
"""
Define Country Factory
"""
class Meta:
model = Country
name = "Narnia"
code = "NN"
class StateFactory(factory.DjangoModelFactory):
"""
Define State Factory
"""
class Meta:
model = State
name = "Narnia"
code = "NN"
country = CountryFactory()
class LocalityFactory(factory.DjangoModelFactory):
"""
Define Locality Factory
"""
class Meta:
model = Locality
name = "Narnia"
postal_code = "60605"
state = StateFactory()
class AddressFactory(factory.DjangoModelFactory):
"""
Define Address Factory
"""
class Meta:
model = Address
street_number = "123"
route = "Rd"
raw = "123 Fake Rd"
formatted = "123 Fake Rd."
latitude = 87.1234
longitude = -100.12342
locality = LocalityFactory()
class CoopTypeFactory(factory.DjangoModelFactory):
"""
Define Coop Type Factory
"""
class Meta:
model = CoopType
I have a very simple test file thus far. It only has one test ...
import pytest
from django.test import TestCase
from .factories import CoopTypeFactory, CoopFactory
class ModelTests(TestCase):
#classmethod
def setUpTestData(cls):
print("setUpTestData: Run once to set up non-modified data for all class methods.")
#management.call_command('loaddata', 'test_data.yaml', verbosity=0)
pass
def setUp(self):
print("setUp: Run once for every test method to setup clean data.")
#management.call_command('flush', verbosity=0, interactive=False)
pass
#pytest.mark.django_db
def test_coop_type_create(self):
""" Test customer model """ # create customer model instance
coop_type = CoopTypeFactory(name="Test Coop Type Name")
assert coop_type.name == "Test Coop Type Name"
But when I run my test, it dies complaining about a duplicate key for a factory that I'm not even creating.
davea$ python manage.py test --settings=maps.test_settings
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: tests.test_models (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.test_models
Traceback (most recent call last):
File "/Users/davea/Documents/workspace/chicommons/maps/web
...
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 434, in _find_test_path
module = self._get_module_from_name(name)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 375, in _get_module_from_name
__import__(name)
File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/test_models.py", line 3, in <module>
from .factories import CoopTypeFactory, CoopFactory
File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/factories.py", line 19, in <module>
class StateFactory(factory.DjangoModelFactory):
File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/factories.py", line 28, in StateFactory
country = CountryFactory()
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 46, in __call__
return cls.create(**kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 564, in create
return cls._generate(enums.CREATE_STRATEGY, kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/django.py", line 141, in _generate
return super(DjangoModelFactory, cls)._generate(strategy, params)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 501, in _generate
return step.build()
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/builder.py", line 279, in build
kwargs=kwargs,
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 315, in instantiate
return self.factory._create(model, *args, **kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/django.py", line 185, in _create
return manager.create(*args, **kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/query.py", line 417, in create
obj.save(force_insert=True, using=self.db)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/base.py", line 759, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/base.py", line 842, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/base.py", line 880, in _do_insert
using=using, raw=raw)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/query.py", line 1125, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1280, in execute_sql
cursor.execute(sql, params)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute
return self.cursor.execute(query, args)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 209, in execute
res = self._query(query)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 315, in _query
db.query(q)
File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/connections.py", line 239, in query
_mysql.connection.query(self, query)
django.db.utils.IntegrityError: (1062, "Duplicate entry 'Narnia' for key 'name'")
----------------------------------------------------------------------
Ran 1 test in 0.000s
What am I doing wrong? Why is Django trying to create a factory for something I'm not creating a factory for?
You should use factory.SubFactory for defining foreign key relationships
class LocalityFactory(factory.DjangoModelFactory):
...
state = factory.SubFactory(StateFactory)
Calling the factories in your classes is creating instances

Django no such table after migrations

After trying all sort of migration im still getting this error
I only get this error when trying to save the new object
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 779, in save_base
force_update, using, update_fields,
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 908, in _do_insert
using=using, raw=raw)
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1332, in execute_sql
cursor.execute(sql, params)
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 99, in execute
return super().execute(sql, params)
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Carlos\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: desporto_noticia
Models
import datetime
from django.db import models
from django.utils import timezone
class Noticia(models.Model):
noticia_texto = models.TextField()
noticia_imagem_path = models.CharField(max_length=100)
noticia_titulo = models.CharField(max_length=100, default='Default')
pub_data = models.DateTimeField('data de publicacao')
noticia_tema = models.CharField(max_length=100)
def __str__(self):
return self.noticia_texto
class Comentario(models.Model):
noticia = models.ForeignKey(Noticia, on_delete=models.CASCADE)
comentario_texto = models.CharField(max_length=300)
def __str__(self):
return self.comentario_texto
Went on my database software to find this is the only table non-existence, the other model has a table tables
Tried all migrates ex :
python manage.py makemigrations desporto
python manage.py sqlmigrate desporto 0001
python manage.py migrate
python manage.py migrate --run-syncdb
Your migrations for the Noticia model has been recorded in the Django migrations table but deleted from the database. If it is not in production you can drop the database and rerun the migrations with the fresh database schema. If you don't want to drop the database then you can delete the migration entry from the migrations table and rerun the migrate command.
Notice: Please don't experiment it with the production database.

Test Django user profile one-to-one link

I'm adding a Profile to my Django app as a way to store more User information. Following https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone
However I'm getting an error when testing it. I'm using the default User model from django.contrib.auth.
models.py
from django.db import models
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
#receiver(post_save, sender=get_user_model())
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=get_user_model())
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
tests/test_model.py
from django.test import TestCase
from app.models import Profile
class ProfileModelTests(TestCase):
#classmethod
def setUpTestData(cls):
Profile.objects.create()
def test_can_create_profile(self):
pass
error
/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
""")
..........E............
======================================================================
ERROR: setUpClass (project-api.polls.tests.test_models.ProfileModelTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (158, null).
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/test/testcases.py", line 1002, in setUpClass
cls.setUpTestData()
File "/Users/user/programming/gatsby/project-api/polls/tests/test_models.py", line 86, in setUpTestData
Profile.objects.create()
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create
obj.save(force_insert=True, using=self.db)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/base.py", line 842, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/base.py", line 880, in _do_insert
using=using, raw=raw)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/query.py", line 1125, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1283, in execute_sql
cursor.execute(sql, params)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (158, null).
----------------------------------------------------------------------
Ran 22 tests in 2.198s
FAILED (errors=1)
Using existing test database for alias 'default'...
System check identified no issues (0 silenced).
Preserving test database for alias 'default'...
#receiver(post_save, sender=get_user_model())
With this code, you are listening to the save method of the User model to create a related Profile entry just in time, if there isn't one yet. This way, you can just go along creating new Users without worrying at creating and linking Profiles manually everytime.
Note that the reverse isn't covered: if you want to create a Profile entry directly, you must pass an existing User object to it, or else you will get an IntegrityError.
Solution: preferrably, stick to one main way to create user + profile pairs; in your case, just create a User and let the signal call the creation of the profile automatically.
class ProfileModelTests(TestCase):
#classmethod
def setUpTestData(cls):
get_user_model().objects.create()
def test_profile(self):
profile = get_user_model().objects.last().profile
The idea is Profile.objects.create(user=instance) if the user doesn't exist yet an IntegrityError exception will be thrown since no user_id to be found. The signals will listen when the user will be created not the reverse.
In your testcase Profile.objects.create() will try to create a One-To-One relation with a user that doesn't exist.

Django Rest Framework - IntegrityError: null value in column "user_id" violates not-null constraint

I am new to Django, want to create custom user models as follows:
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db import models
class UniservedTeam(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
Role = ArrayField(models.CharField(max_length=1000), blank=True,null=True)
ContactNumber = models.CharField(max_length=100)
In shell I am trying to create an user :
>>> user = User.objects.create(email='piyush#uniserved.com',password='Piyush#123',username='Piyush#24',last_name='Wanare',first_name='Piyush',is_active=True)
>>> user
<User: Piyush#24>
>>> user.id
1
>>> team = UniservedTeam.objects.create(id=user.id,Role=['Vendor Co-ordinator'],ContactNumber='862339798167')
Getting Error as follows:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/query.py", line 401, in create
obj.save(force_insert=True, using=self.db)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/base.py", line 700, in save
force_update=force_update, update_fields=update_fields)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/base.py", line 728, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/base.py", line 812, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/base.py", line 851, in _do_insert
using=using, raw=raw)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/query.py", line 1039, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1060, in execute_sql
cursor.execute(sql, params)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/piyush/.environments/awsd/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
IntegrityError: null value in column "user_id" violates not-null constraint
I think what you want instead after you make your user is this
team = UniservedTeam.objects.create(user=user,Role=['Vendor Co-ordinator'],ContactNumber='862339798167')
Try this,
team = UniservedTeam.objects.create(user__id=user.id, Role=['Vendor Co-ordinator'],ContactNumber='862339798167')