Django 1.9 - IntegrityError on update - django

class Configuration(models.Model):
configuration_key = models.CharField(max_length=100, unique=True)
configuration_value = models.TextField()
configuration_description = models.TextField("a brief description of this setting", blank=True)
The above is my model. I am able to able to add configurations using the admin. I have not configured any customizations on the admin. It is a very basic
admin.site.register(Configuration)
When I update an existing configuration with admin, it throws an IntegrityError
duplicate key value violates unique constraint "config_configuration_configuration_key_key"
DETAIL: Key (configuration_key)=(SAMPLE_CONFIGURATION) already exists.
My question: Shouldn't the admin know that an existing configuration is modified and handle this accordingly? Am I missing something? To be clear - SAMPLE_CONFIGURATION - there is only one such row in the table with that configuration_key. I am trying to edit the configuration_value for that row using the admin and it throws the Integrityerror.

Your code is just fine, there must be no error. Update Django to the current version and try again.
Also try to isolate the problem. Use tests to reproduce the issue. If tests are passed, then problem not in your code.
Double check what is inside DB, try to update row directly using SQL.
This test updates configuration_value without any integrity issues.
class ConfigurationModelTest(TestCase):
def test_uniq_issue(self):
config = Configuration.objects.create(configuration_key='SAMPLE_CONFIGURATION',
configuration_value='value')
config.save()
config.configuration_value = 'updated_value'
config.save()

Related

Django BooleanField(default=False) Confusion

Can anyone help me out here? I am inserting data into my postgreSQL DB.
admin_created is a booleanfield set to false by default. I've provided a true value for the first workout, but left the second workout blank for the booleanfield. Based on my understanding it should automatically be set to false, but i'm getting the error message below. Any ideas on why this is happening?
#.sql
INSERT INTO main_app_workout(name, description, admin_created)
VALUES
('Yoga', 'Roll up your yoga mat and discover the combination of physical and mental exercises that have hooked yoga practitioners around the globe.', 'True');
INSERT INTO main_app_workout(name, description)
VALUES
('Boxing', 'Ready to get your sweat on? Learn the six basic punches to build the foundation of an experienced boxer.');
#models.py
class Workout(Model):
name = models.CharField(max_length=40)
description = models.TextField()
exercises = ManyToManyField(Exercise, blank=True)
admin_created = models.BooleanField(default=False)
#Error code
psql:db/create_main_exercises.sql:49: ERROR: 23502: null value in column "admin_created" of relation "main_app_workout" violates not-null constraint
EDIT:
Thank you all for the comments. My solution to this problem was to provide true values for the admin_created for the seeded data. In addition I changed the admin_created field to
admin_created = models.BooleanField(null=True, default=False)
When I create new instances of the model in Django it automatically sets it to False.
Django is builded to use the ORM, if you are doing this insertion manually, Django can't set the defaul value for you, so will be passed NULL.
The field based constraints are only placed at the code level in django not at the DB level.
So if you 'll create a object in django programmatically you 'll not face this issue. But when created using SQL you 'll face this issue.
Only a few constraints are available that you can apply at the DB level that too post django 2.2.
Check the constraints documentation for django here

FOREIGN KEY constraint failed because of models.DO_NOTHING

I have this snippet of code for models.py
class Provider(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING)
provider = models.CharField(max_length=100, unique=True)
active = models.BooleanField(default=True)
when ever I tried to delete an object I faced an error says :
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
I faced this issue on django 2.x , since every thing was perfect on 1.11.
I made a little search I found may this issue happen by this part on_delete=models.DO_NOTHING, So how could I fix it with kepping every thing as it is ?
Basically you're telling Django to do nothing when you delete a user. So you will try to delete the row which has a related foreign key, this is expected behavior.
If you want to keep the provider model even when the user got deleted you have to make user nullable and use models.SET_NULL.
If provider has non sense in your logic you can then cascade.
If you need to reassign to a default user you can use custom method.

Django-postgress: multiple primary keys are not allowed

when I am useing django.db.backends.postgresql_psycopg2 and running manage.py syncdb, following error raised
django.db.utils.ProgrammingError: multiple primary keys for table "token_place" are not allowed
LINE 3: "signatureid" integer NOT NULL PRIMARY KEY REFERENCES "s...
model:
class TokenPlace(models.Model):
token = models.ForeignKey(Token, db_column='tokenid', primary_key=True)
signature = models.ForeignKey(Signature, db_column='signatureid', primary_key=True)
place = models.IntegerField(primary_key=True)
class Meta:
db_table = 'token_place'
my models work correctly with mysql but I must deploy it in postgres
how to fix this problem?
After reading your answer I finally get the question, you are looking for composite keys in Django. Unfortunately this is not supported by Django yet. If you need it there are a few options:
Try the Django Composite Key project: https://github.com/simone/django-compositekey
Use the patches and explanation given on this page to add the support to Django: https://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys
Use SQLAlchemy (http://www.sqlalchemy.org/) for querying as it does support this properly.
Use a single primary key column in Django and read/write from/to a writable view which communicates with the actual table in the background.

using uuid as id/pk in django breaks admin page

i am using django 1.0.4 and have 3 models: Category <-1-m-> Item <-1-m-> Image.
i recently changed the id/pk to uuid:
id = models.CharField(max_length=32, primary_key=True,
default=make_uuid, editable=False)
...
def make_uuid():
return str(uuid.uuid4()).replace('-','')
after i started using uuid, the Item's admin page would no longer let me inline add an Image. it would give me a form validation error even though there isn't any error. furthemore, if an Item has an Image, i can't change the Category, it would give me the following error:
KeyError at /admin/inventory/item/90965921681b4b69880b36bd716b0831/
id
...
/local/env/bfi2/lib/python2.6/site-packages/Django-1.0.4-py2.6.egg/django/forms/forms.py in _raw_value
213. field = self.fields[fieldname]
i think this is similar to the following bug: http://code.djangoproject.com/ticket/10992. ideally, i would like to avoid upgrading django and just patch the necessary files. has anyone else ran into this problem?
thanks,
steve
I've gone into such problems but they got solved with django-extensions UUID field.
But I cannot guarantee that this Field will work with an old django version, it was on 1.2.3

Django reading old model?

I changed the model, synced the db, and now when i do:
Prs = Products.objects.filter(PrName__icontains='bla')
I get the error:
ERROR: column search_products.pr_name does not exist
LINE 1: SELECT "search_products"."id", "search_products"."pr_name", ...
But pr_name was the old model, this is how the new model looks like:
class Products(models.Model):
PrName = models.CharField(max_length=255)
PrDescription = models.CharField(max_length=4000)
PrPrice = models.DecimalField(max_digits=5, decimal_places=2)
PrCompany = models.ForeignKey(Companies)
def __str__(self):
return self.PrName
Why am i getting this error? I synced the db 100 times, checked all the code, there is no reference to pr_name anywhere?
Have you tried restarting your server? If you are using anything other than the development server, you'll probably need to do that manually after making changes like this.
Unfortunately the thing you try to do is not supported by django out of the box :-(
but you can do it ether by adding a db_column to the fields or by exporting the data, removing the table from the database, edit the export file, recreate the database table and reimporting the data.
Also look at the various schema evolution solutions out there