Invalid model identifier in Django Fixture - python

My django fixture contains the following data:
- model: CkProject.NotificationType
pk: 1
fields:
name: comment
message: commented on your project
When I run python manage.py syncdb, it shows an error while loading the fixtures:
raise base.DeserializationError("Invalid model identifier:
'%s'" % model_identifier)
django.core.serializers.base.DeserializationError: Problem installing fixture
'....../source/apps/CkProject/fixtures/initial_data.yaml':
Invalid model identifier: 'CkProject.NotificationType'
I have even tried with a json file instead of YAML and same error is returned.
UPDATE:
Here is my models.py which is located in apps/Notification/models.py
class NotificationType(models.Model):
class Meta:
db_table = 'CkProject_notificationtype'
name = models.CharField(max_length=50)
message = models.TextField()
def __unicode__(self):
return self.name

You have probably moved your model from apps/CKProject/models.py to apps/Notification/models.py, so its app_label has changed and the model is identified by Django as Notification.NotificationType now. You should update your fixture accordingly.
Alternatively, you can also add app_label = 'CKProject' (see: app_label) to NotificationType's Meta object to make Django identify it as CKProject.NotificationType again.

Related

Changing db_table on Django doesn't work after migrations, and adding a user (AbstractUser) foreign key breaks __str__()

This is a 2 problem post, which i suspect are somehow connected.
My posts app on Django doesn't migrate properly (I think), and adding the 'author' (Users AbstractUser model) breaks my code with the error:
str returned non-string (type tuple)
whenever I try to add a row.
I changed the name of the table using db_table (so it will change Postss to Posts on the admin page) and added an output to the __str__ function, I tried a few variations of output for the str function but non of them worked. I even tried to comment it out. and still. no changes in the table name or the error. I tried changing my str functions a few times and got the same result. when deleting the str function, I still get that same result.
I have a few wild guesses about this situation:
it might not work with an abstract users class for some reason, and do not know to to work around this and why this happens at all. (removeing the author=... row resolves this problem but doesn't change the table name, but I do need the user fk there).
it might not be migrating properly due to my environment or python version Python 3.9.1(?).
PS: every change I have made included stopping the server from running and running the lines: python manage.py migrate and python manage.py makemigrations.
posts/models.py:
from django.db import models
from users.models import Users
class Posts(models.Model):
content = models.TextField(max_length=255)
author = models.ForeignKey('users.Users', on_delete=models.CASCADE, null=True)
timestamp = models.DateTimeField(auto_now_add=True, null=True)
class Meta:
db_table = 'Posts'
def __str__(self):
return self.content + " " + self.author.email + " " + self.timestamp
I will add my users model too:
from django.db import models
from django.contrib.auth.models import AbstractUser
# https://rahmanfadhil.com/django-login-with-email/
class Users(AbstractUser):
USERNAME_FIELD = 'email'
email = models.EmailField(unique=True)
REQUIRED_FIELDS = ['username'] # removes email from REQUIRED_FIELDS
def __str__(self):
return (self.email, self.username)
You are trying return a tuple, it must be a string.
def str(self):
return (self.email, self.username)
Use the new-style formatting in Python
Try this instead:
class Users(AbstractUser):
...
def __str__(self):
template = '{0.email} {0.username}'
return template.format(self)
class Posts(models.Model):
...
def __str__(self):
template = '{0.content} {0.author.email} {0.timestamp}'
return template.format(self)
or
def __str__(self):
return '{} {} {}'.format(self.content, self.author.email, self.timestamp)
Second Question:
If I understand your question correctly, then to change the label for the model, you need to use verbose_name:
class Meta:
verbose_name = 'Post'
verbose_name_plural = 'Posts'
With option db_table you change the name of the database table to use for the model.
And see explanation how it works, from Django: if you have an app bookstore (as created by manage.py startapp bookstore), a model defined as class Book will have a database table named bookstore_book.
Then db_table must be:
class Meta:
# your desired table name can you find in your database
db_table = 'appLabel_modelName'
To list the tables in the current database for PostgreSQL, you can run:
python manage.py dbshell
\dt
See also Django db_table
Try changing your __str__ method to this:
def __str__(self):
return self.content + " " + str(self.author.email) + " " + str(self.timestamp)
Also, you only need to migrate when you've made changes to the models not model methods.

Django migration returns unexpected name

I am trying to migrate a database, but every time I try it returns the error below. My app name is 'helloservice', but the table is 'customer' in the database 'pulse'. How do I tell Django not to use the helloservice prefix? If needed I followed a tutorial here, and am now trying to adapt the results to my own needs.
django.db.utils.ProgrammingError: (1146, "Table 'pulse.helloservice_customer' doesn't exist")
Use Meta class and set table name. Then the table name only set customer. It does not use prefix(app name). Then make migrations and set migrate.
class Customer(models.Model):
customer_email = models.EmailField()
password = models.CharField(max_length=20)
ccustomer_first_name = models.CharField(max_length=30)
customer_last_name = models.CharField(max_length=30)
class Meta:
db_table = "customer"

Django db migration stops working with "Meta" class

I'm trying to create a Django application, and I have a class like this in my models.py file:
class Identity(models.Model):
display_name = models.CharField(db_column = "DisplayName", max_length = 200)
When I run python manage.py makemigrations myApp, everything works as expected, and a migration file for the class is created.
The problem happens if the class in the model defines a Meta class as well:
class Identity(models.Model):
display_name = models.CharField(db_column = "DisplayName", max_length = 200)
class Meta:
app_label = "something"
Now, if I run the makemigrations command, I get a "no changes detected" message, and no migration file is generated:
> python manage.py makemigrations myApp
No changes detected in app 'myApp'
Please note that this was just an example, and the problem happens also if I run the command for the first time on a class with a Meta class defined, or if I delete the previously generated migration files.
I'm using Python 2.7.5 and Django 1.9.5 on Windows.
You don't have this in the Meta class do you?
managed = False

Django model error abstract or not installed?

I'm getting the following error when trying to run python manage.py syncdb command
CommandError: One or more models did not validate:
sms.message: 'originator' has a relation with model <class 'sms.models.message.Originator'>, which has either not been installed or is abstract.
models.py
class Originator(models.Model):
originator_name = models.CharField(max_length=11)
user = models.ForeignKey(User, related_name='originators')
class Message(models.Model):
content = models.TextField(help_text=_(u'The body of the message.'))
recipient_number = models.CharField(max_length=32)
sender = models.ForeignKey('auth.User', related_name='sent_sms_messages')
originator = models.ForeignKey(Originator,
related_name='Messages')
I don't see an issue tho! Can anyone else?
What I did notice is that when I remove the FK in Message to Originator the tables are created bar Originator which never gets created!
This is the model I'm adding to....
https://bitbucket.org/schinckel/django-sms-gateway/src/13b68d23f3a28c7d147c4a501965e2ad07f89cf7/sms/models/message.py?at=default
Maybe something else going on here?
Thanks
It installed when I added....
class Meta:
app_label = 'sms'
To the Originator class
Are you sure User is the auth.User model there? It seems to be referring to the Originator model itself, which is strange.
You should probably do the same as you do in Message, and just use the string auth.User as the target of the Originator.user FK.

Django syncdb error: One or more models did not validate

/mysite/project4
class notes(models.Model):
created_by = models.ForeignKey(User)
detail = models.ForeignKey(Details)
Details and User are in the same module i.e,/mysite/project1
In project1 models i have defined
class User():
......
class Details():
......
When DB i synced there is an error saying
Error: One or more models did not validate:
project4: Accessor for field 'detail' clashes with related field . Add a related_name argument to the definition for 'detail'.
How can this be solved..
thanks..
Gee we just had this one; and I answered...
You have a number of foreign keys which django is unable to generate unique names for.
You can help out by adding "related_name" arguments to the foreignkey field definitions in your models. Eg:
class notes(models.Model):
created_by = models.ForeignKey(User, related_name="note_created_by_user")
detail = models.ForeignKey(Details, related_name="noted_and_detailed")
See here for more. http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name

Categories

Resources