Django ORM filter on bool field not permitted - python-3.x

i have my django models:
class p_linea(models.Model):
l_name = models.CharField(max_length=100, verbose_name="Linea")
l_pubblica = models.BooleanField(default=False, verbose_name="Pubblica")
l_note = models.TextField(null=True, blank=True, verbose_name="Note interne")
class Meta:
verbose_name = "Linea"
verbose_name_plural = "Linee"
def __str__(self):
return '%s' % (
str(self.l_name))
class p_catlinea(models.Model):
p_lid = models.ForeignKey(p_linea, on_delete=models.CASCADE, verbose_name="Linea")
p_cid = models.ForeignKey(p_catl, on_delete=models.CASCADE, verbose_name="Categoria")
l_note = models.TextField(null=True, blank=True, verbose_name="Note interne")
dt = models.DateTimeField(auto_now=True, verbose_name="Upload")
class Meta:
indexes = [
models.Index(fields=['p_cid','p_lid']),
]
verbose_name = "Linea/Categoria"
verbose_name_plural = "Linea/Categoria"
def __str__(self):
return '%s' % (
str(self.p_cid))
now in my views.py i try to filter p_catliea baset on the fact that p_linea.l_pubblica is True, i try:
...
p_cl = p_catlinea.objects.all().select_related()
for x in p_cl:
if x.p_lid.l_pubblica:
try:
l_lincat[str(x.p_lid)]['cat'] = get_cat(x.p_lid_id)
except KeyError:
l_lincat[str(x.p_lid)] = {'cat': get_cat(x.p_lid_id),}
but i got error:
'bool' object is not callable
even if i di x.p_lid.l_pubblica == True i got the same error.
How can i filter my data based on True or Fale of related table field?
this is the full error:
TypeError at /prodotti/
'bool' object is not callable
Request Method: GET
Request URL: http://127.0.0.1:8000/prodotti/
Django Version: 3.0.5
Exception Type: TypeError
Exception Value:
'bool' object is not callable
Exception Location: /home/kngmalza/BIGDATA/Project/tebiskin/tebiskin/prodotti/views.py in f_prodotti, line 24
Python Executable: /usr/bin/python3
Python Version: 3.8.2
Python Path:
['/home/kngmalza/BIGDATA/Project/tebiskin/tebiskin',
'/usr/lib/python38.zip',
'/usr/lib/python3.8',
'/usr/lib/python3.8/lib-dynload',
'/home/kngmalza/.local/lib/python3.8/site-packages',
'/usr/local/lib/python3.8/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Tue, 23 Jun 2020 06:50:35 +0000
So many thanks in advance

Related

Migrations Error in Django: AttributeError: 'str' object has no attribute '_meta'

I know this has been asked before. But, I tried the available solutions. Those don't seem to work in my case unless I missed something unintentionally.
I dropped all the tables/relations from the connected database and deleted all the previous migration files except the init.py. And then ran the makemigrations command which worked fine. But got this error after running migrate.
Here is the error:
Applying book.0001_initial... OK
Applying reader.0001_initial...Traceback (most recent call last):
File "/home/brainiac77/github/bookworms_backend/backend/manage.py", line 22, in <module>
main()
File "/home/brainiac77/github/bookworms_backend/backend/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute
output = self.handle(*args, **options)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped
res = handle_func(*args, **kwargs)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 290, in handle
post_migrate_state = executor.migrate(
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 131, in migrate
state = self._migrate_all_forwards(
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 163, in _migrate_all_forwards
state = self.apply_migration(
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 248, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/migration.py", line 131, in apply
operation.database_forwards(
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/operations/models.py", line 93, in database_forwards
schema_editor.create_model(model)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 440, in create_model
if field.remote_field.through._meta.auto_created:
AttributeError: 'str' object has no attribute '_meta'
reader.0001_initial.py
# Generated by Django 4.0.6 on 2022-08-01 07:57
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('book', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Reader',
fields=[
('rid', models.AutoField(primary_key=True, serialize=False)),
('photo_url', models.CharField(blank=True, max_length=200, null=True)),
('bio', models.CharField(blank=True, max_length=200, null=True)),
('read_books', models.ManyToManyField(through='reads.Reads', to='book.book')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'reader',
},
),
]
Reader model
from django.db import models
from django.contrib.auth.models import User
class Reader(models.Model):
rid = models.AutoField(primary_key=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
photo_url = models.CharField(max_length=200, blank=True, null=True)
bio = models.CharField(max_length=200, blank=True, null=True)
read_books = models.ManyToManyField('book.Book', through='reads.Reads');
class Meta:
db_table = 'reader'
def __str__(self):
return {
'username': self.user.username,
'first_name': self.user.first_name,
'last_name': self.user.last_name,
'email': self.user.email,
'photo_url': self.photo_url,
'bio': self.bio,
}
Book Model
from django.db import models
from genre.models import Genre
from reader.models import Reader
class Book(models.Model):
isbn = models.CharField(max_length=13,primary_key=True)
title = models.CharField(max_length=255)
description = models.TextField()
photo_url = models.CharField(max_length=255)
page_count = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
genres = models.ManyToManyField(Genre)
authors = models.ManyToManyField(Reader, related_name='authored_books')
class Meta:
db_table = 'book'
def __str__(self):
return {
'isbn': self.isbn,
'title': self.title,
'description': self.description,
'photo_url': self.photo_url,
'page_count': self.page_count,
'created_at': self.created_at,
'updated_at': self.updated_at,
'genres': self.genres.all(),
'authors': self.authors.all(),
}
Reads Model:
from django.db import models
from reader.models import Reader
from book.models import Book
class Reads(models.Model):
status_choices = (
('w', 'Want to Read'),
('r', 'Reading'),
('c', 'Completed'),
)
rsid = models.AutoField(primary_key=True)
reader = models.ForeignKey(Reader, on_delete=models.CASCADE)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices=status_choices)
class Meta:
db_table = 'reads'
def __str__(self):
return {
'reader': self.reader.user.username,
'book': self.book.title,
'created_at': self.created_at,
'updated_at': self.updated_at,
'status': self.status,
}
INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# local apps
'rest_framework',
'rest_framework.authtoken',
'reader',
'book',
'genre',
'reads',
'bookreview',
'library',
'librarystock',
'bookborrow',
'friend',
]
What am I missing?
I think the migration file (reader.0001_initial.py) is wrong. There the foreign key table is book.book, which should be book.Book.
So I think you need to clear all the migration files and rerun the makemigrations command.
You can remake the migration file for the reader app using the following command.
python manage.py reset_migrations reader

ValidationError at /opd/ ['“OPDCashSheet object (2)” value must be a decimal number.'] How can a model-object be a decimal number?

models.py:
class Opd(models.Model):
patient=models.ForeignKey(Patient, on_delete=CASCADE)
bill_number=models.IntegerField(default=None)
date=models.DateField(default=datetime.date.today)
service_name=models.ForeignKey(ServiceName, on_delete=SET_NULL, null=True)
mode=models.CharField(max_length=5, default=None)
amount=models.DecimalField(max_digits=7, decimal_places=2)
remarks=models.TextField(max_length=500, blank=True, default=None)
opd_date=models.DateTimeField(auto_now_add=True)
modified_on=models.DateTimeField(auto_now=True)
def __str__(self):
return self.patient.name
class OPDParticulars(models.Model):
opd_particulars=models.CharField(max_length=150)
def __str__(self):
return self.opd_particulars
class OPDCashSheet(models.Model):
date=models.DateField(default=datetime.date.today)
patient=models.ForeignKey(Patient, on_delete=SET_NULL, blank=True, null=True)
opd=models.ForeignKey(Opd, on_delete=SET_NULL, null=True, blank=True)
opd_particulars=models.ForeignKey(OPDParticulars, on_delete=SET_NULL, null=True, blank=True)
source=models.CharField(max_length=10, default='OPD', null=True, blank=True)
case_number=models.IntegerField(null=True, blank=True)
mode=models.CharField(max_length=5)
cash_in=models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
cash_out=models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
balance=models.DecimalField(max_digits=7, decimal_places=2, default=0)
bank_oopl=models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
remarks=models.TextField(max_length=500, blank=True, null=True, default=None)
created_on=models.DateTimeField(auto_now_add=True)
modified_on=models.DateTimeField(auto_now=True)
class BankDeposits(models.Model):
opdcashsheet=models.ForeignKey(OPDCashSheet, on_delete=SET_NULL, null=True, blank=True)
date=models.DateField(default=None)
amount=models.DecimalField(max_digits=7, decimal_places=2, default=None)
bank=models.CharField(max_length=70, default=None, null=True, blank=True)
mode=models.CharField(max_length=5, default=None)
bank_ac=models.CharField(max_length=25, default='ABC Pvt. 123456789')
branch=models.CharField(max_length=20, default='XYZ')
remarks=models.TextField(max_length=500, blank=True, null=True, default=None)
created_on=models.DateTimeField(auto_now_add=True)
modified_on=models.DateTimeField(auto_now=True)
forms.py:
class UpdateOPDCashSheetForm(ModelForm):
MODE_SELECT = (
('cash', 'Cash'),
('bank', 'Bank'),
)
mode=forms.CharField(widget=forms.RadioSelect(choices=MODE_SELECT, attrs={'class': 'form-check-inline'}))
class Meta:
model=OPDCashSheet
labels={
'cash_in':'Cash-in',
'cash_out':'Cash-Out',
'balance':'Cash Balance',
'bank_oopl':'To Bank',
'opd_particulars':'Description',
}
fields='__all__'
widgets={
'date': DateInput(attrs={'type': 'date'}),
}
class BankDepositsForm(ModelForm):
MODE_SELECT = (
('cash', 'Cash'),
('bank', 'Bank'),
)
mode=forms.CharField(widget=forms.RadioSelect(choices=MODE_SELECT, attrs={'class': 'form-check-inline'}))
class Meta:
model=BankDeposits
labels={
'bank_ac':'Bank A/c',
}
fields='__all__'
widgets={
'date': DateInput(attrs={'type': 'date'}),
}
class OpdForm(ModelForm):
MODE_SELECT = (
('cash', 'Cash'),
('bank', 'Bank'),
)
mode=forms.CharField(widget=forms.RadioSelect(choices=MODE_SELECT, attrs={'class': 'form-check-inline'}))
class Meta:
model=Opd
fields='__all__'
widgets={
'date': DateInput(attrs={'type': 'date'}),
}
views.py:
def opd_view(request):
if request.method=='POST':
fm_opd=OpdForm(request.POST)
if fm_opd.is_valid():
opd=fm_opd.save()
OpdReport.objects.create(patient=opd.patient, opd=opd)
if opd.mode=='cash':
OPDCashSheet.objects.create(date=opd.date, patient=opd.patient, opd=opd, case_number=opd.bill_number, mode=opd.mode, cash_in=opd.amount)
elif opd.mode=='bank':
opdcashsheet=OPDCashSheet.objects.create(date=opd.date, patient=opd.patient, opd=opd, case_number=opd.bill_number, mode=opd.mode, bank_oopl=opd.amount)
BankDeposits.objects.create(opdcashsheet=opdcashsheet.id, date=opd.date, amount=opd.amount, mode=opd.mode, remarks=opd.remarks)
fm_opd=OpdForm()
return render(request, 'account/opd.html', {'form1':fm_opd})
else:
fm_opd=OpdForm()
return render(request, 'account/opd.html', {'form1':fm_opd})
Coming to the view, it worked fine when the mode was cash and it created the object for OPDCashSheet but when the mode is bank, it can not create an object for the same model, stating a ValidationError - ['“OPDCashSheet object (2)” value must be a decimal number.']. Now if this object could be created, it would have been the OPDCashSheet object (3) as the second object is already saved in the database. So where am I going wrong here? How can a model object be a decimal field? Please help.
EDIT:
Error Traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/opd/
Django Version: 4.0
Python Version: 3.10.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'account',
'mathfilters',
'django_filters']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1551, in to_python
return decimal.Decimal(value)
During handling of the above exception (conversion from OPDCashSheet to Decimal is not supported), another exception occurred:
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "H:\Sonu\Projects\Practice\Project versions\Roughs\slr\2. wrkg\rough1\account\views.py", line 15422, in opd_view
opdcashsheet=OPDCashSheet.objects.create(date=opd.date, patient=opd.patient, opd=opd, case_number=opd.bill_number, mode=opd.mode, bank_oopl=opd.amount)
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 457, in create
obj.save(force_insert=True, using=self.db)
File "H:\Sonu\Projects\Practice\Project versions\Roughs\slr\2. wrkg\rough1\account\models.py", line 139, in save
super(OPDCashSheet, self).save(*args, **kwargs)
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 743, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 780, in save_base
updated = self._save_table(
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 885, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 923, in _do_insert
return manager._insert(
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1301, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1440, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1382, in as_sql
value_rows = [
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1383, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1383, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1324, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1560, in get_db_prep_save
return connection.ops.adapt_decimalfield_value(self.to_python(value), self.max_digits, self.decimal_places)
File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1553, in to_python
raise exceptions.ValidationError(
Exception Type: ValidationError at /opd/
Exception Value: ['“OPDCashSheet object (2)” value must be a decimal number.']

Python3: What's wrong with my Singleton class and why can't I instantiate it?

Trying to create a Singleton class to fetch and manage data like following but I keep getting RunTimeError, not sure if cls.stock_data is correct here either.
class StockData:
__instance = None
def __init__(self):
raise RuntimeError("Call instance()")
#classmethod
def instance(cls):
if cls.__instance is None:
cls.__instance = cls()
cls.__instance.__dict__ = {}
cls.stock_data = {}
return cls.__instance
def save_stock_data_from_yahoo(self, stock_symbol):
import urllib.request
import json
url = "http://finance.yahoo.com/d/quotes.csv?s=" + stock_symbol + "&f=sl1d1t1c1ohgv&e=.csv"
response = urllib.request.urlopen(url)
data = response.read().decode("utf-8")
data = data.split(',')
self.stock_data = {
"symbol": data[0],
"last_trade_price": data[1],
"date": data[2],
"time": data[3],
"change": data[4],
"change_in_percent": data[5],
"open": data[6],
"high": data[7],
"low": data[8],
"volume": data[9],
"average_daily_volume": data[10],
"previous_close": data[11],
"price_per_sales": data[12],
"price_per_book": data[13],
"pe_ratio": data[14],
"dividend_per_share": data[15],
"dividend_yield": data[16],
"earnings_per_share": data[17],
"ebitda": data[18],
"market_cap": data[19],
"one_year_target_price": data[20],
"price_earnings_ratio": data[21],
"price_earnings_growth_ratio": data[22],
"price_sales_ratio": data[23],
"price_book_ratio": data[24],
"short_ratio": data[25],
"day_range": data[26],
"day_range_realtime": data[27],
"year_range": data[28]
}
def get_stock_data(self):
print(self.stock_data)
return self.stock_data
StockData.instance()

django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases

I'm creating multiple types of users with different permissions and hierarchy by extending AbstractBaseUser in django 3.1. All users are Employee, and there is an exploitation administrator type who is a kind of superuser, a Supervisor who has multiple Drivers under his control and there is a controller who is a independent User. But I get an errors about the models that I used. this is my models definition in models.py:
from django.db import models
from django.contrib.gis.db import models
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.gis.db import models as gis_models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from .managers import EmployeeManager
class Employee(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(max_length=128, blank=False, null=False)
last_name = models.CharField(max_length=128, blank=False, null=False)
registration_number = models.PositiveSmallIntegerField(unique=True, blank=False, null=False)
email = models.EmailField()
cni = models.CharField(max_length=18, blank=True)
picture = models.ImageField(upload_to='DriversPictures/', max_length=100, blank=True)
matricule_cnss = models.PositiveIntegerField(blank=True)
driving_licence = models.PositiveIntegerField(blank=True)
recruitment_date = models.DateField(auto_now=False, auto_now_add=False, blank=True)
phone = PhoneNumberField(blank=True, help_text='numéro de telephone')
adress = models.CharField(max_length=128, blank=True)
city_id = models.ForeignKey('City', blank=True, null=True, on_delete=models.SET_NULL)
region_id = models.ForeignKey('Region', blank=True, null=True, on_delete=models.SET_NULL)
# user = models.OneToOneField(User, on_delete=models.CASCADE)
# roles = models.ManyToManyField('Role')
is_exploitation_admin = models.BooleanField(default=False)
is_supervisor = models.BooleanField(default=False)
is_controlor = models.BooleanField(default=False)
is_driver = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
vehicle_id = models.ForeignKey('Vehicle', blank=True, null=True, on_delete=models.SET_NULL)
USERNAME_FIELD = 'registration_number'
REQUIRED_FIELDS = ['first_name', 'last_name', 'email']
objects = EmployeeManager()
def __str__(self):
return (self.registration_number, self.first_name, self.last_name)
class Supervisor(Employee):
zone_name = models.CharField(max_length=128, blank=True)
class Driver(Employee):
supervisor_id = models.ForeignKey('Supervisor', on_delete=models.CASCADE)
projects = models.ManyToManyField('Client', through='ProjectFleet')
class Controlor(Employee):
supervisor_id = models.ForeignKey('Supervisor', blank=True, null=True, on_delete=models.SET_NULL)
gaz_station_id = models.ForeignKey('GazStation', blank=True, null=True, on_delete=models.SET_NULL)
The admin.py I want to have the registration_number to be the unique field for authentication:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import EmployeeCreationForm, EmployeeChangeForm
from .models import Employee
class EmployeeAdmin(UserAdmin):
add_form = EmployeeCreationForm
form = EmployeeChangeForm
model = Employee
list_display = ('email', 'is_active', 'is_exploitation_admin', 'is_supervisor', 'is_controlor', 'is_driver',)
list_filter = ('registration_number', 'email', 'is_active', 'is_exploitation_admin', 'is_supervisor', 'is_controlor', 'is_driver',)
fieldsets = (
(None, {'fields': ('registration_number', 'email', 'password')}),
('Permissions', {'fields': ('is_active', 'is_exploitation_admin', 'is_supervisor', 'is_controlor', 'is_driver')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('registration_number', 'email', 'password1', 'password2', 'is_active', 'is_exploitation_admin', 'is_supervisor', 'is_controlor', 'is_driver')}
),
)
search_fields = ('email','registration_number', 'first_name','last_name')
ordering = ('registration_number', 'last_name')
admin.site.register(Employee, EmployeeAdmin)
the managers.py is:
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
class EmployeeManager(BaseUserManager):
def create_user(self, first_name, last_name, password, **extra_fields):
if not last_name:
raise ValueError(_('Le nom est obligatoire'))
if not first_name:
raise ValueError(_('Le prenom est obligatoire'))
user = self.model(first_name=first_name, last_name=last_name **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, first_name, last_name, mail, password, **extra_fields):
extra_fields.setdefault('is_exploitation_admin', True)
extra_fields.setdefault('is_supervisor', True)
extra_fields.setdefault('is_controlor', True)
extra_fields.setdefault('is_driver', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff=True.'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must have is_superuser=True.'))
return self.create_user(first_name, last_name, email, password, **extra_fields)
The Error message is :
(myEnv) mohammed#Laptop:~/Projects/Transport_Project$ python3 manage.py migrate
Operations to perform:
Apply all migrations: Drivers_App_Management, admin, auth, contenttypes, sessions
Running migrations:
Applying Drivers_App_Management.0001_initial...Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped
res = handle_func(*args, **kwargs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 245, in handle
fake_initial=fake_initial,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/db/migrations/migration.py", line 114, in apply
operation.state_forwards(self.app_label, project_state)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/db/migrations/operations/models.py", line 86, in state_forwards
list(self.managers),
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/db/migrations/state.py", line 95, in add_model
self.reload_model(app_label, model_name)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/db/migrations/state.py", line 156, in reload_model
self._reload(related_models)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/db/migrations/state.py", line 189, in _reload
self.apps.render_multiple(states_to_be_rendered)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/db/migrations/state.py", line 314, in render_multiple
"for more" % (new_unrendered_models, get_docs_version())
django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'Drivers_App_Management.Driver'>]
This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth)
in an app with no migrations; see https://docs.djangoproject.com/en/3.1/topics/migrations/#dependencies for more
I solved the problem by changing the order of models creation in the migrations/001_initial.py, where I found that django tried to create the model Driver model before Employee model and that causes error because the Driver model inherit from Employee.

Display query-set results on a Django template without using a django model

AttributeError at /Blog/mycustomsql
module 'django.http.request' has no attribute 'META'
Request Method: GET
Request URL: http://127.0.0.1:8000/Blog/mycustomsql
Django Version: 2.1.5
Exception Type: AttributeError
Exception Value:
module 'django.http.request' has no attribute 'META'
Exception Location: C:\Users\c822208\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\context_processors.py in debug, line 40
Python Executable: C:\Users\c822208\AppData\Local\Programs\Python\Python37\python.exe
Python Version: 3.7.3
Python Path:
['C:\cygwin64\home\c822208\django\hr',
'C:\Users\c822208\AppData\Local\Programs\Python\Python37\python37.zip',
'C:\Users\c822208\AppData\Local\Programs\Python\Python37\DLLs',
'C:\Users\c822208\AppData\Local\Programs\Python\Python37\lib',
'C:\Users\c822208\AppData\Local\Programs\Python\Python37',
'C:\Users\c822208\AppData\Local\Programs\Python\Python37\lib\site-packages']
Server time: Wed, 9 Oct 2019 08:58:49 +0000
def mycustomsql(self):
import cx_Oracle
conn_string = cx_Oracle.connect('hr/passwd#127.0.0.1/xe')
cursor1=conn_string.cursor()
cursor2=conn_string.cursor()
cursor1.execute("SELECT p.name,p.value FROM v$parameter p ORDER BY p.name")
results1 = cursor1.fetchall()
cursor2.execute("SELECT p.name,p.value FROM v_param p ORDER BY p.name")
results2 = cursor2.fetchall()
for index in range(0,len(results1)):
if results2[index] == results1[index]:
# print ('Found')
continue
rs= (results1[index]," : ",results2[index])
# return HttpResponse(rs) -- this is giving me one row instead of 2
context = {
"object_list": rs
}
return render(request, "Blog/param.html", context)
python python_tut/query.py
localhost/xe - ('shared_pool_size', '0') : localhost/xe - ('shared_pool_size', '5')
localhost/xe - ('streams_pool_size', '0') : localhost/xe - ('streams_pool_size', '8')

Resources