How to solve "OperationalError: no such column" in Django? - python

I'm making a cart app for an e-commerce site to handle users sessions.
I'm getting this error in the admin page when clicking on the carts section:
OperationalError at /admin/carts/cart/ no such column: carts_cart.user_id
Request Method: GET
Request URL: 127.0.0.1:8000/admin/carts/cart
Here's the cart model:
from django.db import models
from django.conf import settings
from django.urls import reverse
from products.models import product
user=settings.AUTH_USER_MODEL
class cart(models.Model):
user = models.ForeignKey(user, null=True, blank=True)
products = models.ManyToManyField(product, blank=True)
total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.id)
def __unicode__(self):
return str(self.id)
views.py
from django.shortcuts import render
from .models import cart
def cart_home(request):
return render(request,"carts/home.html",{})
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#ourapps
'products',
'search',
'carts',
'tags',
]
products ,search ,tags works fine

I simply went to the directory of my project and manually deleted the dbsqlite file.
After, i rerun...
python manage.py makemigrations
python manage.py migrate
And everything worked well

Like #bharat bhushan I used
python3 manage.py migrate --fake 'app name' zero
python3 manage.py migrate 'app name'
BUT, first I had to manually open the sql browser and delete the tables for that app, as otherwise I would get a:
OperationalError: table "appname_classname" already exists
So, delete the tables manually and then use the two mentioned commands.

Just use
python3 manage.py migrate --fake 'app name' zero
python3 manage.py migrate 'app name'
to proper sync of migrations again

I realized that I encountered this error when I forgot to do the following steps when I made changes to my model (in the models.py)
python manage.py makemigrations
python manage.py migrate
I am using Django 2.2, and it worked without problems thereafter

Related

Migrations are not applying to specific model

The problem is whenever I try to migrate changes, migrations does'nt applying to this specific app which is named as Userinfo. The messege in my terminal is
Operations to perform:
Apply all migrations: admin, auth, books_details, contenttypes, sessions
Running migrations:
No migrations to apply.
And that app is not listed in my above list also i don't know what could be the reason
Models.py of that app
from django.db import models
import os
# from django.conf import settings
def upload_rename(instance,filename):
exe=filename.split('.')[-1]
filename=instance.user_name+'.'+exe
try:
os.remove(os.path.join('images','profile_image',instance.user_name,filename))
except:
pass
return os.path.join('profile_image',instance.user_name,filename)
class Userinfo(models.Model):
''' User info '''
user_name = models.CharField(max_length=30, unique=True, null=False,primary_key=True)
full_name = models.CharField(max_length=50, null=False)
user_email = models.EmailField(max_length=254)
college_name = models.CharField(max_length=50)
city = models.CharField(max_length=50)
country = models.CharField(max_length=50)
profile_img = models.ImageField(upload_to=upload_rename, blank=True)
''' The Change I added '''
varified_user =models.BooleanField(default=False)
Admin.py of that app
from django.contrib import admin
from .models import Userinfo
admin.site.register(Userinfo)
INSTALLED_APP in setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'userinfo',
'rest_framework',
'phonenumber_field',
'books_details',
]
Migrations
from django.db import migrations, models
import userinfo.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Userinfo',
fields=[
('user_name', models.CharField(max_length=30, primary_key=True, serialize=False, unique=True)),
('full_name', models.CharField(max_length=50)),
('user_email', models.EmailField(max_length=254)),
('college_name', models.CharField(max_length=50)),
('city', models.CharField(max_length=50)),
('country', models.CharField(max_length=50)),
('profile_img', models.ImageField(blank=True, upload_to=userinfo.models.upload_rename)),
('varified_user', models.BooleanField(default=False)),
],
),
]
Here are some images i think you should see
I don't know why it says create model userinfo as it was pre-existing
Database screenshot
please any can help with this???
i guess you need first to run makemigrations command:
python manage.py makemigrations userinfo
and then run migrate command:
python manage.py migrate
refer to this tuto from django docx :https://docs.djangoproject.com/en/3.1/intro/tutorial02/#activating-models for more explanations
By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.
Update
in some cases, it's better to restart the migration process from scratch just to unlock such situation
so, since you're in development mode i would suggest you deleting:
the database (or better make a backup)
migrations files under migrations folder for each app
and don't forget __pycache__ folders
and then rerun makemigrations and migrate commands respectively

The command migration did not execute

I have a challenge here. I am currently building an application,and I tried to add my app to the settings,in this way :
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
In the model,here is the code :
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
Initially I used this command in the terminal
cd myproject
manage.py migratrate
Here is the output: Apply all migrations: admin,auth,contenttypes,sessions
Running
migrations:No migrations to apply.
Having defined my database in the model,I used the following command.Please,how do I fix this?
Note that I am a beginner in Python and Django
Please check that the polls/migrations/__init__.py file and directory exists. If the polls app is registered correctly in INSTALLED_APPS and the model is registered correctly but the migration file is not created, the next thing to check is to check if the migration directory is normal. Django checks if the __init__.py file exists in the migrations folder, so if it doesn't exist, it won't generate a migration file.
the polls app without polls/migrations/__init__.py:
the polls app with polls/migrations/__init__.py:

Django 3 OperationalError: no such table 'web_user'

