Tag Archives: django

Causes and solutions of Django’s unique error reporting

 


1 RuntimeError at /login
2 You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8009/login/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.

Django was a vengeance alone.

:

: <

:

:

How to Solve Django xadmin installation Error [7 Types of Errors]

Error 1: ModuleNotFoundError: No module named ‘django.core.urlresolvers’

1 ModuleNotFoundError: No module named 'django.core.urlresolvers'

Solution: find the wrong file according to the prompt, and change all import django.core.urlresolvers to   import django.urls

import django.core.urlresolvers 

#change to
import django.urls

Error 2: TypeError: __init__() missing 1 required positional argument: ‘on_delete’

TypeError: __init__() missing 1 required positional argument: 'on_delete'

Solution: This is basically an error in models. Foreignkey() in the models file. Add on in parentheses according to the Django document_delete=models.CASCADE

Error 3: typeerror:__init__() takes 1 positional argument but 6 were given

TypeError: __init__() takes 1 positional argument but 6 were given

Solution: hint that the file xadmin\views\dashboard.py, find

 

forms.Field.__init__(self, required, widget, label, initial, help_text,  *args, **kwargs)

change to

forms.Field.__init__(self)

 forms.Field.__init__(self, required, widget, label, initial, help_text,  *args, **kwargs)

#change to
forms.Field.__init__(self)

Error 4: ImportError: cannot import name ‘login’ from ‘django.contrib.auth.views’

ImportError: cannot import name 'login' from 'django.contrib.auth.views'

Solution: The hint is in xadmin\views\website.py”, line 5, in <module>
from django.contrib.auth.views import login

find the location, and then change

from django.contrib.auth.views import login
from django.contrib.auth.views import logout

to

from django.contrib.auth import authenticate, login, logout

from django.contrib.auth.views import login
from django.contrib.auth.views import logout

#change to
from django.contrib.auth import authenticate, login, logout

 

Error 5: ImportError: cannot import name ‘QUERY_TERMS’ from ‘django.db.models.sql.query’

 ImportError: cannot import name 'QUERY_TERMS' from 'django.db.models.sql.query'

Solution: find the location in xadmin\plugins\filters.py”, line 10, in <module>

then change

from django.db.models.sql.query import LOOKUP_SEP, QUERY_TERMS

to

from django.db.models.sql.query import LOOKUP_SEP, Query

from django.db.models.sql.query import LOOKUP_SEP, QUERY_TERMS

#change to
from django.db.models.sql.query import LOOKUP_SEP, Query

Error 6: ImportError: cannot import name ‘password_reset_confirm’ from ‘django.contrib.auth.views’

ImportError: cannot import name 'password_reset_confirm' from 'django.contrib.auth.views'

Solution: in\xadmin\plugins\passwords.py”, line 4, in <module>
Find    from django.contrib.auth.views import password_reset_confirm

 

change to   from django.contrib.auth.views import PasswordResetConfirmView

in line 77, change   return password_reset_confirm

to   return PasswordResetConfirmView

from django.contrib.auth.views import password_reset_confirm
#change to  
from django.contrib.auth.views import PasswordResetConfirmView

#line 77 
return password_reset_confirm
#to  
return PasswordResetConfirmView

Error 7: AttributeError: ‘Settings’ object has no attribute ‘MIDDLEWARE_CLASSES’

AttributeError: 'Settings' object has no attribute 'MIDDLEWARE_CLASSES'

Solution:   in xadmin\plugins\language.py”, line 24, in <module>
if settings.LANGUAGES and ‘django.middleware.locale.LocaleMiddleware’ in settings.MIDDLEWARE_CLASSES:

change to if settings.LANGUAGES and ‘django.middleware.locale.LocaleMiddleware’ in settings.MIDDLEWARE:

 

if settings.LANGUAGES and 'django.middleware.locale.LocaleMiddleware' in settings.MIDDLEWARE_CLASSES:
#change to
if settings.LANGUAGES and 'django.middleware.locale.LocaleMiddleware' in settings.MIDDLEWARE:

