Django: Field 'object_id' expected a number but got 'fe2b1fd4313c' - python

I am getting this error while trying to save a model from the admin section using Django admin, this is the error Field 'object_id' expected a number but got 'id_b2cbfe2b1fd4313c'.. I am using django shortuuid package https://pypi.org/project/shortuuid/ to create id field in django, and i choose to use it because the inbuild UUID field keeps giving this error Django UUIDField shows 'badly formed hexadecimal UUID string' error? and the id looks like this id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True). What would be the problem witht the short uuid field.
Based on this, i quote:
If you filter on the ForeignKey, then Django will filter on the primary key of the target object, and that is normally an AutoField, unless you referred to another (unique) column, or defined another primary key as field.
But i dont know what the issue might be now
Models.py
class Channel(models.Model):
id = ShortUUIDField( length=16, max_length=40, prefix="id_", alphabet="abcdefg1234", primary_key=True,)
full_name = models.CharField(max_length=200)
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, related_name="channel")
Views.py
def channel_profile(request, channel_name):
channel = Channel.objects.get(id=channel_name, status="active")
context = {
"channel": channel,
}
return render(request, "channel/channel.html", context)

Your database is not sync with your migrations file, because your problem is easy to solve, Django is expecting an ID (integrer) and you are passing a string.
If you have not push your project into production you can delete the migration folder and migrate again, otherwise you need to update your migrations files to change the type for the UD field

Related

NOT_NULL contraint failed when adding foreign key to model in django

I am making a notes app. When I try to create a foreign key to link the user and its notes, im getting an error while using
python manage.py migrate
. I am very new to foreign keys, I looked at the Django docs, this is how they created a foreign key.
here's the code :
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.body[0:50]
here's the error :
django.db.utils.IntegrityError: NOT NULL constraint failed: new__api_note.author_id
Your issue is that that there are existing notes in the database that do not have a author_id field, but you have not set a default value and neither allowed to to be kept blank. Thus it's a IntegrityError to add the field.
You can solve this in 2 ways:
Allow the field to be blank
Delete the last migration in your migrations folder
Edit the author field like this:
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
Run makemigrations and migrate
Set a default value for the field
Delete the last migration from the migrations folder. You can also edit it but simply deleting it is easiest
Run makemigrations again
During make migration, it will prompt you if you want to provide a default value for the field. Select "Provie a one of value for now"
Type models.User.objects.all().first() or alternatively some other "defalt" author for existing notes
Run migrate
You can also solve the problem by removing all existing notes from the database

Django primary key error (Djongo driver)

I'm writing a website on Python, Django using MongoDB and Djongo (to connect Mongo with Django) and I want to be able to add and delete documents from the database using my website. But I have an error while doing it.
If I don't set primary key in my models then I can successfully add documents, but when try to delete have AssertionError (object can't be deleted because its id attribute is set to None), however when I check the database _ID field is there created automatically. If I do set primary key by primary_key = True in models.py I can successfully delete a document, but on insertion I got AssertionError (No exception message supplied).
Also, if primary key is not set, then I cannot access documents from admin panel, but can add them to the database (through admin panel); and if pk is set then from admin panel I can access, delete and edit, but cannot add a new document to the database.
This is my model:
class DevList(models.Model):
dev_num = models.CharField(max_length = 200 , primary_key = True)
dev_name = models.CharField(max_length = 200)
dev_descr = models.CharField(max_length = 200)
dev_type = models.CharField(max_length = 200)
If no pk is set, then I delete primary_key = True line
My view is simple post form and I use d.save() to save and d.delete() to delete.
Actually, Django by default provides an id field with every model which is by default set as primary key.
Now, when you can set other field as primary key by primary_key=True. But for smoother operation I will advice you to use unique=True on other fields.
dev_num = models.CharField(max_length = 200 , unique = True)
I had a similar problem using MongoDB + Django with the Djongo driver (cannot delete objects in the admin page of my website because the _id is not an integer but an ObjectID() wich is not recognized as a valid integer).
This is how I solved it (the quickest way) :
I set for my object an id with the models.PositiveIntegerField type and I use the primary_key argument with the True value) :
class MyObject(models.Model):
id = models.PositiveIntegerField(primary_key=True)
title = models.CharField(max_length=100)
other_field = models.TextField(blank=True)
def __str__(self):
return f"{self.title}"
This way, the _id of mongoDB is not used but the admin system still find a valid integer for the primary key. That has been tested succesfully, problem solved.

Django UUIDField modelfield causes error in Django admin: badly formed hexadecimal UUID string

