Migrations Error in Django: AttributeError: 'str' object has no attribute '_meta' - python-3.x

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

Related

MongoDB with Django: TypeError: Model instances without primary key value are unhashable

I'm trying to connect MongoDB with Django.
settings.py
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': '<name>',
'ENFORCE_SCHEMA': False,
'CLIENT': {
'host': f'mongodb+srv://{mongodb_username}:{mongodb_password}#{mongodb_cluster}/?retryWrites=true',
'uuidRepresentation': 'standard',
'waitQueueTimeoutMS': 30000
}
}
}
models.py
import uuid
from django.db import models
# Create your models here.
class ModernConnectUsers(models.Model):
user_id = models.UUIDField(primary_key=True, default=uuid.uuid4())
user_name = models.CharField(max_length=30, null=False)
The model has not been used anywhere for now.
python manage.py makemigrations && python manage.py migrate
outputs:
Migrations for 'modern_connect':
modern_connect/migrations/0003_alter_modernconnectusers_user_id.py
- Alter field user_id on modernconnectusers
Operations to perform:
Apply all migrations: admin, auth, contenttypes, modern_connect, sessions
Running migrations:
No migrations to apply.
Your models in app(s): 'modern_connect' have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
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/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute
output = self.handle(*args, **options)
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 98, in wrapped
res = handle_func(*args, **kwargs)
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 317, in handle
emit_post_migrate_signal(
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/sql.py", line 52, in emit_post_migrate_signal
models.signals.post_migrate.send(
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 176, in send
return [
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 177, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/contrib/auth/management/__init__.py", line 83, in create_permissions
ctypes.add(ctype)
File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/db/models/base.py", line 597, in __hash__
raise TypeError("Model instances without primary key value are unhashable")
TypeError: Model instances without primary key value are unhashable
The only collection I'm currently using has a Primary Key, but for some reason - The program is falling for self.pk == None in Base.py which is raising this error. Solutions under other questions didn't help, so starting another question.
In your models.py, try importing the models from djongo.
from djongo import models
And for primary key I use
class User(models.Model):
_id = models.ObjectIdField()
But you can play around with uuid() and see if it works or not.

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.']

How to filter Serializers in DjangoRestFramework based on user id?

I'm new to django,
I can't seem to find how to return an api based on the user who requested it and created the Transaction object, can you please guide me through? I have read this, but I can't find a clear guide in the docs to update the Serializer straightaway.
In laravel, I can do:
Transaction::where('user_id', Auth::user()->id)->get();
This is my serializer:
class TransactionSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer(read_only=True)
tags = TagShortSerializer(read_only=True, many=True)
def get_fields(self, *args, **kwargs):
# Override this method so that the list of DatabaseUsers presented in the browseable API
# is restricted to the DatabaseUsers owned by the current user.
fields = super(TransactionSerializer, self).get_fields(*args, **kwargs)
view = self.context["view"]
user = view.request.user
return Transaction.objects.filter(user=user)
class Meta:
model = Transaction
fields = ["user", "title", "amount", "category", "tags"]
My viewset:
class TransactionViewSet(viewsets.ModelViewSet):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
permission_classes = [permissions.IsAuthenticated, IsOwner]
Currently it returns:
Complete traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/transactions/
Django Version: 3.2.5
Python Version: 3.9.5
Installed Applications:
['djmoney',
'rest_framework',
'finance.apps.FinanceConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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 "E:\Development\Python\sharkware-api\.venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\mixins.py", line 43, in list
return self.get_paginated_response(serializer.data)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 745, in data
ret = super().data
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 246, in data
self._data = self.to_representation(self.instance)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 663, in to_representation
return [
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 664, in <listcomp>
self.child.to_representation(item) for item in iterable
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 500, in to_representation
for field in fields:
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 361, in _readable_fields
for field in self.fields.values():
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "E:\Development\Python\sharkware-api\.venv\lib\site-packages\rest_framework\serializers.py", line 349, in fields
for key, value in self.get_fields().items():
Exception Type: AttributeError at /transactions/
Exception Value: 'QuerySet' object has no attribute 'items'
That is not the correct usage for get_fields. That method returns the list of fields to be used when instantiating the serializer.
What you want is to override get_queryset on your viewset:
class TransactionViewSet(viewsets.ModelViewSet):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
permission_classes = [permissions.IsAuthenticated, IsOwner]
def get_queryset(self):
if self.request.user.is_authenticated:
return self.queryset.filter(user=self.request.user)
return Transaction.objects.none()

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.

Django-rest-framework: Authentication/permissions error: TypeError: 'str' object is not callable

I am trying to learn about django-rest-framework and I am stuck in the authentication/permissions processes. I hope someone could help me. Below is my code:
settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'drones.custompagination.LimitOffsetPaginationWithUpperBound',
'PAGE_SIZE': 4,
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.OrderingFilter',
'rest_framework.filters.SearchFilter',
),
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
models.py
class Drone(models.Model):
name = models.CharField(max_length=250,
unique=True)
drone_category = models.ForeignKey(DroneCategory,
related_name='drones',
on_delete=models.CASCADE)
manufacturing_date = models.DateTimeField()
has_it_competed = models.BooleanField(default=False)
inserted_timestamp = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(
'auth.User',
related_name='drones',
on_delete=models.CASCADE)
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
views.py
class DroneList(generics.ListCreateAPIView):
queryset = Drone.objects.all()
serializer_class = DroneSerializer
name = 'drone-list'
permission_classes = (
'permissions.IsAuthenticatedOrReadOnly',
'custompermission.IsCurrentUserOwnerOrReadOnly',
)
filterset_fields = (
'name',
'drone_category',
'manufacturing_date',
'has_it_competed',
)
search_fileds = (
'name',
)
ordering_fields = (
'name',
'manufacturing_date',
)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class DroneDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Drone.objects.all()
serializer_class = DroneSerializer
name = 'drone-detail'
permission_classes = (
'permissions.IsAuthenticatedOrReadOnly',
'custompermission.IsCurrentUserOwnerOrReadOnly',
)
custompermission.py
from rest_framework import permissions
class IsCurrentUserOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
# The method is a safe method
return True
else:
# The method is not a safe method
# Only owners are granted permissions
return obj.owner == request.user
And and below is the error that django is throwing:
[03/Nov/2019 18:01:42] "GET / HTTP/1.1" 200 10070
Internal Server Error: /drones/
Traceback (most recent call last):
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/rest_framework/views.py", line 493, in dispatch
self.initial(request, *args, **kwargs)
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/rest_framework/views.py", line 411, in initial
self.check_permissions(request)
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/rest_framework/views.py", line 331, in check_permissions
for permission in self.get_permissions():
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/rest_framework/views.py", line 278, in get_permissions
return [permission() for permission in self.permission_classes]
File "/home/martin/python/learn_rest/lib/python3.5/site-packages/rest_framework/views.py", line 278, in <listcomp>
return [permission() for permission in self.permission_classes]
TypeError: 'str' object is not callable
[03/Nov/2019 18:01:45] "GET /drones/ HTTP/1.1" 500 107476
Python version: 3.5.3
Django version: 2.2.6
Django Rest Framework version: 3.10.3
I have been searching here for other people having the same problem, but none of the solutions provided seem to work for this particular case
Thank you so much in advance for your help
Try to set the value of permission_classes to the permission classes directly, something like:
from rest_framework import permissions
#import your custome permission module
class DroneDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Drone.objects.all()
serializer_class = DroneSerializer
name = 'drone-detail'
permission_classes = (
permissions.IsAuthenticatedOrReadOnly,
custompermission.IsCurrentUserOwnerOrReadOnly,
)

Resources