Other errors are modulenotfounderror: no module named, just install the corresponding module according to the prompt. If it is not installed, it may be that the module name is written incorrectly

Django startup error: generator expression must be parentized

Return to Django directory

Startup error: syntax error: generator expression must be parented . Sometimes, when using the command Python manager.py runserver , the startup fails first. The error log is as follows:

[[email protected] es_demo]# python37 manage.py runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f220f0edae8>
Traceback (most recent call last):
  File "/usr/local/python/python37/lib/python3.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/python/python37/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    autoreload.raise_last_exception()
  File "/usr/local/python/python37/lib/python3.7/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception
    six.reraise(*_exception)
  File "/usr/local/python/python37/lib/python3.7/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/usr/local/python/python37/lib/python3.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/python/python37/lib/python3.7/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/local/python/python37/lib/python3.7/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/usr/local/python/python37/lib/python3.7/site-packages/django/apps/config.py", line 94, in create
    module = import_module(entry)
  File "/usr/local/python/python37/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/usr/local/python/python37/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 4, in <module>
    from django.contrib.admin.filters import (
  File "/usr/local/python/python37/lib/python3.7/site-packages/django/contrib/admin/filters.py", line 10, in <module>
    from django.contrib.admin.options import IncorrectLookupParameters
  File "/usr/local/python/python37/lib/python3.7/site-packages/django/contrib/admin/options.py", line 12, in <module>
    from django.contrib.admin import helpers, widgets
  File "/usr/local/python/python37/lib/python3.7/site-packages/django/contrib/admin/widgets.py", line 151
    '%s=%s' % (k, v) for k, v in params.items(),
    ^
SyntaxError: Generator expression must be parenthesized

It can be found that the last line indicates that there is a syntax error and that there is a problem with the generator expression. The specific error line content is '% s =% s'% (k, V) for K, V in params. Items(), . You can see that the last punctuation is very interesting. We can find the line corresponding to the source file and remove this punctuation

PS: if it is modified in pycharm, since this file is the source code, you should also select I want to edit this file anyway in the prompt box


welcome to Fuzheng, that’s all see also: [django1.11 startup error: generator expression must be parentized]( https://www.cnblogs.com/yanlin-10/p/9714793.html )

[Solved] Django use search_fields error (in get_lookup_constraint)

django use search_fields error (in get_lookup_constraint)

FieldError at /api/workorder/order/

Related Field got invalid lookup: icontains
Request Method: GET
Request URL: http://127.0.0.1:8000/api/workorder/order/?search=1
Django Version: 2.0
Exception Type: FieldError
Exception Value: Related Field got invalid lookup: icontains
Exception Location: C:\Users\WM\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\query.py in build_lookup, line 1075
Python Executable: C:\Users\WM\AppData\Local\Programs\Python\Python36\python.exe
Python Version: 3.6.5
Python Path: [‘F:\git_code\emergency_itil\EmergencyResponse’, ‘F:\git_code\emergency_itil\EmergencyResponse’, ‘E:\PyCharm 2019.1.1\helpers\pycharm_display’, ‘C:\Users\WM\AppData\Local\Programs\Python\Python36\python36.zip’, ‘C:\Users\WM\AppData\Local\Programs\Python\Python36\DLLs’, ‘C:\Users\WM\AppData\Local\Programs\Python\Python36\lib’, ‘C:\Users\WM\AppData\Local\Programs\Python\Python36’, ‘C:\Users\WM\AppData\Roaming\Python\Python36\site-packages’, ‘C:\Users\WM\AppData\Local\Programs\Python\Python36\lib\site-packages’, ‘E:\PyCharm 2019.1.1\helpers\pycharm_matplotlib_backend’]
Server time: Monday, 22 July 2019 21:07:21 +0800

 

Reason:

search_fields = ('content', 'detail','submitter')

This is a fuzzy query field in the view. The submitter field is a foreign key ForeignKey field. As a foreign key, it corresponds not to a specific field, but to a class

Therefore, we should map it to a specific field associated with a foreign key, such as submitter__username

search_fields = ('content', 'detail','submitter__username')

Error modulenotfounderror when starting Django: no module named ‘pytz’

It was a bad start. I made a mistake when I first learned Django. No module named ‘pytz’ is reported when running the manage.py file through the PY – 3 manage.py runserver 127.0.0.1:8000 command

Solution: install pytz module: PIP3 install pytz

After successful installation, enter py – 3 manage.py runserver 127.0.0.1:8000 to run successfully:

  If you want to directly run the manage.py file in pycharm, you need to add parameters

First open the edit configuration, as shown in the figure:

Add parameters as shown in the figure:

[Solved] Error when connecting to MySQL when creating Django project

After changing the data configuration in the setting file of the project:

DATABASES = {

    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'cesi_DB',    #Your database name
        'USER': 'sheng', # your database username
        'PASSWORD': 'xxoo', # your database password
        'HOST': '10.0.0.11', # your database host, leave blank to default to localhost
        'PORT': '3306', # your database port
    }
}

Error Message:

    'Did you install mysqlclient or MySQL-python?' % e
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?

  Solution:

The engine that needs to change the database:

MYsqlDB ==》pymysql

In application (app01)__init__Add to the document:

import pymysql

pymysql.install_as_MySQLdb()

 

Django logs detailed error reporting information

When the server 500 makes an error, the ordinary log will only record the request information of 500 in one line, and will not record the detailed error location

[ERROR] 2019-06-12 15:07:03,597 "GET /api/v1/test/ HTTP/1.1" 500 74196

You need to add a middleware that records detailed error information in the log

# -*- coding: UTF-8 -*-
import logging

logger = logging.getLogger('default')


class ExceptionLoggingMiddleware(object):
    def process_exception(self, request, exception):
        import traceback
        logger.error(traceback.format_exc())

Add this middleware to the midview of settings_In classes

MIDDLEWARE_CLASSES = (
'utils.my_middleware.ExceptionLoggingMiddleware',
)

Use Django logger

    'loggers': {
        'django': {
            'handlers': ['file', 'console'],
            'level': 'INFO'
        },

Effect

[ERROR] 2019-06-12 15:07:02,265 Internal Server Error: /api/v1/test/
Traceback (most recent call last):
  File "E:\tcp_check\venv\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
  File "E:\tcp_check\venv\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "E:\tcp_check\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\tcp_check\tcp_test_app\views.py", line 23, in test
    a=1/0
ZeroDivisionError: division by zero
[ERROR] 2019-06-12 15:07:03,597 "GET /api/v1/test/ HTTP/1.1" 500 74196

 

Django: How to Solve Using Pymysql Error

Environment:
Ubuntu18.04
mysql:8.0
python: 3.6.8
django: 2.2.6
pymysql: 0.9.3

Install pymysql

pip install pymysql

introduce pymysql into Django

under the package with the same name as the project directory__init__. Write the following code to the PY file:

import pymysql

pymysql.install_as_MySQLdb()

configure MySQL in Django, and then start Django service. The errors are as follows:

File "/home/www/.local/share/virtualenvs/EduScore-UXZMOCwv/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 36, in <module>
    raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

Solution:
Use vim to open /home/www/.local/share/virtualenvs/EduScore-UXZMOCwv/lib/python3.6/site-packages/django/db/backends/mysql/base.py file, and Comment out the following code

#if version < (1, 3, 13):
#    raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)

start Django server and find or report an error. The error information is:

AttributeError: 'str' object has no attribute 'decode'

Solution:

find the corresponding file and change the decode of the error line to encode

 

[Solved] Windows Django Error: A server error occurred. Please contact the administrator.

This is because the get function is used in the view function to get data that does not exist
For example, there is no data in the database with the name hello1, use the following statement to access
message = Message.objects.get(name='hello1')

will report an error message = Message.objects.get(name='boddy1')

Solution.
 See the following figure:

Click the link in the box above to automatically enter line 323 of the debug.py file, and modify line 321 as shown in the figure below:

Run again:

In this case, the error message is normal, the query data does not exist

This problem does not exist in MAC and Linux, where the encoding has been set to utf8 by default.