I have a Django 1.8 project and on one of my models, I am using the new UUIDField like so:
class MyModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
I've also set up my admin.py:
#admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
pass
When I load the admin page to try to create an instance, I get an error:
ValueError at /admin/core/mymodel/add/
badly formed hexadecimal UUID string
I am able to create an instance no problem from the Django shell (./manage.py shell). Once I've done that though, I get the same error as before on the admin site even when viewing the list of object instances.
Any thoughts?
The problem is that I had an existing record in the DB with a default integer autoincrement id, before I had specific that the id field on my model was a UUIDField. The value of this field was just 1, which was not a valid UUID hex string.
Removing this record fixed my issue.

MySQL gives an "Unknown column 'user.id' in 'field list'" error using Django's automatic id

I have my User model set up with no primary key so that the automatic id will be used instead. However, when I try to access it using Django's "_set" notation when it is referenced through a foreign key:
def postDetails(request, pk)
post = Post.objects.get(pk=pk)
if post.user_set.all(): # Errors on this line
[...]
I get an error from MySQL:
OperationalError at /webApp/postDetail/42/ (1054,
"Unknown column 'user.id' in 'field list'")
What am I doing wrong? Should I be accessing it differently? Are there limitations to the automatic id?
Model for reference:
class Post(models.Model):
name = models.CharField(max_length=128)
blog = models.ForeignKey('Blog')
active = models.BooleanField(blank=True)
created_date = models.DateTimeField()
class Meta:
managed = False
db_table = 'post'
def __unicode__(self):
return self.name
class User(models.Model):
level = models.ForeignKey(Level)
post = models.ForeignKey(Post)
name = models.CharField(max_length=64)
note = models.CharField(max_length=4096)
active = models.BooleanField(blank=True, default=True)
class Meta:
managed = False
db_table = 'user'
Something else that I thought to include: I did run syncdb before running this.
EDIT : wrong answer. check comments below
The problem is that you have managed set to False. According to the documentation
If False, no database table creation or deletion operations will be performed for this model. This is useful if the model represents an existing table or a database view that has been created by some other means. This is the only difference when managed=False. All other aspects of model handling are exactly the same as normal. This includes
Adding an automatic primary key field to the model if you don’t declare it. To avoid confusion for later code readers, it’s recommended to specify all the columns from the database table you are modeling when using unmanaged models.
You will need to define the primary key as this is not done by default anymore.
Not 100% sure, but I think even though Django will add the id field to the model class, that field will not propagate to the DB with syncdb.
One way to try it would be to rename the existing User table, run syncdb and see if the User table is created. If not (which is likely because of the managed flag) try again with managed=True. If the id field appears in this case then my guess is you'll have to add it manually to the User table with the same parameters as the automatically created one.

Duplicate model field in Django

A duplicate model field is giving me trouble (no such table appname_modelname when I run my webpage). Whenever I do ./manage.py migrate appname, it gives me "duplicate field". I checked my models.py, there is only one of them there. How do I delete that duplicate field? It seems no matter what I do, it stays. I've tried:
Deleting the database
Deleting migrations folder in app folder
Doing ./manage.py sqlclear south and then dropping the south_migrationhistory table in the dbshell
./manage.py schemamigration appname --initial, ./manage.py migrate appname --fake
I've run out of ideas.
class Document(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True, default=None)
identity = models.CharField(max_length=255, default=None, null=True)
user = models.ForeignKey(User, null=False)
user_id = models.IntegerField(User, null=True)
docfile = models.FileField(upload_to=_upload_path, storage=fs) # upload_to is a path inside the storage path
def get_upload_path(self,filename):
return str(self.user.id) + '/' + str(date.today()) + '/' + filename
You can't do this, for your user foreign key, Django ORM will create a database field named user_id (your foreign key field name plus _id) to use it as a FK in the database.
You don't have to create this field yourself (the ORM will take care), even if you need it, change the name of the attribute user or user_id.
From the documentation:
Behind the scenes, Django appends "_id" to the field name to create its database column name. In the above example, the database table for the Car model will have a manufacturer_id column. (You can change this explicitly by specifying db_column) However, your code should never have to deal with the database column name, unless you write custom SQL. You’ll always deal with the field names of your model object.
Not sure but problem causing here in these two line
user = models.ForeignKey(User, null=False)
user_id = models.IntegerField(User, null=True)
Better to use "related name" attribute to avoid the duplicate error as in database "user" will be added as user_id.
user = models.ForeignKey(User, related_name="id_user") # Change the related field as your convenience
user_id = models.IntegerField(null=True, related_name="user_id")
Check if this resolve your issues

Categories