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.
Related
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.
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
I have added a new model to my admin. This is my models.py:
class EngineeringToolAttributeType(models.Model):
name = models.CharField(max_length=50)
description = models.CharField(max_length=255, blank=True, null=True)
api_url = models.CharField(max_length=255, blank=True, null=True)
api_field = models.CharField(max_length=50, blank=True, null=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.name
And the admin.py:
from extras.models import EngineeringToolAttributeType
from django.contrib import admin
class EngineeringToolAttributeTypeAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'api_url', 'api_field', 'active']
list_display = ('name', 'description', 'api_url', 'api_field', 'active')
admin.site.register(EngineeringToolAttributeType, EngineeringToolAttributeTypeAdmin)
When I try to add (click on add button via the admin), I get this error:
Internal Server Error: /website/admin/extras/engineeringtoolattributetype/add/
IntegrityError at /admin/extras/engineeringtoolattributetype/add/
null value in column "name" violates not-null constraint
This has never happened before. I know name is not allowed to be Null, but I'm still adding a record. How is that possible?
This issue is partially result of not using CharField and TextField properly. You should almost never use null=True on this fields and their subclasses.
https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.Field.null
Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.
I would highly suggest removing this param from yourCharFields and TextFields.
Also just to be sure run ./manage.py makemigrations && ./manage.py migrate.
This has a short answer here.
If you specify a field as not null field django will ask you to either provide a default value in code itself or it will ask you to provide a default value when you run migrations.
A better approach would be to provide some sane default in your models.py itself. After that run python manage.py makemigrations and python manage.py migrate. You should be fine.
I have below model:
class Property(models.Model):
job = models.ForeignKey(Job, on_delete=models.CASCADE)
app = models.ForeignKey(App, on_delete=models.CASCADE)
name = models.CharField(max_length=120)
value = models.CharField(max_length=350, blank=True)
description = models.TextField(blank=True)
pub_date = models.DateTimeField('date_published', default=timezone.now)
class Meta:
verbose_name_plural = "properties"
unique_together = (('value', 'name'),)
def __str__(self):
return self.name
When I try to create a Property object in admin page (I'm using Django Suit) with name/value which are already exist I get the exception: "Property with this Value and Name already exists." So it works perfect.
But in manage.py shell:
>>>from myapp.models import App, Property, Job
>>>from django.shortcuts import get_object_or_404
>>>app = get_object_or_404(App, app_name='BLABLA')
>>>job = get_object_or_404(Job, job_name='BLABLA2')
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>
In this case I do not get any exceptions and objects are added in database.
I tried makemigrations, migrate and migrate --run-syncdb.
Django 1.9.12, sqlite3
The unique constraints are enforced at database level. You're not getting any error probably because SQLite doesn't support this type of constraint. You cannot add constraint to existing table in SQLite. If you're in early development stage, drop the table and recreate it with updated constraints. Then it should work fine in shell.
Check SQLite alter table docs for allowed updates on an existing table.
The admin form throws error because it checks uniqueness by itself without relying on database constraints.
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.