Tag Archives: django

DRF uses paging function Error: unorderedobjectlistwarning

UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class ‘myapp.models.Power’> QuerySet.
paginator = self.django_paginator_class(queryset, page_size)

The reason is that you are not sorting.

Solution.
(a) add ordering to the design of the model

class test(models.Model):
    ...

    class Meta:
        ...
        ordering=["xx"]

(b) Add order_by to the query set for sorting

Solve the problem of error loading MySQL DB module. Encountered during Django project

Solve the problem of error loading MySQL DB module encountered during Django project

Python version 3.9 was used when creating the Django project. The MySQL database was successfully introduced in the process of doing the project, but later the python version was reduced to 3.7, so this error was reported when re running the system

Problem causes and solutions:
the package used by Django to connect to MySQL in Python 3 is pymysql, so the first step is to install pymysql:

pip install pymysql

Installation does not mean that it is OK. It also needs to be installed in the project__ init__. Add the following code to the. Py file:

import pymysql
pymysql.install_as_MySQLdb()


[Solved] Simple jwt Error: AttributeError: type object ‘BlacklistedToken‘ has no attribute ‘objects

Solution: add in Django setting

'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,

For example:

SIMPLE_JWT = {

     'ACCESS_TOKEN_LIFETIME': datetime.timedelta(days=7),
    'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,

}

Jsondecodeerror error: json.decoder.JSONDecodeError: Expecting value: line 1 column 26 (char 25)

json.decoder.JSONDecodeError: Expecting value: line 1 column 26 (char 25)

Cause: JSON format conversion error, not standard JSON format


Note:
(1) the parentheses indicate the object. The object must be composed of attributes, which are composed of key value pairs

(2) Use double quotation marks for attribute values in JSON

(3) If the attribute value in JSON is a logical value or null value, it must be lowercase, false, true and null
① true in JSON, true in Python
② false in JSON, false in Python
③ null in JSON and none in Python

(4) Conversion between JSON data type and Dictionary (pre operation pilot library → import JSON):
① convert JSON to dictionary → JSON. Loads()
② convert dictionary to JSON → JSON. Dumps()

Using postman Test Django Interface error: RuntimeError:You called this URL via POST,but the URL doesn‘t end in a slash

1. Access interface

Using the postman provider

2. Error reporting:

RuntimeError: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.

3. Solution:

In fact, two methods have been suggested in the error report

Method 1: add a at the end of the URL/

http:10.192.171.128:8000/ops/rbac/group/distribute

Method 2: set append in settings_ SLASH=False

Django project running service reported an error NameError: name ‘OS’ is not defined

Existing problems:
after Django creates a new project, when running the service command “Python manage. Py runserver”, an error is reported: NameError: name ‘OS’ is not defined


Solution:
find the setting.py file in the new project path and add “import OS” to it

Note: the method to judge whether the project is successfully created is if something similar to“ http://127.0.0.1:8000/ ”The project address, and “the install worked successfully! Integrations!” is displayed in the browser.

[Solved] Django Models Error: Manager isn‘t accessible via UserInfo instances

Error content: manager isn’t accessible via userinfo instances

Error reason: it is because the variable name is used instead of the object name (model class) when calling the model object, for example:

user = UserInfo()
user_Li = User. Objects. Filter (uname = username), this error will be reported in this call

Solution: call the objects method with the object name

user = UserInfo()
user_li = UserInfo.objects.filter(uname=username)

raise RuntimeError(RuntimeError: ‘cryptography‘ package is required for sha256_password or caching

The Django project in normal operation was written before. After a period of time, when the project is run again, an error occurs when Python manage.py runserver is started:

Reason: when connecting to the database, cryptography   The package is required.

Solution: PIP install   cryptography。

Run again to successfully resolve:

 

 

 

Django framework uses error reporting exception type: templatedoesnotexist

1、 Error: templatedoesnotexist

Exception Type: TemplateDoesNotExist

 

2、 Problem analysis and solution

Problem analysis: the accessed HTML file was not found

reason:

Django directly regards the template path as an absolute path, and the HTML file cannot be found.

After viewing the project setting file, you can see the setting method of template, including an option of “dirs”,
 

Solution:

'DIRS': [os.path.join(BASE_DIR), 'templates'],

AttributeError: ‘Settings’ object has no attribute ‘ROOT_URLCONF’

AttributeError: ‘Settings’ object has no attribute ‘ROOT_ URLCONF’

If you encounter this problem. There are the following prerequisites,
1. You deploy with uwsgi + Django
2. You have modified the settings configuration file path, for example, create a dev.py file in a new place for configuration

Then you have to look at the configuration in uwsgi.ini. Whether the settings in the WSGI file is the configuration file you want.

[Solved] AttributeError: Manager isn‘t available; ‘auth.User‘ has been swapped for ‘

AttributeError: Manager isn't available; ' auth.User' has been swapped for 'account.UserInfo'

This is because I have extended Django’s user authentication model

#setting.py
AUTH_USER_MODEL = 'account.UserInfo'

Official documents

from django.contrib.auth.models import User
from django.contrib.auth import get_user_model

User = get_user_model()

Or use the user info model directly

""" get_user_model"""
def get_user_model():
    """
    Return the User model that is active in this project.
    """
    try:
        return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
    except ValueError:
        raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
    except LookupError:
        raise ImproperlyConfigured(
            "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
        )