Why is Django having trouble accessing my User table? - python

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!

Related

How to create users and groups migrations in Django?

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

Django- Why I am getting this Programming Error

Django- Why I am getting this Programming Error When I have not declared shop_product variable anywhere .
Please help Click here to view error Image
please refer to this image of error
shop_product is the name of the database table for the model Product in the application shop.
Most likely cause for this error is that you didn't apply database migrations, or, if you did, that you didn't add the application shop to your INSTALLED_APPS.
Update:
According to one of your comments, you are trying to use SQLite, which you cannot use on Heroku, see https://devcenter.heroku.com/articles/sqlite3
But it seems you figured that out because according to the settings of your app, you are using PostgreSQL, but you have not applied your migration.
Migrations are created once with manage.py makemigrations, but you have to apply them on every database, i.e. both on your local dev environment and on the database your application running on Heroku uses. For the latter, try this:
heroku run python manage.py
From the partial SQL query in the image it seems that "shop_product" is a table.
Note:
LINE 1: ... "shop_product"."id" FROM "shop_product"
Check your models if you have ShopProduct model, and check if you have migrations are updated.
Check if you have ManyToMany fields that might create that table, and also check if migrations are up to date.

OperationalError occurred while adding new fields in Django

I have a web app I've been managing for months, and I attempted to make some updates on my app. I added new fields to the existing class, but django raised an error.
These are what I've done.
1. Added a new field to an existing model.
class ExistingModel(models.Model):
# Existing Fields
new_field = models.IntegerField()
2. Attempted to make migration
$ python manage.py makemigrations
However, it raised django.db.utils.OperationalError: no such column during this process.
I added django.contrib.sites to INSTALLED_APPS in settings.py.
My django version is 2.0.3.
How can I add new fields to the existing model?

Django dropped table still exists

Having problems with a model in one of my django apps.
I can make an instance of the model, but when I go to access it, I get an error:
# create and save model instance
user_form = UserSearchForm(user=user)
user_form.save()
# Then later
first_user_form = UserSearchForm.objects.all()[0]
(1146, "Table 'project.app_tablename' doesn't exist")
Request Method: GET
Request URL: http://10.0.75.1:8000/search/
Django Version: 1.9.5
Exception Type: ProgrammingError
Exception Value:
(1146, "Table 'project.app_tablename' doesn't exist")
Exception Location: /opt/project-venv/lib/python3.4/site-packages/MySQLdb/connections.py in query, line 280
Python Executable: /opt/project-venv/bin/python
Python Version: 3.4.3
Python Path:
['/opt/project/project',
'/opt/project-venv/lib64/python34.zip',
'/opt/project-venv/lib64/python3.4',
'/opt/project-venv/lib64/python3.4/plat-linux',
'/opt/project-venv/lib64/python3.4/lib-dynload',
'/usr/lib64/python3.4',
'/usr/lib/python3.4',
'/opt/project-venv/lib/python3.4/site-packages']
Server time: Tue, 28 Mar 2017 22:50:16 +0000
I'm using Django 1.95 and I tried the following from the linked answer (https://stackoverflow.com/a/36565161/2516846):
Delete app migrations folder
Drop all app tables, e.g. DROP TABLE search_usersearchform
Delete all migrations from db: DELETE FROM django_migrations WHERE app = 'search'.
python manage.py makemigrations search
python manage.py migrate
But when I run migrate, it gives error:
django.db.utils.ProgrammingError: relation "search_usersearchform" already exists
Summary: Cannot create model again as relation already exists, yet cannot access model in my app as it says table doesn't exist
Is there a reference to this table/model stored else where which I need to remove? I don't know how the relation can already exist if I dropped the table, deleted migrations folder and removed migrations from db
EDIT
Okay finally got this sorted.
My project had two databases, the 'default' db, using postgres, and the 'secondary' db, using mysql.
When I created a new model in my app, and ran the migration, the table was added to the default db.
This allowed me to create an instance of the new model.
However when I went to access a previously saved instance, I got the error saying the table does not exist.
Turns out it was caused by my apps router.py, which redirected any queries to the 'secondary' db, which of course did not have the table.
To fix this, I added conditionals to the db_for_write and db_for_read methods in router.py, to route those models to the 'default' db.
Try deleting or changing migration files that have that model in them, care with the dependencies. Then run again python manage.py makemigrations and python manage.py migrate it should create the model again. (We are talking about your test DB right?)
make a back up of the models.py, delete the model code from the original models.py, then run:
python manage.py makemigrations
python manage.py migrate
Then simply restore the model code in models.py and run the above commands again.
Following these steps should fix it:
Remove the database.
Create an empty one with the same name.
Optionally, you may need to create a superuser for the new database.
Remove the content of package migrations (not the entire package), except file init.py.
Run command python manage.py makemigrations
Run command python manage.py migrate

Extending the existing User model in Django 1.7

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!

Categories