How to drop a table (sqlite3) in Django==2.1? - django

I created the following models in my app events :
from django.db import models
from django.utils import timezone
from django.urls import reverse
class EventType(models.Model):
type_of_event = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.type_of_event
class Event(models.Model):
type_of_event = models.ForeignKey(EventType, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
description = models.TextField()
event_date = models.DateTimeField(default=timezone.now())
venue = models.CharField(max_length=200)
entry_fee = models.FloatField()
def __str__(self):
return self.name
Due to some errors and changes, I created and deleted the migration file many times. Now, the makemigrations command works but when I try to migrate the models using : python manage.py migrate , it shows the following error:
File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 294, in execute
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: table "events_event" already exists
I am using django version 2.1 along with sqlite3.
Most questions similar to this were too old and incompatible to the version I am using now.

First of all, make a backup of the file db.sqlite3
You could use dbshell, which runs the command-line client for the database engine
https://docs.djangoproject.com/en/dev/ref/django-admin/#django-admin-dbshell
python manage.py dbshell
list all tables
sqlite> .table
delete table
sqlite> DROP TABLE <table>;

Related

Making use of the users table, causing an error

In Django (2.x) I have an entry form, the model is here:
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
class Sample(models.Model):
sample_id = models.AutoField(primary_key=True)
area_easting = models.IntegerField()
area_northing = models.IntegerField()
context_number = models.IntegerField()
sample_number = models.IntegerField()
# taken_by = models.IntegerField()
taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.PROTECT)
def __str__(self):
return str(self.sample_id)
class Meta:
db_table = 'samples\".\"sample'
#ordering = ["sample_id"]
managed = False
#verbose_name_plural = "samples"
This works as expected, a list of usernames drops down (while I would like to format - firstname lastname). However, when I return to the main viewing page I see an error.
django.db.utils.ProgrammingError: column sample.taken_by_id does not exist
LINE 1: ...text_number", "samples"."sample"."sample_number", "samples"....
^
HINT: Perhaps you meant to reference the column "sample.taken_by".
Clearly Django is adding the _id to the table name causing the error, I expect because it is a foreign key.
Any ideas how to remedy this behaviour?
You can explicitly set the underlying db column via the db_column attribute:
taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='taken_by', on_delete=models.PROTECT)
https://docs.djangoproject.com/en/2.1/ref/models/fields/#database-representation
^ link to the docs where it specifies that it creates a _id field.
based from the error message you have posted. It seems that your database schema is not updated.
you might need to do manage makemigrations and migrate to apply your model changes to your db schema
e.g
$ python manage.py makemigrations
# to apply the new migrations file
$ python manage.py migrate

Django error: multiple default values for specified column "id"

I'm working with a project with docker-compose, where I have a postgre container.
When I run:
docker-compose -f dev.yml run django python manage.py migrate
I get the error:
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "scrapy_scrapy"
That is happening before I made some changes to my models.py file. But now the file is correct and should be working. This is the content of the models.py file:
from django.db import models
import django
# Create your models here.
class Scrapy(models.Model):
user = models.CharField(max_length=50,blank=True)
password = models.CharField(max_length=50,blank=True)
projecte = models.CharField(max_length=100)
estat_last_check = models.CharField(max_length=700, default="", blank=True)
date = models.DateTimeField(default=django.utils.timezone.now, blank=True)
app_label = ''
def __str__(self): # __unicode__ on Python 2
return self.projecte + " - " + self.user
class Meta:
app_label = 'scrapy'
As you can see, no id filed is defined anymore, so, why is complaining about that field?
I've done my research and tried some possible solutions, but no luck. I've already tried deleting the full Docker container and creating it again, or trying to delete the database.
Any ideas?

unique_together does not work in Django shell

