I am a beginner to Python/coding/web development, and am running into and error during deployment process.
I coded a matchmaking app using Python/Django. I am attempting to deploy this app using Heroku. I followed all the directions in terms of setting up server, initializing Git repo, created Profile, Gunicorn, etc. etc. etc.
I was able to git push heroku master.
However, when I actually try to sync my files into the database, it returns an error. I typed this: heroku run python manage.py make migrations.
I get the following error:
Running python manage.py migrate on ⬢ blooming-island-78995... up, run.1306
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute
django.setup()
File "/app/.heroku/python/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/app/.heroku/python/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/app/.heroku/python/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/app/.heroku/python/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/app/directmessages/models.py", line 9, in <module>
user_obj = User.objects.get(username='ayaspencer')
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py", line 381, in get
num = len(clone)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py", line 240, in __len__
self._fetch_all()
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py", line 52, in __iter__
results = compiler.execute_sql()
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql
cursor.execute(sql, params)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "auth_user" does not exist
LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user...
^
What does it mean by auth_user does not exist? Does this mean I need to create a superuser? I tried and it won't let me. When I do heroku run python manage.py createsuperuser, it gives me the exact same error.
Here is my models.py for Posting app
from django.db import models
from django.contrib.auth.signals import user_logged_in
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
def upload_location(instance, filename):
#extension = filename.split(".")[1]
location = str(instance.user.username)
return "%s/%s" %(location, filename)
class PostingMessageManager(models.Manager):
def get_num_unread_messages(self, user):
return super(PostingMessageManager, self).filter(read=False).count()
class PostMessage(models.Model):
subject = models.CharField(max_length=150)
body = models.CharField(max_length=3000)
service_being_requested = models.CharField(max_length=3000, null=True)
service_being_offered = models.CharField(max_length=3000, null=True)
sender = models.ForeignKey(User, related_name='sent_post_messages', null=True, blank=True)
receiver = models.ForeignKey(User, related_name='received_post_messages', null=True, blank=True)
sent = models.DateTimeField(auto_now_add=False, auto_now=False, null=True, blank=True)
read_at = models.DateTimeField(auto_now_add=False, auto_now=False, null=True, blank=True)
read = models.BooleanField(default=False)
parent = models.ForeignKey('self', related_name='parent_message', null=True, blank=True)
replied = models.BooleanField(default=False)
CERTIFIED = 'Yes'
NONCERTIFIED = 'No'
INDIFFERENT = 'Indifferent'
CERTIFICATION_CHOICES = (
(CERTIFIED, 'Yes'),
(INDIFFERENT,'Indifferent'),
)
CERTIFICATION_CHOICES_ME = (
(CERTIFIED, 'Yes'),
(NONCERTIFIED, 'No'),
)
should_they_be_certified = models.CharField(max_length=200,
choices=CERTIFICATION_CHOICES,
default=INDIFFERENT)
are_you_certified = models.CharField(max_length=200,
choices=CERTIFICATION_CHOICES_ME,
default=NONCERTIFIED)
def is_certified(self):
return self.should_they_be_certified in (self.CERTIFIED)
def dont_care(self):
return self.are_you_certified in (self.INDIFFERENT)
def iam_certified(self):
return self.are_you_certified in (self.CERTIFIED)
def __unicode__(self):
return self.body
objects = PostingMessageManager()
def get_absolute_url(self):
return (reverse('view_post_message', kwargs={'ps_id': self.id}))
class Meta:
ordering = ['-sent',]
def set_messages_in_session(sender, user, request, **kwargs):
post_message = PostMessage.objects.get_num_unread_messages(user)
request.session['post_num_of_messages'] = post_message
user_logged_in.connect(set_messages_in_session)
#class F(models.Model):
#certification = models.CharField(max_length=50, choices=CERTCHOICE)
#class Meta:
#model = PostMessage
#fields = ['certification']
Also, not sure if this will be of any help, but I did a search for clean_username and based on my readings from this Django custom user model in admin, relation "auth_user" does not exist
python2.7/site-packages/django/contrib/auth/backends.py:
123 return
124 user = None
125: username = self.clean_username(remote_user)
126
127 UserModel = get_user_model()
...
143 return user
144
145: def clean_username(self, username):
146 """
147 Performs any cleaning on the "username" prior to using it to get or
python2.7/site-packages/django/contrib/auth/middleware.py:
78 # persisted in the session and we don't need to continue.
79 if request.user.is_authenticated():
80: if request.user.get_username() == self.clean_username(username, request):
81 return
82 else:
..
94 auth.login(request, user)
95
96: def clean_username(self, username, request):
97 """
98 Allows the backend to clean the username, if the backend defines a
99: clean_username method.
100 """
101 backend_str = request.session[auth.BACKEND_SESSION_KEY]
102 backend = auth.load_backend(backend_str)
103 try:
104: username = backend.clean_username(username)
105: except AttributeError: # Backend has no clean_username method.
106 pass
107 return username
7 matches across 2 files
It seems you didn't migrate, can you try:
heroku run python manage.py migrate
And you don't have to heroku run python manage.py makemigrations since migration scripts are already there
try to run these two commands
heroku run python manage.py migrate auth
heroku run python manage.py migrate
I was stuck in the exact same problem for more than 4 days. Everything got fixed with me when I used Postgres instead of Sqlite, which you are presumably using because it's the default option that comes with django, so I recommend following this tutorial to use Postgres: Django Girls: Installing PostgreSQL
Good Luck!
Related
I had a model Profile which was an extension to my User model which was the ForeignKey of my Post model, but I changed it to an AbstractUser and now if I try migrating or running and refreshing the page the server I get an error.
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
bio = models.TextField(max_length=500,null=True)
from django.db import models
from django.conf import settings
from django.urls import reverse
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=100)
content = models.TextField()
def get_absolute_url(self):
return reverse('post-details', kwargs={'pk': self.pk})
settings.py
INSTALLED_APPS = [
...
'posts',
'users',
]
AUTH_USER_MODEL = 'users.User'
error message after I try migrating
Apply all migrations: admin, auth, contenttypes, posts, sessions, users
Traceback (most recent call last):
File "/home/user/Projects/DNF/Project/manage.py", line 22, in <module>
main()
File "/home/user/Projects/DNF/Project/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.10/dist-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 448, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/commands/migrate.py", line 295, in handle
pre_migrate_apps = pre_migrate_state.apps
File "/usr/local/lib/python3.10/dist-packages/django/utils/functional.py", line 57, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/state.py", line 566, in apps
return StateApps(self.real_apps, self.models)
File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/state.py", line 637, in __init__
raise ValueError("\n".join(error.msg for error in errors))
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
The field posts.Post.author was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
The field users.Profile.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
I easily solved it by deleting all the migration files in the migrations folder except the init.py file. And also delete db.sqlite3. Now run the following commands : python manage.py makemigrations and then python manage.py migrate. Now you'll have to create the super user once again, so for this just type the following commmand : python manage.py createsuperuser. Then it will prompt for username, email and password, so enter your credentials and all will continue to work properly once again I hope that this will be helpful.
try to directly reference the User model, not through settings
change the foreign key field to this:
author = models.ForeignKey("users.User", on_delete=models.CASCADE, null=True)
To have a reference to the User model, you should not do through settings directly instead you can use get_user_model() function. This function will return the currently active User model of project( the custom User model if one is specified, or User otherwise).
So change the foreign key field of your Post model like below:
from django.db import models
from django.conf import settings
from django.urls import reverse
from django.contrib.auth import get_user_model
User = get_user_model()
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
...
Reference: get_user_model() [Django-doc]
I created a model like this.
class BloodDiscard(models.Model):
timestamp = models.DateTimeField(auto_now_add=True, blank=True)
created_by = models.ForeignKey(Registration, on_delete=models.SET_NULL, null=True)
blood_group = models.ForeignKey(BloodGroupMaster, on_delete=models.SET_NULL, null=True)
blood_cells = models.ForeignKey(BloodCellsMaster, on_delete=models.SET_NULL, null=True)
quantity = models.FloatField()
But now I need to apply inheritance to my model, like this. [(models.Model) ---> (BaseModel)]
class BloodDiscard(BaseModel):
timestamp = models.DateTimeField(auto_now_add=True, blank=True)
created_by = models.ForeignKey(Registration, on_delete=models.SET_NULL, null=True)
blood_group = models.ForeignKey(BloodGroupMaster, on_delete=models.SET_NULL, null=True)
blood_cells = models.ForeignKey(BloodCellsMaster, on_delete=models.SET_NULL, null=True)
quantity = models.FloatField()
BaseModel is another model I created before but forgot to inherit it in my current model.
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status_master = models.ForeignKey(StatusMaster,on_delete=models.SET_NULL,default=3,null=True, blank=True)
I applied "python manage.py makemigrations" after changing (models.Model) ---> (BaseModel) and got this...
(venv) G:\office\medicover\medicover_bloodbank_django>python manage.py makemigrations
You are trying to add the field 'created_at' with 'auto_now_add=True' to blooddiscard without a default; the database needs something to populate existing rows.
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
You can accept the default 'timezone.now' by pressing 'Enter' or you can provide another value.
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
[default: timezone.now] >>>
Migrations for 'Form':
Form\migrations\0018_auto_20220622_2322.py
- Add field created_at to blooddiscard
- Add field status_master to blooddiscard
- Add field updated_at to blooddiscard
But after that when I am applying "python manage.py migrate". I am getting this error.
(venv) G:\office\medicover\medicover_bloodbank_django>python manage.py migrate
Operations to perform:
Apply all migrations: Form, Master, User, admin, auth, contenttypes, sessions
Running migrations:
Applying Form.0018_auto_20220622_2322...Traceback (most recent call last):
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.ForeignKeyViolation: insert or update on table "Form_blooddiscard" violates foreign key constraint "Form_blooddiscard_status_master_id_ffe293fa_fk_Master_st"
DETAIL: Key (status_master_id)=(3) is not present in table "Master_statusmaster".
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
post_migrate_state = executor.migrate(
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\migration.py", line 126, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards
schema_editor.add_field(
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\base\schema.py", line 522, in add_field
self.execute(sql, params)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\base\schema.py", line 145, in execute
cursor.execute(sql, params)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: insert or update on table "Form_blooddiscard" violates foreign key constraint "Form_blooddiscard_status_master_id_ffe293fa_fk_Master_st"
DETAIL: Key (status_master_id)=(3) is not present in table "Master_statusmaster".
And when doing "python manage.py runserver" getting this...
(venv) G:\office\medicover\medicover_bloodbank_django>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): Form.
Run 'python manage.py migrate' to apply them.
June 22, 2022 - 23:23:51
Django version 3.2.5, using settings 'App.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
NOTE:-
In StatusMaster table there's only two rows having id's 1 and 2.
That will not work, since BaseModel is a non-abstract model, and thus the BaseModel and the BloodDiscard share the same "primary key space": the primary key of the BloodDiscard is a ForeignKey to the BaseModel primary key.
Likely you do not want BaseModel to be a non-abstract model, but an abstract one, so you can rewrite BaseModel to:
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status_master = models.ForeignKey(
StatusMaster,
on_delete=models.SET_NULL,
default=3,
null=True,
blank=True
)
class Meta:
abstract = True
Remove the problematic migration file, make a new migration file, and migrate.
This is the error I was getting:-
django.db.utils.IntegrityError: insert or update on table "Form_blooddiscard" violates foreign key constraint "Form_blooddiscard_status_master_id_ffe293fa_fk_Master_st"
DETAIL: Key (status_master_id)=(3) is not present in table "Master_statusmaster".
as we can see:-
DETAIL: Key (status_master_id)=(3) is not present in table "Master_statusmaster".
it is telling me that in status_master, there is no "id" (PK) having the value "3".
however, in my base model:-
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status_master =
models.ForeignKey(StatusMaster,on_delete=models.SET_NULL,default=3,null=True, blank=True)
someone provided a default value "3" of "status_master" which does not exist. So, I simply just removed the default value and it got solved.
So I have been trying to implement a way to upload multiple images to a post. The way I did it is to have tables. One for the actual post, and one of the multiple images uploaded. I was planning to link them with a foreign key but it is not working. My terminal started throwing the error "TypeError: id() takes exactly one argument (0 given)" . It throws me this error whenever I migrate it.
I am not sure how to fix this.
MY code:
models.py
from django.db import models
from django.utils import timezone
from django.forms import ModelForm
from django.utils.text import slugify
from django.utils.crypto import get_random_string
from django.conf import settings
from PIL import Image
import os
DEFAULT_IMAGE_ID = 1
# Create your models here.
class Projects(models.Model):
title = models.CharField(max_length=30)
description = models.TextField(max_length=150)
publish_date = models.DateTimeField(auto_now=False, auto_now_add=True)
update_date = models.DateTimeField(auto_now=True, auto_now_add=False)
slug = models.SlugField(unique=True)
files = models.FileField(upload_to='files/', blank=True)
images = models.ImageField(upload_to='images/', height_field = 'img_height', width_field = 'img_width',blank=True)
img_height = models.PositiveIntegerField(default=600)
img_width = models.PositiveIntegerField(default=300)
#feature_images = models.ForeignKey(P_Images, on_delete=models.CASCADE, default=DEFAULT_IMAGE_ID)
feature_images = models.AutoField(primary_key=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
# Generates a random string
unique_string = get_random_string(length=32)
# Combines title and unique string to slugify
slugtext = self.title + "-" + "unique_id=-" + unique_string
self.slug = slugify(slugtext)
return super(Projects, self).save(*args, **kwargs)
class P_Images(models.Model):
p_file = models.ImageField(upload_to='images/', blank=None)
p_uploaded_at = models.DateTimeField(auto_now_add=True, auto_now=False)
#fk_post = models
fk_post = models.ForeignKey(Projects, on_delete=models.CASCADE)
The errorlog
Operations to perform:
Apply all migrations: admin, auth, contenttypes, projects, sessions
Running migrations:
Applying projects.0005_auto_20180823_0553...Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
output = self.handle(*args, **options)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle
fake_initial=fake_initial,
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/migrations/migration.py", line 122, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 525, in alter_field
old_db_params, new_db_params, strict)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 630, in _alter_field
new_default = self.effective_default(new_field)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 218, in effective_default
default = field.get_default()
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 775, in get_default
return self._get_default()
TypeError: id() takes exactly one argument (0 given)
I use a MySQL database for this. This error started popping up after I updated my tables to be able to link with each other. I plan the fk_post of the P_Images to contain the feature_image value of Projects for the foreign key.
005_migration.py
import builtins
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('projects', '0004_auto_20180823_0547'),
]
operations = [
migrations.AlterField(
model_name='p_images',
name='fk_post',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='projects.Projects'),
),
migrations.AlterField(
model_name='projects',
name='feature_images',
field=models.IntegerField(default=builtins.id),
),
]
please let me know if the migration.py tells you something or nothing.
You have something very bizarre in your migration:
models.IntegerField(default=builtins.id)
This is referring to the builtin id function, which requires an argument because it returns the internal ID of an object in Python. It has nothing to do with database IDs, and doesn't belong here at all. I can only guess that you were asked for a default when creating the migration and you just typed in id.
You should delete that default from the migration, but that may make it unable to execute. You could also try a default of 0, which makes sense there; but your actual models code shows that field as the primary key, so you presumably have another subsequent migration that changes the field again; and 0 wouldn't work as a pk.
If you're still in development and don't have any data you need to keep, I would suggest deleting your database and migrations completely and starting again with makemigrations.
I think this error occurred because you haven't set a default value to your foreign key. For your previous P_Images instances (before your current migration), they don't have a Projects id related to them.
The error text shown also confirms it:
return self._get_default()
TypeError: id() takes exactly one argument (0 given)
So try adding a default value :
DEFAULT_PROJECT = 1 # or the id of any project that does exist
fk_post = models.ForeignKey(Projects, on_delete=models.CASCADE, default = DEFAULT_PROJECT)
I'm creating a blog using Django and anytime I run manage.py migrate, I get the error below:
(venv) (C:\Users\KOLAPO\Anaconda3) C:\Programming\Websites\shelteratyourcrossroads\shelteratyourcrossroads>manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions, sites, taggit
Running migrations:
Applying blog.0001_initial...Traceback (most recent call last):
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\utils.py", line 62, in execute
return self.cursor.execute(sql)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 335, in execute
return Database.Cursor.execute(self, query)
sqlite3.OperationalError: table "blog_post" already exists
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Programming\Websites\shelteratyourcrossroads\shelteratyourcrossroads\manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\base.py", line 345, in execute
output = self.handle(*args, **options)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
fake_initial=fake_initial,
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\migrations\operations\models.py", line 96, in database_forwards
schema_editor.create_model(model)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\base\schema.py", line 295, in create_model
self.execute(sql, params or None)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\base\schema.py", line 112, in execute
cursor.execute(sql, params)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\utils.py", line 62, in execute
return self.cursor.execute(sql)
File "C:\Programming\Websites\shelteratyourcrossroads\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 335, in execute
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: table "blog_post" already exists
Here's everything in my models.py file:
from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from taggit.managers import TaggableManager
from ckeditor_uploader.fields import RichTextUploadingField
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
subtitle = models.TextField()
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, related_name='blog_posts')
image = models.ImageField(upload_to='posts/%Y/%m/%d', blank=True)
# body = models.TextField()
body = RichTextUploadingField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
tags = TaggableManager()
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', args=[
self.publish.year, self.publish.strftime('%m'),
self.publish.strftime('%d'), self.slug])
objects = models.Manager() # default manager
published = PublishedManager() # custom manager
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
image = models.ImageField(upload_to='users/%Y/%m/%d', null=True, blank=True)
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
def __str__(self):
return 'Profile for user {}'.format(self.user.username)
class Feedback(models.Model):
name = models.CharField(max_length=200, help_text="name of sender")
email = models.EmailField(max_length=200)
subject = models.CharField(max_length=200)
message = models.TextField()
date = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = "Feedback"
def __str__(self):
return (self.name, "-", self.email)
I'm stuck on that error. How do I fix it please?
Maybe faking the initial migration of blog app will help you. Try the following.
./manage.py migrate --fake blog 0001_initial
Django 3.2
The following worked for me:
delete all the migration files, including the initial migration. Then perform:
python manage.py makemigrations
python manage.py migrate
Every time I see this kind of question I wondered: if the model.py is ok, why does no one suggests (in the answer) dropping the wrong table and - instead - almost everybody suggests deleting all migration files? It's overkill!
If model.py is proper and ok now, then you can always do two things:
Edit migration files - instead of deleting them. If this doesn't work, then:
With SQL shell: drop a single (wrong) table by accessing it via SQLite or PostgreSQL - depending on the one that you are using. Also, you can edit and update it.
Update:
There are some cases when things get more tricky. If the problem is related to the foreign key that was added to the particular table in SQLite, then it's more difficult to solve the problem, than having the same issue but with PostgreSQL. The SQLite is lacking some very handy features like removing a column that has foreign keys. I had a few situations where the first error was related to some table that I needed to drop, but after that, another issue was with a foreign key. Because both problems were related to some model that had a one-to-many relation. That's why I recommend getting familiar with PostgreSQL. That will make it easier to solve this kind of situation without deleting a whole database.
I am havnig troulble about migrating..I first tried
python manage.py migrate qablog
and didn't work. so I tried
python manage.py migrate qablog --fake-initial
and didn't work too.. so I googled again and some people were talking about changing the settings.py so I changed some things like changing USE_TZ to false ..
python manage.py makemigrations qablog
worked well though...can anyone help me with this? ..
python version: 3.4.4
mysql server version: 5.7
django version: 1.10.3
The error log is like below:
C:\inetpub\wwwroot\test>python manage.py migrate qablog --fake-initial
Operations to perform:
Apply all migrations: qablog
Running migrations:
Applying contenttypes.0001_initial... FAKED
Applying auth.0001_initial... OK
Applying qablog.0001_initial... OK
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line
367, in execute_from_command_line
utility.execute()
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line
359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 294,
in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 345,
in execute
output = self.handle(*args, **options)
File "C:\Python34\lib\site-packages\django\core\management\commands\migrate.py
", line 224, in handle
self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps,
plan=plan,
File "C:\Python34\lib\site-packages\django\core\management\sql.py", line 53, i
n emit_post_migrate_signal
**kwargs
File "C:\Python34\lib\site-packages\django\dispatch\dispatcher.py", line 191,
in send
response = receiver(signal=self, sender=sender, **named)
File "C:\Python34\lib\site-packages\django\contrib\auth\management\__init__.py
", line 83, in create_permissions
Permission.objects.using(using).bulk_create(perms)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 452, in b
ulk_create
ids = self._batched_insert(objs_without_pk, fields, batch_size)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 1068, in
_batched_insert
self._insert(item, fields=fields, using=self.db)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 1045, in
_insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python34\lib\site-packages\django\db\models\sql\compiler.py", line 10
53, in execute_sql
for sql, params in self.as_sql():
File "C:\Python34\lib\site-packages\django\db\models\sql\compiler.py", line 10
38, in as_sql
result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
File "C:\Python34\lib\site-packages\mysql\connector\django\operations.py", lin
e 223, in bulk_insert_sql
return "VALUES " + ", ".join([items_sql] * num_values)
TypeError: can't multiply sequence by non-int of type 'tuple'
[manage.py]
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "swingqa.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
[models.py]
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
and for the migration file.. I looked inside the qablog > migrations folder and there are init and 0001_initial file.. init file is empty (it's just blank inside) and 0001_ initial file is like below
[0001_initial.py]
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-10 07:56
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('text', models.TextField()),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('published_date', models.DateTimeField(blank=True, null=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
I'd really appreciate for some help :-)
found a solution to this question by myself :-)
I don't really know the reason but
if you change operations.py file in this path below
C:\Python34\Lib\site-packages\mysql\connector\django
especially the part where def bulk_insert_sql function is,,from
def bulk_insert_sql(self, fields, num_values):
items_sql = "({0})".format(", ".join(["%s"] * len(fields)))
return "VALUES " + ", ".join([items_sql] * num_values)
to ...
def bulk_insert_sql(self, fields, placeholder_rows):
"""
Format the SQL for bulk insert
"""
placeholder_rows_sql = (", ".join(row) for row in placeholder_rows)
values_sql = ", ".join("(%s)" % sql for sql in placeholder_rows_sql)
return "VALUES " + values_sql
there will be no errors in doing python manage.py migrate qablog command.