Tag Archives: django

Solution of dpkg interrupted problem

Linux installation software is sometimes encountered “DPKG is interrupted, you must manually run sudo DPKG — configure -a to solve this problem”, but following the instructions does not solve the problem well. /var/lib/dpkg/updates is the update file for /var/lib/dpkg/updates. This is the update file for /var/lib/dpkg/updates. Sudo rm /var/lib/dpkg/updates/*
sudo apt-get upgrade
*]sudo apt-get update
[*]sudo apt-get update
[*]sudo apt-get update
[*]sudo apt-get upgrade
[*]sudo apt-get upgrade
[*]sudo apt-get upgrade
PS: “DPKG” is short for “Debian Packager”. A dedicated “Debian” package management system for easy installation, update, and removal of software. All “Linux” distributions from “Debian” use “DPKG”

Some mistakes and solutions in Django

Some of Django’s common mistakes and fixes
The CSS and JS files fail to model the existing tables the data table field names don’t match the model field URL match problem view function passes the data problem

CSS and JS files are invalid
When you load a view with CSS and JS files, the easiest way to do this is to say href= “absolute path to file”, but a lot of times you write relative paths because it’s easier. If relative paths are used, static files cannot be found when a page submits a form or redirects to a view function with arguments. So load static file {% load static %} and use reverse parsing to make the page look for static files.
Model existing tables
To create ORM on tables that have already been in the database, run Python manager.py InspectDB & GT; Model.py to generate the model for the existing table, make sure to comment db_manage =False or delete it directly, otherwise Django has no permission to operate on the table.
The data table field name does not match the model field
The corresponding column is not a field name. You can implement the ORM by setting db_column = “corresponding field name” in the model
Url matching problem
When your two url matching rules are written very closely, if load is written on the top without any initial restriction (^), the following url will match the first one, even if it resolves
, such as the following two urls:

  url(r'load/(?P<index>.*)/', views.load, name='load'),
  url(r'manage_load/(?P<index>.*)/', views.manage_load, name='manage_load'),

Since the LOAD URL is written above, when you parse the URL backwards, {% URL “load” %}, by default Django matches urls from top to bottom, matching the first one because there is no restriction on the beginning and end.

  url(r'^load/(?P<index>.*)/', views.load, name='load'),
  url(r'manage_load/(?P<index>.*)/', views.manage_load, name='manage_load'),

You can use ^,$as a starting and ending character limit and it won’t match any other URL.
View functions pass data problems

request.session["index"] = index
request.session.flush()

In many cases, passing values from view function to view function is the simplest way to record data except passing parameters to view function. The following sentence can be used to clear session in the login interface or some fixed page, otherwise the data will exist until it is destroyed automatically by Django.

Django. Using f () to solve the competition problem

What are the competition issues:
When multiple users operate on a field at the same time, there is no expected return.
F () function:

from django.db.models import F

def vote(request, choice_id):
    selected_choice = question.choice_set.get(pk=request.POST['choice'])
    selected_choice.votes = F('votes') + 1
    selected_choice.save()

 

Practice based on how to tango with Django 1.7 (1)

The point of the book is to develop an application called Rango. To develop this application, it will cover most of the core content of making web applications.
2.4Rango: Initial Design and Planning
2.4.1 Design overview
Your client needs to set up a website called Rango, which allows users to browse their own customized web pages. In Spanish language, rango used to mean “sort through quality” or “place in the hierarchy of society” (see https://www.vocabulary.com/dictionary/es/rango).

On the home page of the site, visitors can see:

The 5 Most viewed pages the 5 highest quality directories How visitors can browse or find a directory

When a user views a directory page, it will display:

Directory name, number of visits, number of likes; A page close to the directory (showing the page title and its URL); Some search functions (via Bing’s search API) are used to find other pages that can be linked to this directory

A particular directory, the name of the directory the client wants, the number of times each directory page has been visited and how many users have clicked the ‘like’ button to be recorded. Each directory can be accessed via a readable URL – e.g. /rango/books-about-django/. Only registered users can search and add pages to the catalog. In the meantime, visitors can sign up for an account.

At first glance, the app looks strange. In fact, it’s just a list of directories, and they can link to the page, right?However, there is still a lot of complexity to deal with. First, let’s try to draw a picture of what we want to develop.
2.5 practice
Before going on, consider the instructions below and try to draw a design.
A framework URL binding of the N-tier or system architecture diagram home page and catalog page is the entity-relationship diagram that we are going to implement the data model
2.6 N- layer structure
Rango is a variant of the 3-tier structure in which most Web applications are structured, and requires interaction with an external service.
The UML diagram is drawn using Processon

If we were to create Web applications using Django, we would need the following techniques for each layer.
Client is a browser (i.e. Chrome, Firefox, Safari, etc.) that will return HTML/CSS page; Middleware is a Django application that will form the end of developing Django built into a Web service; database will be SQLite3 database engine based on Python; search API will be Bing search API
Although we had to deal with all the pieces above, most of the focus of the book was on developing middleware.
2.7 wire frame
Wireframes are a great way to design a website’s interface. They save a lot of time and are different from tool-dependent hand drawing. For Rango, we would like its home page to look like the figure below.

The directory page is shown in the figure below:

2.8 Page and URL mappings
By the rule description, we have confirmed that we will present two pages to the user at different times. To get to different pages we need to map the URL, which is the text that the user enters in the browser to get to the page.Rango’s URL map is shown below.
/rango/about/ will point to the About page view./ Rango /category/ will point to each category page view, which might be:

The game; Python trick code or compiler

/rango/etc/, which sets aside etc for future functional implementation
When we create an application, we might need to create some other URL mappings. But those are the ones that we need to build in the first place. Also consider that if the provided directory name does not exist, we need to convert the directory name to a valid URL string.
As we dig deeper into the book, we’ll get a handle on creating web pages with the Django framework and using the model-View-Template design pattern. Now that we have a general idea of the URL mapping and web page interface, we also need to define the data model to provide the data for our application.
2.9 Entity-relationship diagram
Given the rules, we know that there are at least two entities: a directory and a page. One directory can hold many pages at the same time. We can describe our data model through the ER diagram below.

Note that a page can be in one or more directories. So we need to have a many-to-many relationship. To make things less complicated, let’s make the simple assumption that a directory can contain multiple pages, but a page can only belong to one directory. This does not prevent a page from appearing in two different directories – in a less-than-ideal situation, the page might enter twice.
Writing technical notes is a great hobby, especially when you know it will happen again! By writing them down, you can communicate with your development team to ensure that the same problems can be solved quickly.
Str for string or char,Int for integer,URL for URL, FK for Foreign Key.

We also have a user table – not shown here, but described later. In the following sections we will see how to instantiate these data models in Django and learn how to use Django’s ORM to connect to a database.
2.10 summarize
These designs and instructions will be helpful in building our Web applications. The same techniques and procedures we will use apply to most data-driven websites. Familiarity with these specifications and designs is of great benefit to us.
If you already have Python2.7 and Django1.7 installed, and you know how to set up your path from the command line, you can skip the Django basics chapter. Otherwise, let’s look at chapter three.
2.10.1 Work with the Django official tutorial
We recommend that the Django official tutorial be used as an exercise for each chapter of the book. You can find the correspondence between the chapters in the two books in the table below. The official teaching exercises will help you get a deep understanding of the Django framework and improve your skills.
Tango woth Django Django Tutorial
Chapter 3 Part 1 – Models
Chapter 5 Part 2 – The Admin Interface
Chapter 6 Part 3 – URLs and Views
Chapter 7 Part 4 – Templates
Chapter 18 Part 5 – Testing
Chapter 11 Part 6 – CSS

fatal error: Python.h: No such file or directory

Error:
system centos7.4 64-bit
python 2.7.5
plugins/python/uwsgi_python.h:2:20: fatal error: Python.h: No such file or directory
#include < Python.h>
Command “/usr/ bin/python2-u-c” import setuptools, tokenize;
Command “/usr/ bin/python2-u-c” import setuptools, tokenize; The file = ‘/ TMP/PIP – build – r2TLym uwsgi/setup. Py “; F = getattr (tokenize, open, open) (file); Code = f.r ead (). The replace (‘ \ r \ n ‘, ‘\ n’); f.close(); exec(compile(code, file, ‘exec’)) “install –record/TMP/pip-jwt5ox-record /install-record. TXT –single-version –compile” failed with error code 1 in/TMP/pip-build-r2tlym /uwsgi/

Check the solution:
yum install python-devel.x86_64
Then run the installation and fix the problem.

django.core.exceptions . improverconfigured: mysqlclient 1.4.0 or new is required; you have

Django. Core. Exceptions. ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; You have solutions for 0.10.1
An error occurred today when replacing mysql database while learning django:
is written in _init_. Py

import pymysql
pymysql.install_as_MySQLdb()

Error: the django. Core. Exceptions. ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; You have 0.10.1.
This is actually a mismatch between django and Pymysql. Python3 is not supported by mysqldb.
1. Tried to comment the python/Lib/site – packages/django/db/backends/mysql/base. Py files
' ' 'if the version & lt; (1, 4, 0): Raise ImproperlyConfigured(' mysqlClient 1.4.0 or Newer is required; You have %s.' % Database.) '
2. Updated version of Django, also useless
Final solution:
init.py is changed to

import pymysql
pymysql.version_info = (1, 4, 13, "final", 0)
pymysql.install_as_MySQLdb()

Specify the Pymysql version directly
Xiaobai learns Python, if there is a mistake, please give me more advice

Django reads the txt file in view

Problem description:
In view, you want to load a TXT of block-words to block out dirty words.
but cannot find the file
Solutions:
Use the full path, put TXT under the same path as view.py, and add the first two lines

module_dir = os.path.dirname(__file__)
file_path = os.path.join(module_dir, 'block-words.txt')  # full path to text.
block_words = pd.read_csv(file_path,header=None)

Subsequent operation:
Use find to match, replacing all matched words with asterisks

for word inblock_words[0]:
    if info.find(word) != -1:
        info = info.replace(word, '*' * len(word))

Four ways to get Django parameters in request

1. Query string data (String)
Like:?key1=value1& Key2 = value2
use

requisition.get ("key", "value") GET
2. request-getlist ("key", []) GET the last value

Ii. Request Body Data (BODY) :
For example: form data, JSON,…
2.1 form data :(only post requests are supported)

request.POST.get("name", "")

2.1 json data :(post and put requests are supported)

Loads (json_str) json_str = request. Body # attribute to get the original request data
json_dict = json.json (json_str)# convert the original data into dictionary format
json_dict. Get ("key", "default value ") # get the data

3. Specific part of data in the URL path

Regular, or routing converter

4. Request Header Data (HEADER) :

request.MEAT.get("key")

Django debug = false internal server error 500

Add the following in Setting.py

# AMDIN CONFIGURATION
#-------------------------------------------------------------------------------
ADMINS = [('hiveme', '[email protected]')]

# EMAIL CONFIGURATION
#-------------------------------------------------------------------------------
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

When set from this, if the server generates 500 errors it prints the error message to the log/screen. You can also set up other EMAIL_BACKEND so that it will email errors to your email.

django.core.exceptions . improveconfigured: error loading MySQL DB module. Django configuring MySQL database

A, errors,

Traceback (most recent call last):
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in <module>
    import MySQLdb as Database
ModuleNotFoundError: No module named 'MySQLdb'

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

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
    django.setup()
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
    app_config.import_models()
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/models/base.py", line 114, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/models/base.py", line 315, in add_to_class
    value.contribute_to_class(cls, name)
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/models/options.py", line 205, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/utils.py", line 202, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend
    return import_module('%s.base' % backend_name)
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/home/ubuntu/anaconda2/envs/python3/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 20, in <module>
    ) from err
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?

Ii. Problem Solving
1. Source of problem
After installation of Django, the default database driver is sqlite, but I do not have sqlite database, so change to
mysql, then go to the directory first/first/settings.py, and find:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

Modified to:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'first',
        'USER': 'python',
        'PASSWORD': '123456',
        'HOST': '192.168.99.124',
        # 'PORT': '',
    }
}

Run the command python manage. Py runserver then executes to start the service at the following Error:
django. Core. Exceptions. ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
2. Solve
Obviously, there is no mysql driver installed, just install it, so I quickly typed the command line:

pip install mysql-python

ImportError: No module named 'ConfigParser'
Python3.x is changed to lowercase relative to PYTHON 2.x, indicating that THE MYSQL python in PIP does not support Python3.x. Maybe the update in PIP is relatively slow, so we will download their source code installation. However, the latest update date of the source code is 2012, and there is still no support for Python3.x!
How does this work?Change the support python3 driver try, heart energizes, grass mud horse, of course, as a result on making a search, found a PyMySQL (https://github.com/PyMySQL/PyMySQL), which, of course, also have it in the PIP, then I quickly on the command line with:

pip install PyMySQL

Django does not recognize this alien monk, how to do, or to do, find mysite/mysite/init.py, enter the following content and save:

import pymysql
pymysql.install_as_MySQLdb()

Then When I ran Python Manager.py Runserver, another prompt popped up:
You have unapplied migrations; Run 'Python manage. Py Migrate' to apply them.
Of course, this prompt does not affect the operation of the native server. At this time, when we visit http://127.0.0.1:8000, we will see the successful prompt:

It worked!

Congratulations on your first Django-powered page.

Of course, you haven't actually done any work yet. Next, start your first app by running python manage.py startapp [app_label].

You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work!

Of course, I didn't like the warning, and he told me what to do to get rid of him, of course! I quickly copy the contents to the command line:

python manage.py makemigrations
python manage.py migrate

Then restart the service, it's normal!


The environment

    Python version: 3.6.0Django version: 2.5

A server error occurred. Please contact the administrator.

In terms of Django site management, login to site Admin, if there is a problem with a title, it could be for the following reasons:
1, localization, letter case didn’t pay attention to, the right is LANGUAGE_CODE = 'useful - Hans' and TIME_ZONE =' Asia/Shanghai ', then analysis is setting up the contents of the file has been changed after cannot be interpreter identification, so later met the same problem can according to this train of thought analysis (then if new create a project to try again, or if the original error, Maybe the previous project wasn't closed). 2. Without the model migration, the data table of the project will not be generated, and the login site is the operation of the data table, without the migration even without the table, how can you log into the site?

Error loading pscopg2 module: no module named pscopg2

When using Django to connect to a postgresql database, use python manager.py migrate to create a database.
django. Core. Exceptions. ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' solution:
apt install psycopg2 if it fails, don't care if apt install libpq-dev or apt install postgresql-server-dev-x.y must be installed successfully, one of them PIP install psycopg2 must be installed successfully. Finally, remember to set an access password for the database set in your setting. Py , otherwise an error will be reported. You can set the access password by referring to the relevant commands here.