Django Evolution error: 'ConnectionRouter' object has no attribute 'allow_syncdb' - python

I've searched for the solution on internet and here and didn't find one. It seems like something needs to be changed or added, or maybe I just did something wrong.
I recently started a new project with Django and although I know a little bit of web programming and python I'm totally new to Django.
Everything was ok until I decided to add a new column to my MySQL DB. So, I with easy_install I installed Django Evolution in my VirtualEnv, then I added "django_evolution" in my INSTALLED_APPS.
After this, I ran 'python manage.py syncdb'
Then I added a new field (preview) in my Models file:
from django.db import models
# Create your models here.
class posts(models.Model):
author = models.CharField(max_length = 30)
title = models.CharField(max_length = 100)
bodytext = models.TextField()
preview = models.TextField()
timestamp = models.DateTimeField()
After this I ran 'python manage.py evolve --hint --execute' command.
In the terminal I got an error: ConnectionRouter' object has no attribute 'allow_syncdb'
When I'm trying to access the page I get: 1054, "Unknown column 'myblog_posts.preview' in 'field list'"
It seems like for some reason a preview column can't be added to the DB with Django Evolution.
What I'm doing wrong?

Related

Problem in panel of Django3.0 after migrations

Why is the error appearing in django/admin? Migrations ok, I need to have 3 items in the table where I will have results.
class Robot(models.Model):
"""Robot model, speed and position simulation"""
product = models.IntegerField(choices=CHOOSE)
velocity = models.FloatField()
positionX = models.FloatField()
positionY = models.FloatField()
angleTHETA = models.FloatField()
class Meta:`enter code here`
verbose_name = "Robot"
verbose_name_plural = "Robots"
def __str__(self):
resum = self.get_product_display()
return resum
ProgrammingError at /admin/robot/robot/
column robot_robot.velocity does not exist
LINE 1: ...LECT "robot_robot"."id", "robot_robot"."product", "robot_rob...
====
Hello, can someone help me with the above problem, I keep getting this error:
django.db.utils.ProgrammingError: relation "robot_cleanrobot" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "robot_cleanrobot"
first migrations done
then pip install -r requirements.txt
python manage.py startapp
settings
makemigrations & migrate
add model
register a view
nothing helps me, I have done many times from scratch, even deleted the whole directory and also nothing,
I changed the model in the new project and nothing
At the beginning it worked ok for the first time, but when I added the float it all went down - I do not know what to do about it. Please help. Thx.
class CleanRobot(models.Model):
"""..."""
name = models.CharField(max_length=100, null=True, blank=True)
class Meta:
verbose_name = "CleanRobot"
verbose_name_plural = "CleanRobots"
def __str__(self):
return self.name
=================================
Ok, not working: ok step by step what i am doing:
i create a django project
enable (venv)
makemigrations
migrate
pip install -r requirements.txt
copy to settinigs_local project
python manage.py start app
change settings - add code -> reference to local + register application
add code to models
register models
makemigrations
migrate
runserver
dajngo/admin
... +Add is ok, by name entering I get error... I have other projects on my computer and they work normally... I have other projects on my computer and they work normally... not today I have deleted the whole folder for the 20th time...
You are getting the error because the database fields that you requested probably do not exist. Remember to run both makemigrations and migrate commands.
As #ElvinJafarov suggested, migrate the database before proceeding. You get the message about angleTHETA field because of constraints on the database - that’s completely normal. As stated in the message "This is because the database needs something to populate the existing rows".
At this point you can quit and manually define the default value in the models.py (press 2 in message prompt). After this change your Robot by setting a field default, so that Django can populate DB with the default value, e.g.:
angleTHETA = models.FloatField(default=0)
You can also change DB constraints by allowing it to have empty values.
angleTHETA = models.FloatField(null=True, blank=True)
In general, I advise you to read the documentation on migrations.
Update 1:
From your description it seems that first you ran makemigrations and migrate commands, and then created the model. It should be the other way around - first make the model, then run makemigrations. If it went well you should see something like this
and also you should have a new non-empty file in your app's migrations folder. Then run migrate command. You should see something like:
If something went wrong, post the message you did get.
Works:
I don't know which of these things worked but:
i had alpha name and alpha project name so i changed to alphaapp,
after migration 2 I created a new superuser
Maybe this will be useful for someone ;)