I want to have 2 types of users in my Django app, so I followed this tutorial and ran
python manage.py makemigrations web
python manage.py migrate
('web' is the name of my app)
Now I want to access the admin part of the site, automatically added by django at localhost:PORT/admin. When I try to access that page, this error shows:
django.db.utils.OperationalError: no such table: web_user
Here's my models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
from web import constants
class User(AbstractUser):
USER_TYPE_CHOICES = (
(constants.USER_TYPE_CLEANER, 'cleaner'),
(constants.USER_TYPE_CONTRACTOR, 'contractor'),
)
user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)
# extra fields
email = models.CharField(max_length=100)
phone_number = models.CharField(max_length=15)
date_of_birth = models.DateField('date_of_birth')
address = models.CharField(max_length=50)
city = models.CharField(max_length=25)
state = models.CharField(max_length=25)
and set this in settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'web.apps.WebConfig',
]
# Authentication
AUTH_USER_MODEL = 'web.User'
How can I enable django's admin site? It's very useful for creating demo data.
make sure that before running makemigrations and migrate, add your app name in INSTALLED_APPS in project settings
Thanks to #bmons , the answer was to delete database db.sqlite3, migration files, and create a new user. Note that the extra fields must be nullable, otherwise creating a superuser will fail.

Creating first Django project: admin webpage will not open

NOTE: THE SPECIFIC QUESTION IS AT THE END BELOW. FIRST I DESCRIBE ALL THE STEPS I WENT THROUGH :-) )
Im using Python 2.7 and Django 4.2.1
on Windows.
I am creating a project called "mysite" which is the project used at docs.djangoproject.com.
So far, I have done the following just like in the tutorial:
1)typed: django-admin.py startproject mysite
This created all the standard folders, which are:
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
2) typed: manage.py runserver
and when typing http://127.0.0.1:8000 in the address bar I got a congratulations message.
So far, so good..
3) Then I edited the settings.py file. First I edited the DATABASE ENGINE and typed the following:
'django.db.backends.sqlite3'
4) Still in settings.py, I indicated a DATABASE name so that it creates a database file. I called it:
'mysitedb'
5) Then I synced the database (to create the tables) by typing:
manage.py syncdb
6) Then the tutorial asks to create an app called polls. So I typed:
manage.py startapp polls
That created the following folder and files:
polls/
__init__.py
admin.py
models.py
tests.py
views.py
7) The tutorial then asks to edit the models.py by typing the following:
from django.db import models
import datetime
from django.utils import timezone
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
8) Moving along, I then I had to edit the INSTALLED_APPS section in the settings.py file by typing the following:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
9) Then I typed the following to create tables and their fields (I guess..):
manage.py sql polls
then the following printed out:
BEGIN;
CREATE TABLE "polls_poll" (
"id" integer NOT NULL PRIMARY KEY,
"question" varchar(200) NOT NULL,
"pub_date" datetime NOT NULL
);
CREATE TABLE "polls_choice" (
"id" integer NOT NULL PRIMARY KEY,
"poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
"choice_text" varchar(200) NOT NULL,
"votes" integer NOT NULL
);
COMMIT;
10) Then I had to type this to create the tables (sync):
manage.py syncdb
So far, still so good..
10) Then they suggest I run python shell in command and play with the database API. At that point everything was working fine. Could add data in the tables' fields, etc.
But here is where it doesn't work. From PART 2 of the tutorial. I have to runserver again (I did that: manage.py runserver, and it worked fine..).
I opened a browser webpage and typed http://127.0.0.1:8000/admin/ and I get the same "It worked! Congratulations on your first Django-powered page..."
No error message. So how do I get the admin page with user logins (username and password) to appear?
Any help will be appreciated.
Thanks!
Usually when the admin in Django isn't working the two main culprits are forgetting to add the following two lines to the urls.py file.
admin.autodiscover()
and
url(r'^admin/', include(admin.site.urls))
Now you can go ahead with the tutorial and when you register models in your admin.py, don't forget
admin.site.register(MyModelGoesHere, MyModelAdminNameGoesHere)
Good luck! :)

Fails to Implement orderedmodel

I'm trying to implement orderedmodel from here: https://github.com/kirelagin/django-orderedmodel
But it fail with DatabaseError Exception Value: no such column: qrgame_place.order
The documentation says nothing about that the model should contain the field order so I suppose the parent class is supposed to implement that field? [EDIT: Yeah, it is. Tried that...]
Here are some of the important snippets from the django files:
# models.py
import hashlib
import random
from django.db import models
from orderedmodel import OrderedModel
class Place(OrderedModel):
name = models.CharField(max_length=100)
clue = models.CharField(max_length=300)
code = models.CharField(max_length=7, editable=False)
def __unicode__(self):
return self.name
def save(self):
# Need a secret identifier for url. Using a hashed name (which
# is also secret until found. So no need to obscure more)
if not self.id:
hashsrc = self.name.encode('utf-8')
self.code = unicode(hashlib.sha1(hashsrc).hexdigest()[:7])
super(Place, self).save()
# admin.py
from django.contrib import admin
from qrgame.models import Place
from orderedmodel import OrderedModelAdmin
class PlaceAdmin(OrderedModelAdmin):
list_display = ['name', 'clue', 'reorder']
admin.site.register(Place, PlaceAdmin)
# settings.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'orderedmodel',
'qrgame',
)
I have ran python manage.py syncdb after implemented this.
Any idea what's wrong? (Django version is (1, 4, 1, 'final', 0))
syncdb can't alter existing tables at the moment. You can do the following:
drop table manually and than run syncdb
run manage.py reset qrgame but all data of the qrgame app will be lost
use any existing django db migration solutions, like South
manually add column to the table (hints: manage.py dbshell will give you db REPL. You can get column definition from manage.py sqlall qrgame
dumpdata and loaddata commands can be helpful for saving and restoring existing data between schema changes

Categories

Resources