I'm still learning to use Django and I have an issue while trying to create a model.
Here's my models.py
class Identifiants(models.Model):
id = models.AutoField(primary_key=True)
taxon = models.IntegerField(unique=True)
noms = models.TextField(blank=True, null=True)
fiche = models.IntegerField(blank=True, null=True)
comestible = models.TextField(blank=True, null=True)
sms = models.NullBooleanField()
a_imprimer = models.NullBooleanField()
lieu = models.TextField(blank=True, null=True)
apparition = models.TextField()
class Meta:
managed = True
db_table = 'identifiants'
The makemigrations command works with no issues but the migrate one is where I have problems
Running migrations:
Applying app.0001_initial...Traceback (most recent call last):
File "/usr/lib/python3.5/site-packages/django/db/backends/utils.py", line 83,
in _execute
return self.cursor.execute(sql)
psycopg2.DataError: NUMERIC precision 65535 must be between 1 and 1000
LINE 1: ...iants" ("id" serial NOT NULL PRIMARY KEY, "taxon" numeric(65...
I'm using IntegerField method so I can't see why there is an issue ...
Can anyone help me ?
Thanks
Remove id = models.AutoField(primary_key=True) id is automatically created by django.
check it here, its similar to your question.
Related
I'm working on creating a filter in django where the options displayed are coming from a new column in the database. It turns out that this column was created directly in the database and so that it could be displayed in my template, I need to capture this field in the models.
After some research, I found in django's own documentation a function called "inspectdb" that is called by manage.py. So far so good, after executing the function, the database fields are added to my project so that they can be directed to their corresponding app.models.
The documentation indicates that I must perform a python manage.py migrate for the sync to complete, this snippet of code is where the problem happens. When performing the migrate, I get the following error: "django.db.utils.ProgrammingError: relation "crontabmanager" already exists"
The "crontabmanager" table actually exists in my database, but it is not changing at this time.
Some actions were taken to try to get around this problem, for example:
I tried to ignore the migration and use the new field directly in the system, but it returns stating that the new column does not exist
Delete the migration file and create a new "makemigration"
Delete the "crontabmanager" table from the database for django to recreate through the ORM
Changing models.py properties to ignore changes made
Below is the snippet of my current models.py code:
from django.db import models
class Crontab(models.Model):
client = models.TextField('Cliente', blank=True, null=True)
script = models.TextField('Nome do script', primary_key=True)
schedule_code = models.TextField('Codigo Crontab', blank=True, null=True)
crontab_command = models.TextField("Comando", blank=True, null=True)
log = models.TextField("Log", blank=True, null=True)
class Meta:
verbose_name = 'Crontab'
verbose_name_plural = 'Crontab'
db_table = "crontabmanager"
class Trello(models.Model):
id_card = models.TextField('ID do Card', primary_key=True)
card_name = models.TextField('Nome do Card', blank=True, null=True)
due_date = models.TextField('Data de conclusão', blank=True, null=True)
list_name = models.TextField('Nome da lista', blank=True, null=True)
tipo_corte = models.TextField('Tipo do corte', blank=True, null=True)
cortes = models.TextField('Numero de cortes', blank=True, null=True)
unidade = models.CharField(max_length=200, blank=True, null=True) #new field added
class Meta:
db_table = "trello_pta"
error when running python manage.py migrate
$ python3 manage.py migrate
Operations to perform:
Apply all migrations: accounts, admin, auth, contenttypes, core, sessions, users
Running migrations:
Applying core.0002_initial...Traceback (most recent call last):
File "/home/file_names/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 87, in _execute
return self.cursor.execute(sql)
psycopg2.errors.DuplicateTable: relation "crontabmanager" already exists
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
...
return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "crontabmanager" already exists
I have just switched to PostegreSQL. Now whenever I add the following code to my Custom User Model, the database is broken, no new values are added to the database, for example during registration
from django.contrib.postgres.fields import ArrayField
class NewUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('Email'), unique=True)
username = models.CharField(max_length=150, unique=True)
start_date = models.DateTimeField(default=timezone.now)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(default=timezone.now)
code = models.ImageField(blank=True, upload_to='code',)
#part that breaks the databse:
ip_addresses = ArrayField(
models.CharField(blank=True), default=list)
From the moment also no more migrations are recognized.
Or I get something like this
django.db.utils.ProgrammingError: column "ip_addresses" does not exist
LINE 1: ...ER COLUMN "ip_addresses" TYPE varchar(15)[] USING "ip_addres...
What error I get is 50 50 chance but atleast the first error is always here.
I also tried this which did not work either
ip_addresses = ArrayField(
models.CharField(max_length=15), default=list)
I'm upgrading a project from Django 1.8 to Django 2.1.3 (yes, I know I should update more, but that's the client requirement at this point).
The exact same models.py file and exact same Django ORM query in the views.py file are in both (Python3 updates notwithstanding), the Django 1.8 version works fine but with Django 2.1.3, this filter (which worked perfectly fine with Django 1.8):
kwargs['car__carcategory__category__category_id'] = categoryId
is now producing the following error with Django 2.1.3:
raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0]))
django.core.exceptions.FieldError: Related Field got invalid lookup: carcategory
Here is the query:
cars = CarModel.objects.only(
'car__car_id',
'car__cardate',
'car__title',
'car__location',
'car__quote',
'car__key',
'car__cartype_id',
'maker__lastname',
'maker__firstname',
'maker__middlename',
'maker__nickname',
).select_related(
'car',
'maker',
).extra(
select={
'is_position_paper': 'cartype_id = 7',
'is_null_date': 'cardate IS NULL',
'shorttitle': extra,
},
).filter(**kwargs).distinct(sort_order_for_distinct, 'car__car_id').order_by(sort_order, 'car__car_id')
Here are the relevant models:
class CarModel(models.Model):
car_candidate_id = models.IntegerField(primary_key=True)
car = models.ForeignKey(Car, on_delete=models.PROTECT)
partsmanufacturer = models.ForeignKey(Manufacturer, on_delete=models.PROTECT)
created = models.DateTimeField(blank=True, null=True)
modified = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'car_model'
class Car(models.Model):
car_id = models.IntegerField(primary_key=True)
cartype = models.ForeignKey(Cartype, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
cardate = models.DateField(null=True)
db_table = u'car'
class Carcategory(models.Model):
car_category_id = models.IntegerField(primary_key=True)
car = models.ForeignKey(Car, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
class Meta:
db_table = u'car_category'
Anybody know what gives here? What was changed or deprecated in terms of being to do this Django 1.8 but now no longer in a slightly new Django version?
The DB is the same, nothing's been changed there, and like I said, the models.py file is exactly the same (aside from updating some ForeignKey fields with on_delete=models.CASCADE for the Django 2.1.3 version)
I am making a Q&A site like stackoverflow. But Django model field clashes.
I am using Django2.1.5
I tried to add related_name = 'answers_case' but nothing changed.
Here is my models:
class Post(models.Model):
user = models.ForeignKey(MyUser, on_delete=models.CASCADE)
post_date = models.DateTimeField(auto_now_add=True)
score = models.IntegerField(default=0)
body = models.TextField()
last_edit_date = models.DateTimeField(null=True, blank=True)
is_active = models.BooleanField(default=False)
class Case(Post):
title = models.CharField(max_length=150)
slug = models.SlugField(unique=True, max_length=150)
view_count = models.IntegerField(default=0)
keyword = models.ManyToManyField(Keyword)
class Answer(Post):
case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name='answers_case')
is_accepted = models.BooleanField(default=False)
And the error is:
Unhandled exception in thread started by .wrapper at 0x7fa57c42c7b8>
Traceback (most recent call last):
File "/home/emre/anaconda3/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/home/emre/anaconda3/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/home/emre/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 425, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
medicus_website.Answer.case: (models.E006) The field 'case' clashes with the field 'case' from model 'medicus_website.post'.
System check identified 1 issue (0 silenced).
You fell into a trap of models inheritance in django. You are applying the Multi-table inheritance, while I assume you are expecting the Abstract inheritance.
In other words, your Post already has a case field - since you have multi-table inheritance from Case to Post, each Post might have corresponding Case, and that's why you have the name clash. If you want to maintain current behaviour (in terms of db structure and relations construction) you will have to rename either Case model or case field in answer. On the other hand, if you'd like to switch to abstract inheritance, with each table self-conatined, you could do this like this:
class AbstractPost(models.Model):
user = models.ForeignKey(MyUser, on_delete=models.CASCADE)
post_date = models.DateTimeField(auto_now_add=True)
score = models.IntegerField(default=0)
body = models.TextField()
last_edit_date = models.DateTimeField(null=True, blank=True)
is_active = models.BooleanField(default=False)
class Meta:
abstract = True
class Post(AbstractPost):
# if you need standalone posts
pass
class Case(AbstractPost):
title = models.CharField(max_length=150)
slug = models.SlugField(unique=True, max_length=150)
view_count = models.IntegerField(default=0)
keyword = models.ManyToManyField(Keyword)
class Answer(Post):
case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name='answers_case')
is_accepted = models.BooleanField(default=False)
I'm trying to create a unique constraint on my TranslationRequest model listed below. TranslationRequest has a foreign key relationship with a MachineTranslator model, which exists in another Django application. When I try to run syncdb, I get the error: Error: One or more models did not validate:
wt_articles.translationrequest: "unique_together" refers to translator, a field that doesn't exist. Check your syntax.
When I remove translator from the unique_constraint specification, syncdb runs correctly. Note: I'm using Sqlite3 as my back-end database.
Here are the definitions of TranslationRequest and SourceArticle.
from wt_translation.models import MachineTranslator
class TranslationRequest(models.Model):
article = models.ForeignKey(SourceArticle)
target_language = models.ForeignKey(Language, db_index=True)
date = models.DateTimeField(_('Request Date'))
translator = models.ForeignKey(MachineTranslator),
status = models.CharField(_('Request Status'),
max_length=32,
choices=TRANSLATION_STATUSES)
class Meta:
unique_together = ("article", "target_language", "translator")
class SourceArticle(models.Model):
title = models.CharField(_('Title'), max_length=255)
language = models.ForeignKey(Language, db_index=True)
timestamp = models.DateTimeField(_('Import Date'), default=datetime.now())
doc_id = models.CharField(_('Document ID'), max_length=512)
source_text = models.TextField(_('Source Text'))
sentences_processed = models.BooleanField(_('Sentences Processed'))
Here is the definition of MachineTranslator, in a different (but referenced Django application).
class MachineTranslator(models.Model):
shortname = models.CharField(_('Name'), max_length=50)
supported_languages = models.ManyToManyField(LanguagePair)
description = models.TextField(_('Description'))
type = models.CharField(_('Type'), max_length=32, choices=TRANSLATOR_TYPES, default='Serverland'),
timestamp = models.DateTimeField(_('Refresh Date'), default=datetime.now())
is_alive = models.BooleanField()
Not all of the dependencies have been included in this code sample. Thanks for your help!
i dont' know if it is a typo but i see s "," comma at the end of the line where you declare your translator = models.ForeignKey(MachineTranslator)
This is why maybe the attribute is ot seens