Tag Archives: Python programming

[Solved] AttributeError: ‘Manager‘ object has no attribute ‘get_by_natural_key‘

Problem description


E:\SweetYaya\MyProj03>python manage.py createsuperuser
Identifier: 12
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 "D:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\Program Files\Python36\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
    return super().execute(*args, **options)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "D:\Program Files\Python36\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 113, in handle
    error_msg = self._validate_username(username, verbose_field_name, database)
  File "D:\Program Files\Python36\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 234, in _validate_username
    self.UserModel._default_manager.db_manager(database).get_by_natural_key(username)
AttributeError: 'Manager' object has no attribute 'get_by_natural_key'

terms of settlement


Add to the defined model

class SysUsers(models.Model):
    
	...
	# add
    objects = UserManager()
	
	...

django.db.utils.OperationalError: no such table: django_admin_log

Problem orientation


Using Python shell to delete custom user table data

from MyApp import models
dU = models.SysUsers.objects.all()
dU.delete()

The error is as follows

django.db.utils.OperationalError: no such table: django_admin_log

terms of settlement


Direct migrate may not work. Parameters should be added as follows

python manage.py makemigrations
python manage.py migrate --run-syncdb

ValueError: The field admin.LogEntry.user was declared with a lazy reference to ‘MyApp.sysusers‘

Problem description


E:\SweetYaya\MyProj03>python manage.py migrate
Operations to perform:
  Apply all migrations: MyApp, admin, auth, contenttypes, sessions
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 "D:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 202, in handle
    pre_migrate_apps = pre_migrate_state.apps
  File "D:\Program Files\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\Program Files\Python36\lib\site-packages\django\db\migrations\state.py", line 208, in apps
    return StateApps(self.real_apps, self.models)
  File "D:\Program Files\Python36\lib\site-packages\django\db\migrations\state.py", line 277, in __init__
    raise ValueError("\n".join(error.msg for error in errors))
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'MyApp.sysuser', but app 'MyApp' doesn't provide model 'sysuser'.

Find your own python3. X and enter the site packages/Django/contrib/admin/migrations file directory__ init__. Py file, delete all others( Be careful not to__ init__. If you delete the PY file, don’t delete the migrations in the folder contrib/contenttypes. Otherwise, the function of migrate will be invalid and Django can only be removed.

Djangorestframework-simplejwt: ‘str‘ object has no attribute ‘decode‘ [Solved]

Problem description

Python v3.6.6Django v3.2.4djangorestframework v3.12.4djangorestframework-simplejwt v4.4.0

When testing the interface after running runserver command, the error of background printing is as follows

Traceback (most recent call last):
  File "D:\Program Files\Python36\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Program Files\Python36\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "D:\Program Files\Python36\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework_simplejwt\views.py", line 27, in post
    serializer.is_valid(raise_exception=True)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\serializers.py", line 220, in is_valid
    self._validated_data = self.run_validation(self.initial_data)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\serializers.py", line 422, in run_validation
    value = self.validate(value)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework_simplejwt\serializers.py", line 75, in validate
    data['refresh'] = str(refresh)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework_simplejwt\tokens.py", line 82, in __str__
    return token_backend.encode(self.payload)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework_simplejwt\backends.py", line 43, in encode
    return token.decode('utf-8')
AttributeError: 'str' object has no attribute 'decode'

terms of settlement

Method 1

Upgrade the djangorestframework simplejwt version to 4.6.0 +

Method 2

Open
D:// program files/Python 36/lib/site packages/rest_ framework_ simplejwt\backends.py

File, edit line 43. take

return token.decode('utf-8')

It can be amended as follows

return token

explain

Migration admin.0001_initial is applied before its dependency xxx.0001_initial on database ‘default‘

Problem orientation

Developed in Django framework, a user table is defined to replace the user table automatically generated by the framework, which appears when the migrate command is executed to synchronize the database. Details of the error are as follows

E:\SweetYaya\MyProj01> python manage.py migrate
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 "D:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 95, in handle
    executor.loader.check_consistent_history(connection)
  File "D:\Program Files\Python36\lib\site-packages\django\db\migrations\loader.py", line 310, in check_consistent_history
    connection.alias,
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency MyApp.0001_initial on database 'default'.

terms of settlement

Method 1

delete database , delete all Auth in the database_ and Django_ and re execute it. It's rough. It's not good.

Method 2

First makemigrations Open settings. Py and comment out install_ In apps,
'django. Contrib. Admin ', Open URLs. Py , comment out the admin in urlpatterns, and then migrate will not report an error. Finally, pay attention to recover the comment content

Python modifies word document content and inserts pictures

The following code

#!/usr/bin/python
# coding:utf-8
import docx
def main():
    filepath = 'test.docx'
    filepath1 = 'wtest.docx'
    newdocx = docx.Document(filepath)
    table = newdocx.tables
    for oTable in table:
        rows_num = len(oTable.rows)
        columns_num = len(oTable.columns)
        cell = oTable.cell(3, 0)
        # cell.add_paragraph("a")
        cell.text = ""
        cell.paragraphs[-1].runs[0].add_picture('t1.jpg')
        print(rows_num)
        print(columns_num)
        newdocx.save(filepath1)
if __name__ == '__main__':
    main()

Python error: ‘int’ object is not callable

TypeError: ‘int’ object is not callable ‘; ‘int’ object cannot be called .

I just want to use the sum of the 1-100, and () function, but an error, because I’m using ipython, I at first thought it was the cause of the ipython, then I will bring in python interactive tool test, found that there is no problem, can be normal use, the following figure:

I then looked at me in ipython before operation, before the “sum” this keyword is defined as a variable name, then I tried to put their own custom variables to deleted, please try again after deleting, found, it was the sum () function is when the cause of the variable name before, It’s attempt to:
lookup is defined before the variable name

by reset delete custom variable

try again, can be normal use

this is my problem and the solution, the hope can help you!
hint: python variable names and method names should not be the same