ValueError in models.py - django

Here is my models.py file. When I try to migrate it gives me an error.
I changed Class name and it gives me an error. Now if I put even old name, it gives me the same error
from django.db import models
from tinymce.models import HTMLField
class BlockTags(models.Model):
pass
class BlockTags_Text(models.Model):
text = models.CharField(max_length=300, verbose_name='Заголовок 1', null=True, blank=True)
block = models.ForeignKey(BlockTags, related_name="text", verbose_name='Заголовок 1', on_delete=models.CASCADE, null=True,blank=True)
number = models.DecimalField(max_digits=3, decimal_places=0)
ValueError: The field content.BlockTags.text was declared with a lazy reference to 'content.blocktags_text', but app 'content' doesn't provide model 'blocktags_text'.
(venv) appledeMacBook-Pro:letbuycar apple$

app 'content' doesn't provide model 'blocktags_text'.
This means that django doesnt see a blocktags_text model in your models.py, try running makemigrations and then migrate, also try adding at least one field to your empty model.

Related

Django migration issue for boolean field

I have models and there was no Boolean field in the very beginning when i run makemigraiton and migrate
In that mean time, i added some post...
later i added new field called is_printable as boolean field...
this is my current models:
from django.db import models
import datetime
from django.utils import timezone
Create your models here.
class Article(models.Model):
title = models.CharField(max_length=50)
body = models.TextField()
category = models.CharField(
null=False,
blank=False,
max_length=50,
)
is_printable = models.BooleanField()
date = models.DateTimeField(timezone.now)
when i add
is_printable = models.BooleanField()
I cant run migrate command, it throws me an error called
django.core.exceptions.ValidationError: ["'2019-07-07 06:56:52.693378+00:00' value must be either True or False."]
What is possible solution for this?
When you added is_printable field and ran makemigrations Django would've asked you to enter default value for the newly added field, what is the default value you gave? I presume you gave timezone.now() and because of that it would've thrown error during migrate.

Making use of the users table, causing an error

In Django (2.x) I have an entry form, the model is here:
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
class Sample(models.Model):
sample_id = models.AutoField(primary_key=True)
area_easting = models.IntegerField()
area_northing = models.IntegerField()
context_number = models.IntegerField()
sample_number = models.IntegerField()
# taken_by = models.IntegerField()
taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.PROTECT)
def __str__(self):
return str(self.sample_id)
class Meta:
db_table = 'samples\".\"sample'
#ordering = ["sample_id"]
managed = False
#verbose_name_plural = "samples"
This works as expected, a list of usernames drops down (while I would like to format - firstname lastname). However, when I return to the main viewing page I see an error.
django.db.utils.ProgrammingError: column sample.taken_by_id does not exist
LINE 1: ...text_number", "samples"."sample"."sample_number", "samples"....
^
HINT: Perhaps you meant to reference the column "sample.taken_by".
Clearly Django is adding the _id to the table name causing the error, I expect because it is a foreign key.
Any ideas how to remedy this behaviour?
You can explicitly set the underlying db column via the db_column attribute:
taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='taken_by', on_delete=models.PROTECT)
https://docs.djangoproject.com/en/2.1/ref/models/fields/#database-representation
^ link to the docs where it specifies that it creates a _id field.
based from the error message you have posted. It seems that your database schema is not updated.
you might need to do manage makemigrations and migrate to apply your model changes to your db schema
e.g
$ python manage.py makemigrations
# to apply the new migrations file
$ python manage.py migrate

Django admin gives error "'Model' object has no attribute 'field_name'" after field name change

To improve my code and database, I needed to change the field name in a model away from a value that was confusing and close to a reserved word.
The original model was effectively this:
class Company(models.Model):
my_old_name = models.CharField(max_length=100, db_index=True)
The new model is effectively this:
class Company(models.Model):
my_new_name = models.CharField(max_length=100, db_index=True)
I ran:
python manage.py makemigrations my_app
and the migration code was this:
class Migration(migrations.Migration):
dependencies = [
('my_app', '0004_auto_20160605_1852'),
]
operations = [
migrations.RenameField(
model_name='company',
old_name='my_old_name',
new_name='my_new_name',
),
]
And then I executed:
python manage.py migrate
The site runs fine. All the pages show up and use 'new_name' as desired. However, I cannot use the admin site to administrate the database. It throw the error:
Error during template rendering
In template /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/s... error at line 91
'Company' object has no attribute 'my_old_name'
I've been at this for a while with no luck. Any help would be appreciated.
As an addendum to the first suggestion, this is the contents of admin.py:
from django.contrib import admin
from .models import Company, Parameters
admin.site.register(Company)
admin.site.register(Parameters)
It doesn't contain 'my_old_name'...
OK, found the error. The class model definition also contains the code:
def __str__(self):
return self.my_old_name
Changing it to:
def __str__(self):
return self.my_new_name
solved the problem. I missed this bit of code which tells admin what to display. (The model is more complex and contains another few dozen lines than snippets that I posted.)