I have below model:
class Property(models.Model):
job = models.ForeignKey(Job, on_delete=models.CASCADE)
app = models.ForeignKey(App, on_delete=models.CASCADE)
name = models.CharField(max_length=120)
value = models.CharField(max_length=350, blank=True)
description = models.TextField(blank=True)
pub_date = models.DateTimeField('date_published', default=timezone.now)
class Meta:
verbose_name_plural = "properties"
unique_together = (('value', 'name'),)
def __str__(self):
return self.name
When I try to create a Property object in admin page (I'm using Django Suit) with name/value which are already exist I get the exception: "Property with this Value and Name already exists." So it works perfect.
But in manage.py shell:
>>>from myapp.models import App, Property, Job
>>>from django.shortcuts import get_object_or_404
>>>app = get_object_or_404(App, app_name='BLABLA')
>>>job = get_object_or_404(Job, job_name='BLABLA2')
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>
In this case I do not get any exceptions and objects are added in database.
I tried makemigrations, migrate and migrate --run-syncdb.
Django 1.9.12, sqlite3
The unique constraints are enforced at database level. You're not getting any error probably because SQLite doesn't support this type of constraint. You cannot add constraint to existing table in SQLite. If you're in early development stage, drop the table and recreate it with updated constraints. Then it should work fine in shell.
Check SQLite alter table docs for allowed updates on an existing table.
The admin form throws error because it checks uniqueness by itself without relying on database constraints.

Django South DatabaseError: App inside app - Table doesn't exist

After being inspired by django-oscar, I tried to put a cmsplugin inside its main app. However, after doing a schemamigration --initial I can't use the plugin in Django CMS.
DatabaseError: (1146, "Table 'devel_test.cmsplugin_galleries_gallerycontainer_galleries' doesn't exist")
App Tree
gallery
apps
cmsplugin_galleries
migrations
cms_plugins.py
init.py
models.py
init.py
migrations
static
templates
admin.py
init.py
models.py
views.py
Gallery models
class Gallery(models.Model):
title = models.CharField(_(u'title'), max_length=200)
description = models.TextField(_(u'description'), blank=True)
image_folder = FilerFolderField(verbose_name=_(u'image folder'))
is_video = models.BooleanField(_(u'is video content'), default=False)
snippet = models.TextField(_(u'video snippet'))
class Meta:
verbose_name = _(u'Gallery')
verbose_name_plural = _(u'Galleries')
class GalleryImage(models.Model):
gallery = models.ForeignKey(Gallery, verbose_name=_(u'gallery'))
title = models.CharField(_(u'title'), max_length=200, blank=True)
src = FilerImageField(verbose_name=_(u'image'))
Cmsplugin_galleries models
class GalleryContainer(CMSPlugin):
title = models.CharField(_(u'title'), max_length=200)
galleries = models.ManyToManyField(Gallery, verbose_name=_(u'galleries'))
def __unicode__(self):
return u'%s' % self.title
Since I can properly run it using syncdb --all, what did I do wrong?
Notes:
Using syncdb creates a table with the name cmsplugin_galleries_gallerycontainer_galleries but using south, the table name is cmsplugin_gallerycontainer_galleries
Thanks
Since there was no other alternative I followed #daigorocub tip and replaced all the shorten_name instances of cmsplugin_gallerycontainer_galleries inside the migration file
m2m_table_name = db.shorten_name(u'cmsplugin_gallerycontainer_galleries')
to
m2m_table_name = db.shorten_name(u'cmsplugin_galleries_gallerycontainer_galleries')
This issue was fixed in the development branch of django cms 3.0 (https://github.com/divio/django-cms/issues/2291#ref-pullrequest-26529456) but since my version is older I couldn't update to the latest branch
Thank you guys for your help!

.py file is not compiled on django

I'm using django 1.6.1. I got one file name "payment.py" on models folder and it's not compiled to .pyc file. Even if I changed the file name to "payment_room.py", it still won't be compiled
The other model files have been compiled already and worked pretty well.
Because of that, django won't create the table on my database if I run syncdb command. I run validate command using manage.py, but it didn't return any error.
N.B.
It's still on debug & development mode. The web hasn't been deployed to apache server yet.
from django.db import models
from ghb_manager.models.reservation import Reservation
class Payment (models.Model):
class Meta:
app_label = 'ghb_manager'
PAYMENT_METHOD_CHOICES = (
('CA', 'Cash'),
('CR', 'Credit'),
('TR', 'Transfer')
)
payment_id = models.CharField(max_length=14, primary_key=True)
reservation_id = models.ForeignKey(Reservation)
ammount_tendered = models.DecimalField(max_digits=19, decimal_places=2)
payment_method = models.CharField(max_length=20, choices=PAYMENT_METHOD_CHOICES)
payment_date = models.DateField()
def __unicode__(self):
return self.payment_id
Please check your init.py in your models directory. You have to import all the models you create in models directory, like:
# __init__.py
from payment import Payment
Django looks into app.models for app's models.