I have a weird problem. I've added the below to the model. I have run migrations, but I still still get the error no such column: Linked_OKR
linked_OKR = models.ForeignKey(okrtasks, on_delete=models.CASCADE,db_column='okrid', blank=True, null=True)
Weirdly in the admin view, it also shows up not in bold, unlike all other columns
Any idea what's going on?
You have used:
db_column='okrid', blank=True, null=True
db_column='okrid': This signifies that that model will use okrid as the column name and not linked_OKR.
blank=True, null=True: This signifies that the field is optional and can accept blank and null values. Django admin does not bold this field since bold means required fields.
Related
When I am trying to run python3 manage.py makemigrations it shows :
You are trying to add a non-nullable field 'topic_id' to journey_template without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
enter code here
from django.db import models
class Topic_Table(models.Model):
topic_id=models.IntegerField(primary_key=True)
topic_name = models.CharField(max_length=100, blank=True)
weightage = models.CharField(max_length=15, blank=True)
grade = models.IntegerField( null=True)
subject = models.CharField(max_length=100, blank=True)
sequence = models.IntegerField(null=True)
month = models.CharField(max_length=15, blank=True)
class Journey_template(models.Model):
student_id = models.IntegerField(default=1)
topic_id = models.ForeignKey('Topic_Table',on_delete=models.CASCADE)
subtopic_id = models.IntegerField()
journey_template_key = models.IntegerField(primary_key=True)
How would I fix this?
You are adding the topic_id field on Journey_template model.
This model already has data on your database.
You have a few options:
1 - provide a default value (like entering the number 1)
2 - delete your database and start with a fresh migration
If you table already has data, adding a non-nullable column without any default will violate the non-null constraint. Django migration doesn't check the table for data, so it assumes there is some.
If your table has no rows, you can go ahead and give it any legal default value. The default does not change your model, it just gives Django a value it can fill in. Since there are no rows of data in the table, it will have no effect other than to make Django happy.
If you table has rows, then if you can think of a sensible value to populate the existing rows with, then use it. Your other option is to change the model by adding null=True to the field and Django will just put nulls in that field for existing rows. (Later, you can put your own values in to those fields with Django or other methods and change the field back to null=False if you like. You will get the same question when you migrate but the answer will have no effect if the fields are not null). null=False is the default for any field in your model.
I am using Django-Jet and have a model with many ForeignKey fields. For those fields I want their values retrieved dynamically via AJAX and not preloaded. One of the field is like this:
class Person(Base_Entity):
first_name = models.ForeignKey(
'Name',
null = True,
blank = True,
default = None,
verbose_name = _('first name of person'),
on_delete = models.SET_NULL,
related_name = 'is_first_name_of_%(app_label)s_%(class)s',
)
)
#staticmethod
def autocomplete_search_fields():
return 'first_name__name',
(The Name model has hundreds of entries, and there will be even more later)
It seems I cannot set that field to NULL in Django Admin (no line with dashes appears):
If I turn on autocomplete (i.e. remove the autocomplete_search_fields method), I do get that NULL entry, BUT I also get all the possible values preloaded in the HTML select, and that slows down the page loading to a point it is not usable.
I am using Django 2.1.4, Django-Jet 1.0.8 (I suspect the issue is closely related to Django-Jet)
Any help is appreciated.
I am using djangojet and this relation shows an empty value choice in admin ("-----"):
someModel_FK= models.ForeignKey(someModel,
related_name='this-model',
null=True,
blank=True,
on_delete=models.SET_NULL)
a - Remove django-jet and check on default admin.
b- Are you missing migrations ? is this "null=True,blank=True, " migrated to DB ?
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 changed my model from this:
class DistList(models.Model):
creator = models.ForeignKey(User, related_name='creator')
created_date = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=200, unique=True)
description = models.TextField(blank=True, null=True)
company = models.ForeignKey(Company, blank=True, null=True)
To this:
class DistList(models.Model):
creator = models.ForeignKey(User, related_name='creator')
created_date = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=200, unique=True)
description = models.TextField(blank=True, null=True)
company = models.ForeignKey(Company)
The only change was turning the company FK relationship from not required to required.
When I run the migration I specify a one off value that corresponds to the pk of the first company.
./manage.py schemamigration distlist --auto
? The field 'DistList.company' does not have a default specified, yet is NOT NULL.
? Since you are making this field non-nullable, you MUST specify a default
? value to use for existing rows. Would you like to:
? 1. Quit now, and add a default to the field in models.py
? 2. Specify a one-off value to use for existing columns now
? Please select a choice: 2
? Please enter Python code for your one-off default value.
? The datetime module is available, so you can do e.g. datetime.date.today()
>>> 1
But when I run the migration I get an error because it has a pending trigger event?
./manage.py migrate distlist
Running migrations for distlist:
- Migrating forwards to 0005_auto__chg_field_distlist_company.
> distlist:0005_auto__chg_field_distlist_company
FATAL ERROR - The following SQL query failed: ALTER TABLE "distlist_distlist" ALTER COLUMN "company_id" SET NOT NULL;
The error was: cannot ALTER TABLE "distlist_distlist" because it has pending trigger events
I'm not doing anything that seems weird from my point of view so I don't understand this error at all. Can anyone offer insight? I can post the full stack trace if it'll help but I feel like theres something obvious about south and postgresql that perhaps I'm missing?
So I believe I've found the answer. I think postgresql doesn't like altering schemas and adding data at the same time. I first created a datamigration:
./manage.py datamigration distlist add_default_values_to_existing_companies
Then I added this to the forwards method:
def forwards(self, orm):
"Write your forwards methods here."
for distlist in orm['distlist.Distlist'].objects.all():
distlist.company = orm['userprofile.Company'].objects.get(id=1)
distlist.save()
Then I altered the model to remove the blank and null from company.
Then I ran the schema migration and chose to specify a one off for the value as 1 (as I did in the question).
Then I edited that migration file thusly:
def forwards(self, orm):
# Changing field 'DistList.company'
# db.alter_column(u'distlist_distlist', 'company_id', self.gf('django.db.models.fields.related.ForeignKey')(default=1, to=orm['userprofile.Company']))
db.alter_column(u'distlist_distlist', 'company_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['userprofile.Company']))
I just commented out the generated line and removed the default=1 arg.
I don't know... maybe this isn't right but it seemed to work. Hopefully this will help someone.
I have following model.
class Comment(models.Model):
type = models.CharField(max_length=21, choices=OBJECT_TYPE_CHOICES)
program = models.ForeignKey(Program, db_column='object_id', to_field='id', null=True, blank=True)
article = models.ForeignKey(Article, db_column='object_id', to_field='id', null=True, blank=True)
Type field determine, which field (program or article) will be active. But when i try to add comment using Django admin panel, I get error: "Column 'object_id' specified twice". I understand why this error occurs, but don't understand how to fix it.
This type of behavior isn't supported by Django. Even if you managed to accomplish it, it's a dirty, dirty hack and will result in much cursing at you by any developer that should ever be so unfortunate as to inherit your code.
Use the contenttypes framework, specifically GenericForeignKeys: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations
The problem is because you're using the same name for two columns in database, I think you should use this:
https://docs.djangoproject.com/en/1.3/ref/contrib/contenttypes/