`wagtailimages` not found in reverse data migration for custom image field

TLDR: Getting error: LookupError: No installed app with label 'wagtailimages'. once the custom data migration is executed in wagtail which causes all tests to fail, as Django can't find the app after running the latest migration.
I needed to add a few custom fields to my image model in my wagtail installation that supports a Vue SPA.
I followed the guidelines in the docs here: http://docs.wagtail.io/en/v2.0/advanced_topics/images/custom_image_model.html
So, I created a custom image model along with custom rendition like this:
class CustomImage(AbstractImage):
alt_text = models.CharField(max_length=255, blank=True)
caption = models.CharField(max_length=255, blank=True)
admin_form_fields = Image.admin_form_fields + (
"alt_text",
"caption",
)
class CustomRendition(AbstractRendition):
image = models.ForeignKey(
CustomImage, on_delete=models.CASCADE, related_name="renditions"
)
class Meta:
unique_together = (
("image", "filter_spec", "focal_point_key"),
)
I also changed the WAGTAILIMAGES_IMAGE_MODEL setting to point to my new model:
WAGTAILIMAGES_IMAGE_MODEL = "pages.CustomImage"
I wrote a data migration with the help of this blog post which refers to this StackOverflow discussion:
# Generated by Django 2.1.10 on 2020-01-15 09:03
from django.db import migrations, models
def forwards_func(apps, schema_editor):
wagtail_image_model = apps.get_model("wagtailimages", "Image")
custom_image_model = apps.get_model("pages", "CustomImage")
tagged_item_model = apps.get_model("taggit", "TaggedItem")
django_content_type = apps.get_model("contenttypes", "contenttype")
db_alias = schema_editor.connection.alias
# Get images stored in default wagtail image model
images = wagtail_image_model.objects.using(db_alias).all()
new_images = []
for image in images:
new_images.append(
custom_image_model(
id=image.id,
title=image.title,
file=image.file,
width=image.width,
height=image.height,
created_at=image.created_at,
focal_point_x=image.focal_point_x,
focal_point_y=image.focal_point_y,
focal_point_width=image.focal_point_width,
focal_point_height=image.focal_point_height,
file_size=image.file_size,
collection=image.collection,
uploaded_by_user=image.uploaded_by_user,
)
)
# Create images in new model
custom_image_model.objects.using(db_alias).bulk_create(new_images)
# Leave all images in previous model untouched.
# Move tags from old image to new image model. Moving tags is
# a little different case. The lookup table taggit_taggeditem looks like this:
# id object_id content_type_id tag_id
# 1 1 10 1
# 2 1 10 2
# 3 1 10 3
# 4 1 10 4
# In our case, the object_id will be same for old and new image model
# objects. So, we have to only change the content_type_id
ct_custom_img_model, created = django_content_type.objects.using(
db_alias
).get_or_create(app_label="pages", model="customimage")
ct_wagtail_model = django_content_type.objects.using(db_alias).get(
app_label="wagtailimages", model="image"
)
tagged_item_model.objects.using(db_alias).filter(
content_type_id=ct_wagtail_model.id
).update(content_type_id=ct_custom_img_model.id)
def reverse_func(apps, schema_editor):
# We get the model from the versioned app registry;
custom_image_model = apps.get_model("pages", "CustomImage")
tagged_item_model = apps.get_model("taggit", "TaggedItem")
django_content_type = apps.get_model("contenttypes", "contenttype")
db_alias = schema_editor.connection.alias
# Move tags from new image model to old wagtail model
ct_extended_model = django_content_type.objects.using(db_alias).get(
app_label="pages", model="customimage"
)
ct_wagtail_model = django_content_type.objects.using(db_alias).get(
app_label="wagtailimages", model="image"
)
tagged_item_model.objects.using(db_alias).filter(
content_type_id=ct_extended_model.id
).update(content_type_id=ct_wagtail_model.id)
# Delete all images created in the new model
custom_image_model.objects.using(db_alias).all().delete()
class Migration(migrations.Migration):
dependencies = [
("pages", "0030_auto_20200115_0817"),
]
operations = [
migrations.RunPython(forwards_func, reverse_func),
]
The forward migrations work as expected to migrate all the data and work well when I tested these changes locally.
I tried to test my backward migration, and they also work fine.
However, if I try to get the old wagtailimages.Image model in my reverse_func function, it throws an error LookupError: No installed app with label 'wagtailimages'.
Although I actually wanted to delete the images from the old model just to perform cleanup, but due to this error, I thought that it is not that important and I can just move on.
Unfortunately, as soon as I pushed the code to CI, all my tests were failing as when this 31st migration which is a custom data migration is applied, Django seems to not find the wagtailimages app at all.
I'm not sure what is the issue here. I've been trying to debug this issue for a while now but all my efforts were futile. I also didn't find anything related to this on the web which might help.
I've also tried to simplify my migration like not doing barely anything at all and just trying to fetch the model using Django's apps.get_model. The forward migration works fine, but in reverse migration, it seems that wagtailimages app just vanishes. I'm not sure why django.setup() isn't able to load that app.
Can anyone help in this regard and provide me a pointer on where are things going sideways?
I just ran into this myself. Your migration seems to depend on models from other apps, wagtailimages is among them. You gonna want to list the labels of these apps with a migration (the latest when creating your datamigration) in the dependencies list for the migration.
You gonna need to find a migration name for each of the apps.
dependencies = [
("pages", "0030_auto_20200115_0817"),
("wagtailimages", "0023_add_choose_permissions"), # I am using Wgatail 2.16 here.
...
]
This exact error is actually explained in the Django docs.
wagtail.wagtailimages is now wagtail.images
Reference (see Old Name/New Name table)
Put wagtail.images in INSTALLED_APPS.