django-taggit on models with UUID as pk throwing out of range on save

I have models that uses UUID as its PK
class Foo(models.Model):
foo_id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)
tags = TaggableManager()
When I go and try to add a new tag
f = Foo.objects.latest('pk')
f.tags.add("testing")
I get DataError: integer out of range
When I import pdb on the cursor to view the SQL going in I see this.
(Pdb) params
(1, 287082253891563438098836942573405313042, 9)
(Pdb) sql
'INSERT INTO "taggit_taggeditem" ("tag_id", "object_id", "content_type_id") VALUES (%s, %s, %s) RETURNING "taggit_taggedit
m"."id"'
That long integer (287082253891563438098836942573405313042) trying to be insterted is obvsiouly the cause for the error. This number is the int of the UUID for foo_id
In [6]: foo.foo_id.int
Out[6]: 287082253891563438098836942573405313042
Is there something I can set to allow django-taggit to play nicely with contenttypes and UUID?
I'd like to extend #Pramod response, that was very helpful for me to find the right answer:
Taggit has another class that allows to change the behavior of the TaggedItem
Here is a snippet of how to implement this solution:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from taggit.managers import TaggableManager
from taggit.models import GenericUUIDTaggedItemBase, TaggedItemBase
class UUIDTaggedItem(GenericUUIDTaggedItemBase, TaggedItemBase):
# If you only inherit GenericUUIDTaggedItemBase, you need to define
# a tag field. e.g.
# tag = models.ForeignKey(Tag, related_name="uuid_tagged_items", on_delete=models.CASCADE)
class Meta:
verbose_name = _("Tag")
verbose_name_plural = _("Tags")
class Food(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
# ... fields here
tags = TaggableManager(through=UUIDTaggedItem)
source: http://django-taggit.readthedocs.io/en/latest/custom_tagging.html#genericuuidtaggeditembase
Here's an answer based on Austin's comment.
In django-taggit, references to tagged models are stored in a model named GenericTaggedItemBase under a field called object_id. The object_id field is hardcoded to models.IntegerField. So it's not possible to tag models having UUID primary keys. The code is located here.
If all your models that need to be tagged are of the same type (in this case, models.UUIDField), then you can set object_id's type to models.UUIDField.
Here are the changes that have to be made, assuming you're using virtualenvwrapper
Locate the taggit package in the site packages folder. ~/virtualenvs/<your_virtualenv>/lib/<python_version>/site-packages/taggit
Copy the taggit directory into your project.
Delete the taggit directory from site-packages
In the models.py file in taggit, replace
object_id = models.IntegerField(verbose_name=_('Object id'), db_index=True) with
object_id = models.UUIDField(verbose_name=_('Object id'), db_index=True)
Migrate taggit.
python manage.py makemigrations taggit
python manage.py migrate

Why is this giving me an MRO error?

I'm using Django 1.8rc1. When I try to do a makemigrations with this models.py:
from django.db import models
from datetime import datetime
class TrackedModel(models.Model):
created_date = models.DateField()
modified_date = models.DateField()
class Meta:
abstract = True
class Project(models.Model):
name = models.CharField(max_length=12)
due_date = models.DateField()
complete_date = models.DateField(default=datetime.now)
I am getting:
TypeError: Cannot create a consistent method resolution
order (MRO) for bases Model, TrackedModel
I can't even see where it would be getting confused over methods with such a simple abstract model. In case you're wondering, the Project model is inheriting from models.Model in the example but that was just to troubleshoot -- ultimately I want Project to inherit from TrackedModel.
What am I missing?
Figured it out. The migration history got me again. I had to clear out the files in my app's migrations folder. Apparently it had stored a previous set of models that were not set up right, during a previous migration.