Error at OneToOneField in models while creating new models class django - django

I am facing below error while creating a new model class.
the error pop up only at this line "user = models.OneToOneField(User)"
"E1120:No value for argument 'on_delete' in constructor call"
section/models.py
from django.db import models
from django.contrib.auth.models import User
class userProfile(models.Model):
user = models.OneToOneField(User)
admin.py
from django.contrib import admin
from section.models import userProfile
admin.site.register(userProfile)
If I add below entry with "on_delete=models.CASCADE"
user = models.OneToOneField(User,on_delete=models.CASCADE)
the error got subsided but the new class "userProfile" is not appearing in admin page, under Users tab.
Also run migrations:
C:\Users\srini\djangoProjects\college>python manage.py makemigrations
No changes detected
C:\Users\srini\djangoProjects\college>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
Could some one please guide me how to fix this ?

Include your app_name in INSTALLED_APPS list in settings.py.
Then try migrations. After that check Admin after running the server.

Related

When I click on a user in the custom user model in admin, an error occurs (django)

step1
settings.py
AUTH_USER_MODEL = 'accounts.User'
step2
accounts/models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
# website = models.CharField(unique=True, max_length=255)
email = models.EmailField(unique=False)
step3
1.delete db.sqlite3
2.migrations, migrate
(askcompany) C:\my_django\askcompany>python manage.py makemigrations
No changes detected
(askcompany) C:\my_django\askcompany>python manage.py migrate
Operations to perform:
Apply all migrations: accounts, admin, auth, blog1, contenttypes, instagram, sessions
Running migrations:
No migrations to apply.
step4
and When I click on a user in the custom user model in admin, an error occurs (django)
error message:
File "C:\Users\hyunsepk\AppData\Local\conda\conda\envs\askcompany\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: accounts_user_groups
[02/Aug/2020 15:41:10] "GET /admin/accounts/user/2/change/ HTTP/1.1" 500 217698
how to fix it?
thanks for let me know
look like you miss migrations
./manage.py makemigrations
./manage.py migrate
I think you havent migrated, and hence there is no such table in your database. So migrate it by python manage.py makemigrations and then python manage.py migrate. And then try it.

failed: django.db.utils.ProgrammingError: relation "users_userprofile" does not exist

Using django 10 and postgres 9.4.
After the website full setup I noticed that I cannot create new objects from my applications, default django apps like users are OK.
ran makemigrations and migrate afterwords, and when re trying it says nothing to migrate.
To make it simple:
When entering django shell and typing
from users.models import *
User.objects.all()
Out[3]: [<User: root>]
but :
UserProfile.objects.all()
Out[4]:
<repr(<django.db.models.query.QuerySet at 0x39b4610>) failed: django.db.utils.ProgrammingError: relation "users_userprofile" does not exist
LINE 1: ...."is_superuser", "users_userprofile"."wight" FROM "users_use...
^
UserProfile is my site users with onetoone to django.contrib.auth
class UserProfile(models.Model):
user = models.OneToOneField(User)
Thanks
you must import the django.setup before doing the operation:
import django
django.setup()

Django 1.9 - OperationalError: no such table: products_category_artists; due to ManyToManyField?

I tried Googling this problem, but I mostly saw answers that were from versions of Django where South was needed for migration and/or syncdb was still a thing. The ones that were relevant matched the symptom, but not the cause.
I started with the default project/app that Django creates when you do django-admin startproject project-name and django-admin startapp products.
models.py
from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
# Create your models here.
class Artist(models.Model):
user = models.OneToOneField(User, null=True, blank=True)
name = models.CharField(max_length=50)
def __str__(self): return "<Artist: %s>"%self.name
class Category(models.Model):
artists = models.ManyToManyField(Artist)
name = models.CharField(max_length=50)
desc = models.CharField(max_length=200)
My process:
python manage.py flush to clear the database
rm -rf products\migrations to delete prior migrations
python manage.py migrate
Output:
Operations to perform:
Apply all migrations: sessions, contenttypes, auth, admin
Running migrations:
No migrations to apply.
python manage.py makemigrations products
Output:
Migrations for 'products':
0001_initial.py:
- Create model Artist
- Create model Category
python manage.py migrate
Output:
Operations to perform:
Apply all migrations: contenttypes, admin, sessions, products, auth
Running migrations:
No migrations to apply.
At this point, I'm confused. Aren't there migrations to be applied, and yet there aren't any? I press on nonetheless.
python manage.py shell
In this shell, I enter these commands:
>>> from products.models import *
>>> artist = Artist(name="foo")
>>> artist.save()
>>> categ = Category(name="bar", desc="baz")
>>> categ.save()
>>> categ.artists.add(artist)
At this point, I get a huge error traceback. The problem seems to be this:
django.db.utils.OperationalError: no such table: products_category_artists
I see the same error if I try to use the built-in admin site.
My guess is that the problem is that migrations aren't actually being applied or that a particular table isn't being created, but I don't know how to fix either of these problems.
There is a table generated by django called django_migrations which keeps track of what migrations have been applied. If you delete your migrations, re-generate them and try to migrate without deleting the records from the table than django will think it already applied them. You should never delete your migrations, it will cause django to get confused.
If you are actively developing and want to skip the entire migrations system you can, but once you start using migrations, never delete them. Here is what I use while developing a new project:
dropdb mydb && createdb mydb && python manage.py migrate --run-syncdb && python manage.py loaddata initial
First, it drops the database and all data. Then it creates an empty one. The --run-syncdb generates the schema and the loaddata loads data from a fixtures file.
So, if you are still developing and can delete all your data and move what you care about to a fixtures file than you can delete all your migration folders and run the command above each time you change your model.