AttributeError: module 'django.db.models' has no attribute 'Models'

When I'm trying to migrate a new app onto the server i get this error
AttributeError: module 'django.db.models' has no attribute 'Models'- in terminal
I'm using PyCharm. I am very fresh to Django and web development so any tips will help. Thanks!
from django.db import models
# Create your models here.
class product(models.Model):
item = models.Textfiels()
description = models.Textfields()
price = models.Textfields()
There's no such class django.db.models.TextFields but this works for me on any recent version :
from django.db import models
class product(models.Model):
item = models.TextFiel()
description = models.TextField()
price = models.TextField()
You made 2 typos : the correct name is TextField and you typed Textfields (Python is case sensitive)
I suspect you didn't setup correctly your project under PyCharm. When correctly setup, it shows warnings on misspelled names (names underlined with red dots with default setting).
There's another variation to this question and that is in the form of:
AttributeError: module 'django.contrib.auth' has no attribute 'models'
As far as I can tell this is typically caused by conflicting imports or improperly imported files. Another cause could be changes to Django's updates but I'm not sure about that as I didn't find any documentation that changed that aspect of the Django library.
Short term solution to this is as follows:
from django.contrib.auth import models
class MyClass(models.User): """ """
This will allow you to at least test your runserver command and website on a browser of your choosing.
I'm still trying to figure out any other solutions to this problem that can be a fix for individually importing the 'auth' module itself.
At the time of this writing I'm using Django 2.2.6 whereas Django 2.2.7 is out and 2.2.8 is on the way to be released.
I'm not sure if this is the solution , but when I had this problem it was because in my admin.py file I had
from django.contrib import admin
from meetings.models import Meeting, Room
admin.site.register(Meeting, Room)
But changing it to solved the issue
from django.contrib import admin
# Register your models here.
from meetings.models import Meeting, Room
admin.site.register(Meeting)
admin.site.register(Room)

What is the correct way to reference nested django apps in ManytoManyFields

