Tag Archives: django

[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.

How to Solve Django Error: No module named ‘MySQLdb’

Since many related dependent packages were unloaded when MySQL was unloaded, the following error occurred when Django was started after reloading MySQL:

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

Due to the development of Python version 3.6.4, mysql-python does not support python3, after a lot of trouble to install mysqlclient

The following is my process to solve the problem, I am lazy, I will show you in the form of pictures

First of all, I tried to install MySQL python, but there was an error. The following is the solution for online search:

Here’s how I found the solution and installed mysqlclient:

The following is the code to install mysqlclient and its dependent environment:

pip install mysqlclient
sudo apt-get install python3-dev libmysqlclient-dev

Conclusion:

When there is a problem with no module named ‘MySQL db’. It is recommended to install mysqlclient. MySQL Python does not support python3

[Solved] Django cannot create an app after creating a project

F:\index>python manage.py startapp news
Traceback (most recent call last):
File “manage.py”, line 8, in <module>
from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named ‘django’

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File “manage.py”, line 14, in <module>
) from exc
ImportError: Couldn’t import Django. Are you sure it’s installed and available on your PYTHONPATH environment variable?Did you forget to activate a virtual environment?
After creating a django project, adding python manage.py startapp news gives the following error
Uninstall django and install it again, can’t fix it
python -m pip install django problem solved
F:\index>python -m pip install django
Collecting django
Using cached https://files.pythonhosted.org/packages/ab/15/cfde97943f0db45e4f999c60b696fbb4df59e82bbccc686770f4e44c9094/Django-2.0.7-py3-none-any.whl
Requirement already satisfied: pytz in c:\programdata\anaconda3\lib\site-packages (from django)
Installing collected packages: django
Successfully installed django-2.0.7
You are using pip version 9.0.1, however version 10.0.1 is available.
You should consider upgrading via the ‘python -m pip install –upgrade pip’ command.

Error encountered in Django: forbidden CSRF cookie not set

How is 618 sales champion made?Uncover the secret of e-commerce’s “invigorating” hundreds of millions of sales data>>>

CSRF cookie not set	

The hint is that

CSRF cookie not set

What is CSRF

Indicates that string validation is required for Django to send post requests globally

function: function to prevent cross site request forgery

working principle : when the client accesses the server, when the server normally returns data to the client, it returns a string to the client. When the client visits the server next time, the server will look up the previously returned string from the client. If it is found, it will continue. If it is not found, it will refuse

access process : client – URL routing system – CSRF – view function

What I want to write here is an API interface for internal use, and Cross Site Request Forgery is unlikely

So here are two not very recommended, but very simple ways to solve this problem

Since CSRF is not needed, we can turn off CSRF detection

Solution 1:

In the project you created, find the settings. Py file

Find the midview parameter in the file settings.py

Comment out 'django. Middleware. CSRF. Csrfviewmiddleware ',

Like this,

Solution 2:

The second method is similar to the first

Above is the comment of Django. Middleware. CSRF. Csrfviewmiddleware , which is a global setting

In fact, we can also make special settings for a single API

Here we use @ CSRF_ Exempt

@csrf_ Exempt is used to cancel the anti Cross Site Request Forgery function of the current function

Find the views. Py file, which is where we deal with API rules

Import from django.views.decorators.csrf import CSRF_ exempt

We add @ CSRF to the corresponding function_ exempt

Like this, isn’t it very simple

Note: please indicate the source of the reprint, thank you^_^

When deploying Django project on centos7, there will be an error of importerror: cannot import name middlewaremin

Deployment on embedded devices has been fine, but this problem occurs on Linux Centos7, usually due to versioning issues.
Solution Install pip3 install Django==1.11.1
However, the following ImportError: cannot import name patterns
vim touch/extra_apps/DjangoUeditor/urls.py

# coding:utf-8
from django import VERSION

if VERSION[0:2] > (1, 3):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url

from .views import get_ueditor_controller

urlpatterns = [
url(r’^controller/$’, get_ueditor_controller)
]

to:

# coding:utf-8
from django import VERSION

if VERSION[0:2] > (1, 3):
from django.conf.urls import url
else:
from django.conf.urls.defaults import url

from .views import get_ueditor_controller

urlpatterns = [
url(r’^controller/$’, get_ueditor_controller)
]

Due to version issues, this may cause the following problems

render_to_string() got an unexpected keyword argument ‘context_instance’

Solution:

context must be a dict rather than RequestContext.

is when the context becomes
{
“context”:context
}

Due to the version upgrade, the previous code

return render_to_response(‘info_count.html’, {}, context_instance=RequestContext(request))

should be rewritten to something like this.

from django.shortcuts import render

return render(request, “info_main.html”, {‘time_refresh’: time_refresh,
‘time_refresh_long’: time_refresh_long,
‘time_refresh_net’: time_refresh_net,
‘version’: version})

Django’36935;’21040;Invalid HTTP’u HOST header

Why can’t you stop buying 618?From the technical dimension to explore>>>

When deploying Django, use

python manage.py runserver 0.0.0.0:8080

0.0.0 website

To

invalid http host header:’192.168.2.157:8080’。 You may need to add ‘192.168.2.157’ to allow ‘192.168.2.157:8080’ to be used as a ‘get/blog http:// 1.1’ 400 58424 ‘
invalid http:// host header:’ 192.168.2.157:8080 ‘. You may need to add ‘192.168.2.157’ to allowed hosts.
bad request:// favicon. ICO
[31/DEC/2019 08:49:31] “get/favicon. ICO http:// 1.1” 400 58433

Legal information:

settings.py

ALLOWED_HOSTS = ['192.168.2.157','127.0.0.1']

The value of “*” enables all web addresses to access the Django project. It loses the function of protection and can be used for testing

ALLOWED_HOSTS = ['*']

Django exception-ImportError: No module named django.core.management

Django error-ImportError: No module named django.core.managementProblem
description:
Enter manage.py runserver on the command line, it prompts that the django.core.management module cannot be found.

Problem analysis:
1. Make sure that Django has been installed, and check the Django installation directory. django.core.management does exist
. 2. There are two versions of Python on the computer. Check that the Python version set by the environment variable has Django installed
. 3. Followed by Command line input:
python
import django
django.VERSION
prints out Django version V1.3.1

4. Continue to point 3, type in the command line:
from django.core.management import execute_manager
command input is normal! ! ! This is weird. .

5. You can determine the function of normal Django, Python If you have heard that there may be multiple versions installed version compatibility issues, try to manually specify the version of Python to run Django project, at the command line:
Python25 manage.py the runserver
problem is solved

Solution :
specified before the command manage.py runserver to use Python version, at the command line:
Python25 manage.py runserver

Summary:
When there are multiple versions of Python installed on the computer, sometimes even if the version to be run is correctly set in the environment variable, there may still be errors. At this time, you can try to specify the Python to be used on the command line, such as python25 manage.py runserver