Django OperationalError: missing table; migration does not recognize missing table

I'm having trouble in Django 1.7, I am trying to save a user to a table, but I'm getting an error that the table does not exist.
Here is the code I'm executing:
from django.conf import settings
from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY, get_user_model
User = get_user_model()
from django.contrib.sessions.backends.db import SessionStore
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, email, *_, **__):
session_key = create_pre_authenticated_session(email)
self.stdout.write(session_key)
def create_pre_authenticated_session(email):
user = User.objects.create(email=email)
session = SessionStore()
session[SESSION_KEY] = user.pk
session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
session.save()
return session.session_key
However, at
user = User.objects.create(email=email)
I get an Error message :
django.db.utils.OperationalError: no such table: accounts_user
Here is the user model at accounts/models.py that I'm trying to use to build the table:
from django.db import models
from django.utils import timezone
class User(models.Model):
email = models.EmailField(primary_key=True)
last_login = models.DateTimeField(default=timezone.now)
REQUIRED_FIELDS = ()
USERNAME_FIELD = 'email'
def is_authenticated(self):
return True
I've run sqlmigrate against this migration with 'manage.py accounts 0001.initial' and I have gotten the correct create table SQL back, but running 'manage.py migrate' gives me the following :
Operations to perform:
Apply all migrations: sessions, admin, lists, contenttypes, accounts, auth
Running migrations:
No migrations to apply.
The migration is just the result of running 'makemigration' from the shell, no custom code. I do see accounts listed in the included applications, but the migration isn't being ran, so my site is in an odd spot where Django says the table is missing when I try to use it, but Django says it exists when I try to run the migration to create it. Why does Django erroneously think that the table already exists when I can look at the database and see that it doesn't?
#user856358 Your comment about the other sqlite file seems like the root cause. I encountered the same error, and it was resolved by removing that file and running another migration. In my case, the file was located as specified in settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, '../database/db.sqlite3'),
}
}
By removing the .sqlite3 file there, I was able to successfully run the migration and resolve the no-such-table error...
django.db.utils.OperationalError: no such table: accounts_user
$ rm ../database/db.sqlite3
$ python3 manage.py migrate

Add a field to Mezzanine blogpost

I am using Mezzanine for a project. I need to add a extra field to Mezzanine blogpost.
I notice using EXTRA_MODEL_FIELDS can do it, but it looks complex.
I also try copy the blog folder from the site-package to my project path, and then modify the models.py. but I doesn't work.
I am new to Django, can some one help?
Thanks
By do some research, now I got the answer:
1. copy the blog app from sites-package to my project
2. change my setting.py
INSTALLED_APPS = (
"blog", #it was "mezzanine.blog",
.....
3. modify the blog/models.py
add following line to class BlogPost
shop_url= models.CharField(max_length=250,null=True, blank=True)
4. migirate the table (installed South)
./manage.py schemamigration blog --auto
./manage.py migrate blog
You can create a django app (CustomBlog), add it to your installed apps
and remove or comment the Mezzanine blog:
INSTALLED_APPS = (
"CustomBlog", #it was "mezzanine.blog",
...
)
In the models.py and admin.py, of your CustomBlog, inherit from the class BlogPost of Mezzanine:
models.py
from django.db import models
from mezzanine.blog.models import BlogPost
from mezzanine.blog.models import BlogCategory
class CustomBlog(BlogPost):
# Add New Field
# example
new_field = models.CharField(max_length=255)
class CustomBlogCategory(BlogCategory):
pass
admin.py
from django.contrib import admin
from .models import CustomBlog,CustomBlogCategory
admin.site.register(CustomBlog)
admin.site.register(CustomBlogCategory)
Then in the terminal create and run migrations
python manage.py makemigrations
python manage.py migrate