I'm trying to extend the User model of a django app, but I keep getting the error:
OperationalError at /admin/auth/user/3/
Exception Value: no such column: subjects_subject.user_id
My Code:
#subjects/models.py
from django.contrib.auth.models import User
from django.db import models
class Subject(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=100)
models.signals.post_save
#_admin/admin.py
from django.contrib.auth.models import User, Group
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from .extended_admin import new_admin
from django.contrib import admin
from subjects.models import Subject
class SubjectInline(admin.StackedInline):
model = Subject
can_delete = False
verbose_name_plural = 'subject'
class UserAdmin(UserAdmin):
inlines = (SubjectInline, )
new_admin.register(User, UserAdmin)
new_admin.register(Group, GroupAdmin)
I have pretty much copied Django's own documentation word for word. Any help would really be appreciated!
EDIT:
I also wanted to say that I have ran syndb and flush
I had the same issue and here are the steps I took to solve it. You did not specify the database you are using but in my case I am using MySQL. From Django docs here https://docs.djangoproject.com/en/1.8/topics/migrations/#mysql it seems sometimes creating the tables fails. I had a table called 'administration' and that kept failing to detect any changes.
Here is what I did:
Remove migration directory from my app. This was so as to create new migration schemas
Rename the directory. I renamed my directory from 'administration' to 'donor'. For some weird reason this seemed to fix the issue. I am not entirely sure why but could be 'administration' is a key word in either MySQL or Django
If both steps do not work, you might have to manually add the changes as directed on the django docs. Even easier, you can drop the existing table if its empty and recreate it. (WARNING! Please only do this if the table is empty otherwise you risk losing all your data)
All in all, there seems to be no outright reason as to why this could be happening at the moment. My trial and error approach seems to have fixed it.
Did you solved this problem?
I had the same issue , after different trying , I solved this. I'm using sqlite3 .
it seems like the when you first migrate , there is something wrong with the database table (I don't know what this problem caused by , so you raise the error : no such column: subjects_subject.user_id)
if you remove the migrations directory , and re-migrate , that will not solve this problem , because Django keeps track of all the applied migrations in django_migrations table.Migration was faked because the table already existed (probably with an outdated schema)SO I delete all the rows in the django_migrations table.
Here is what I did:
1.remove all files in migrations directory in my django app
2.using python manage.py dbshell , then DELETE FROM django_migrations WHERE app='your-app-name or DELETE FROM django_migrations WHERE ID='your-first-migrate
3.then python manage.py makemigrations python manage.py migrate
Successful!
Related
I am new to Django and web development in general. I am trying to test my app, recipe_book, using the admin page.
When try to login at http://127.0.0.1:8000/admin, I get the following error:
no such table: recipe_book_user
I have a model class named "User", defined below:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
pass
I then successfully made migrations and migrated the changes.
To resolve this issue, I've tried registering the User class in admin.py, with no success. I've also tried following the steps to reset the database in the following question:
Django - no such table exception
Does anyone know how I can resolve this?
I resolved this - it turns out that my migrations weren't being created. I had been typing python manage.py makemigrations instead of python manage.py [app_name] in my initial migration. Problem solved!
So I've got an API built in Django with Django Rest Framework and I now want to add a role based access control to it. For this I found the django-rest-framework-roles extension. I've got it installed, but I'm not really familiar with the usual authentication system in Django. It says I need to define the groups in the settings as
ROLE_GROUPS = [group.name.lower() for group in Group.objects.all()]
So I need the Group model and of course also the User model. As far as I understand, these are standard models. However, I don't have any tables in my DB for them. So I need a migration for it, but I'm unsure how I can do that.
I guess it should be really easy, but even on the relevant pages in the documentation I don't see any mention on how to add these models to my Django installation.
Could anybody enlighten me on this?
In your settings.py you have something like this:
INSTALLED_APPS = [
...
"django.contrib.auth",
...
]
That app has the Group and User models(included django app), so the first thing that you will do after config the database is migrate with this command./manage.py migrate, after migrate you can use importing them like this: from django.contrib.auth.models import User, Group
The standard User model in django has the table name auth_user.
The standard Group model has the table name of auth_group.
The database tables themselves are created once you have ran your first migration script after starting your project.
This is done from the command line with:
$ python manage.py migrate
I have several apps in my Django 2.0.2 project. One of the apps (app_one) has a migration that depends on migrations from the other app (app_two) being installed. It is initial migration of app_one and it looks like this:
def import_data(apps, schema_editor):
schema_model = apps.get_model('app_two', 'Model')
# do import
def drop_data(apps, schema_editor):
schema_model = apps.get_model('app_two', 'Model')
# undo import
class Migration(migrations.Migration):
dependencies = [
('app_two', '0005_auto_20180127_2155')
]
operations = [
migrations.RunPython(
import_data,
reverse_code=drop_data
)
]
Currently in order to install the database I need to manage.py migrate app_two and only after that do manage.py migrate, because otherwise I get an error on this migration that relation Model from app_two does not exist. Also I'm unable to run tests manage.py test normally due to the same error. It seems that Django ignores dependency in this migration for some reason. How do I fix that?
Check out the docs about ordering your migrations:
https://docs.djangoproject.com/en/2.0/howto/writing-migrations/#controlling-the-order-of-migrations
IDK wat's happening, but today I made some changes to migrations like adding run_before and the issue was gone. BUT! I rolled all changes back, droped all the related databases and the bug didn't came back. The code is literally the same as it was when I posted the question...
Take a look at the Django documentation regarding the configuration variable MIGRATION_MODULES.
Link to doc: https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-MIGRATION_MODULES
I am trying create a new model with Django, but I keep running into the error Lookup failed for model referenced by field help.HelpDefinition.org: account.Organization. Organization has been imported. You can see the model below.
models.py
org = models.ForeignKey(Organization, unique=True)
help_type = models.CharField(max_length=255, choices=HELP_CHOICES)
help_content = models.TextField(blank=True)
This model has been successfully migrated previously. I dropped the table via psql in Postgres so that it could be recreated.
It happens when you change the target objects in relationship. Even if they have the same name and fields they are not the same objects. I had the same issue and deleting all previous migrations from migrations folder solved it.
You can also add as a dependency to the migration the last migration from the object's app. That did the trick for me.
class Migration(migrations.Migration):
dependencies = [
(<app>, <last_migration_filename>),
...
My case was: moving away from South I deleted almost all migration files from several apps and applied makemigrations and migrate and later on I found out some forgotten migrations in one app and I tried to do the process (delete/makemigrations) only for this one app. But going back one step and recreating the migrations for ALL the apps fixed the issue for me.
I've a table name UGC and would like to clear all the data inside that table. I don't want to reset the entire app which would delete all the data in all the other models as well. Is it possible to clear only one single model? I also have South configured with my app, if that would help.
You could use raw SQL :
cursor.execute(“DROP TABLE UGC”)
or you could just use the ORM directly inside a Django shell :
UGCModel.objects.all().delete()
That would erase the data (not the table, though), so you have to be careful :)
Another way (for completeness and to make use of South) would be to comment out the model in your models declaration, migrate and then put it back again (assuming there are no models with a reference to it.)
HTH
In the admin interface, you can go to the list page for that model, then you can select all models and use the Delete selected ... action at the top of the table.
Remember that, in whatever way you delete the data, foreign keys default to ON DELETE CASCADE, so any model with a foreign key to a model you want to delete will be deleted as well. The admin interface will give you a complete overview of models that will be deleted.
Faced such issues today with django 2.0.2 because i created my model with
class Front(models.Model):
pass
and migrated it but when i later updated the model, i couldn't run
python manage.py makemigrations because it was saying
You are trying to add a non-nullable field 'update' to front 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:
What was my solution?
I choose option 2 which is to quit
I commented out the troublesome model/table which is Front in my case
I ran python manage.py makemigrations which deleted the troublesome table/model
I uncommented my model and ran python manage.py makemigrations again which recreated the table/model and finally
I migrated my changes with python manage.py migrate and everyhing was resolved!
Note: Be careful with the above instruction cause it will delete all references/foreign keys to the table/model with on_delete=models.CASCADE which is the default!
Django 3.1.14
If you're interested in doing it on the command line, and you'll be doing this type of cleaning of your db frequently, I do this:
# project_name/app_name/management/commands/clear_test_models.py
from django.core.management.base import BaseCommand
from django.apps import apps
keep_models = ['KeepModel0', 'KeepModel1']
class Command(BaseCommand):
"""
clear all in app_name app except listed in keep_models list
"""
help = 'clear all models except those listed in keep_models list'
def handle(self, *args, **kwargs):
my_app = apps.get_app_config('app_name')
my_models = my_app.get_models()
for model in my_models:
if model.__name__ not in keep_models:
model.objects.all().delete()
To run on the command line:
DJANGO_SETTINGS_MODULE=app_name.settings.local python manage.py clear_test_models