I'm trying to update an old django app from 1.1.x to 1.8 LTS, which has involved updating paths, as I apps move apps around.
However, I'm unable to generate migrations for one app, and I can't see how to reference a namespaced app model correctly (assuming that's the problem)
If I've moved files from PROJECT/news/models to PROJECT/site_name/news/models, how should I be referencing these models in in foreign keys or ManyToManyFields?
My app
I have a projects app I want to make migrations for. Projects in some_org/projects, and listed in installed apps like so:
INSTALLED_APPS = (
'some_org.maps',
'some_org.library',
'some_org.extras',
'some_org.news',
'some_org.projects',
'some_org.members',
'some_org.comments',
)
All the apps with the namespace are within the some_org directory.
Here's an abridged view of the models file in the projects app:
# some_org/projects/models.py
from some_org.library import Paper
class Project(models.Model):
name = models.CharField(max_length=30)
def get_children(self):
return ProjectPage.objects.filter(level=1, publish=True, project=self)
def has_library(self):
return Paper.objects.filter(projects=self).count() > 0
Calling ./manage.py makemigrations library, gives me this error:
ValueError: Lookup failed for model referenced by field library.Paper.projects: projects.Project
When I look in the Paper model, it looks like this:
class Paper(models.Model):
# snip
# NewsLinkSubject, Projects et al used to in an app on
# the project root, like `./app_name/models.py`, but is now
# in `some_org/app_name/models.py`
subjects = models.ManyToManyField("news.NewsLinkSubject", blank=True)
projects = models.ManyToManyField("projects.Project", blank=True,)
country = models.ForeignKey("maps.Country", null=True, blank=True)
I initially wonder if the label for the app is wrong, and try the projects ManytoMany field to:
projects = models.ManyToManyField("some_org.projects.Project", blank=True,)
This gives a different error:
ERRORS:
library.Paper.subjects: (fields.E300) Field defines a relation with model some_org.projects.Project', which is either not installed, or is abstract.
As far as I can tell the app is installed, and the models aren't abstract.
I'm pretty stumped - what am I doing wrong, and how can I fix this so I can make migrations for these apps?
I'm using Django 1.8.17, and Python 2.7.13.
You should define an app_label in the Meta class for your models. Whatever you put in there becomes the first part of the name you use in the ManyToManyField definition.

Data migrations for OneToOneField in django

I have a Product model and I want to extend by using OneToOneField.
For example
class Product:
name = models.CharField(..)
price = models.FloatField(...)
I want to do like this
class MyProduct:
product = models.OneToOneField(myapp.Product, on_delete=models.CASCADE)
location = models.CharField(...)
and using signal
def create_myproduct(sender, instance, created, **kwargs):
"""Create MyProduct class for every new Product"""
if created:
MyProduct.objects.create(product=instance)
signals.post_save.connect(create_myproduct, sender=Product, weak=False,
dispatch_uid='models.create_myproduct')
This works for newly created Product, so I can do like this in template.
{{ product.myproduct.location }}
But Old products that created before adding this OneToOneRelation,has no field 'myproduct' and that template code didn't work.
I heard I need a data migrations for old product using RunPython or manage.py shell. Can you teach me how to do? I read a documentation from django, but still don't fully understand.
you can add new migration. and apply it.
something like this code:
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-22 06:04
from __future__ import unicode_literals
from django.db import migrations, models
def create_myproducts(apps, schema_editor):
Product = apps.get_model('myapp', 'Product')
MyProduct = apps.get_model('myapp', 'MyProduct')
for prod in Product.objects.all():
MyProduct.objects.create(product=prod)
class Migration(migrations.Migration):
dependencies = [
('myapp', 'your last migration'),
]
operations = [
migrations.RunPython(create_myproducts)
]
I just found out.
Like Rohit Jain said
product.myproduct is None.
When I tried to access product.myproduct, I got an exception that object does not exist. It has a relation to myproduct but the actual object doesn't exist.
What I really want was creating MyProduct object and add it to Product class.
So I did it in python manage.py shell
products = Product.objects.all()
for prod in products:
if not hasattr(prod, 'myproduct'):
prod.myproduct = MyProduct.objects.create(product=prod)
prod.save()
I think it works for me now.
Thank you guys
You should just migrate your models in a normal way
python manage.py makemigrations
python manage.py migrate
During making migrations you will be asked how to fill new fields for existing data
Please notice that when you are using Django under 1.7 version you do not have migrations (and syncdb will not do the job for existing tables) - consider using the 3rd part tool like south

Categories