Tag Archives: django

Django PythonConsole error: Requested setting DEFAULT_INDEX_TABLESPACE

Error:
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Solution:
Add to the python file that reports the error:

import os,django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings") # project_name project name
django.setup()

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

Error: command error out with exit status 1: Python when installing mysqlclient in django2.0 setup.py egg_ info

Environment: centos7 + django2.0 + Python 3.6

Django2.0 needs to install pymysql and mysqlclient to connect with MySQL

pip3 install PyMySQL

pip3  install  mysqlclient

 

Error in installing mysqlclient

Then install the dependency

yum install  mysql-devel

yum install python-devel

Install PIP3?Install?Mysqlclient?OK again!!!!!!!

Error creating Django application: error on Python side.Exit code:1.

Due to the need of work, I recently learned Django based web program, but in the actual development, I also encountered a series of problems:
New Django project based on pychar compiler, and the following errors appeared:

the solution given:
1. Django 1.11 above does not seem to support Python 2.7, change to Django 1.10 version
1 2. It’s better to set up the project directory of Django in Chinese
3. It’s better to re install Django in the same directory as Python
PS: it’s just a problem you encounter in your study. You are welcome to give us some advice

File “manage.py“, line 17 ) from exc ^ SyntaxError: invalid syntax

The newly created Django project will run directly after entering

python manage.py runserver

The mistakes are as follows:

user@UserdeMacBook-Pro djangoProject % python manage.py runserver
  File "manage.py", line 17
    ) from exc
         ^
SyntaxError: invalid syntax

I feel a little puzzled. Later, I found that there was a problem with the specification of the python version. I should specify the python 3 version

python3 manage.py runserver

That’s it.

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