Tag Archives: django

How to Solve Django Error: No such column: xxx

The operation before and after the model is as follows:

First migration:

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=True)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)

After change:

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=True)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
    owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
    highlighted = models.TextField()

There are three steps for Django to modify the database

1. Make changes to models.py (normal)

2. Creating migrations using makemigrations

3. Migration using migrate

Analysis: after the modified model, the code and highlighted fields cannot be empty when the database is synchronized for the second time. If you create the highlighted field the first time, there is no impact because the table does not have an existing row. If the data table has been created for the first time and data has been inserted into the table, a default value must be defined to fill in the existing row, otherwise the database will not accept the data table changes because of violating the integrity of the data

Solution: change to

code = models.TextField(default =”)

highlighted = models.TextField(default =”)

Linux Implement Django Error: nohup: ignoring input and appending output to ‘nohup.out’

1、 Deploying Django to remote Linux server

Using xshell to connect to Linux server through SSH, the normal startup command is

python3 manage.py runserver 0.0.0.0:80

However, after you close xshell, you won’t be able to access Django

Concept: if you are running a process and you feel that the process will not end when you exit the account, you can use the nohup command. This command can continue to run the corresponding process after you exit the account/close the terminal.)

Enter

nohup python3 manage.py runserver 0.0.0.0:80

An error will be reported

nohup: ignoring input and appending output to ‘nohup.out’

2、 Solutions

1. Why

Because using nohup will generate log files, which are written to nohup.out by default

2. Solution

Output the log of nohup to/dev/null, this directory will make all the information to it disappear automatically

nohup python3 manage.py runserver 0.0.0.0:80 > /dev/null 2> /dev/null &

[Solved] Django Run Error: TypeError: object supporting the buffer API required

Type error: object supporting the buffer API required

Solution:

Change the password of database in settings.py to string format

Source code:

def scramble_caching_sha2(password, nonce):
    # (bytes, bytes) -> bytes
    """Scramble algorithm used in cached_sha2_password fast path.

    XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce))
    """
    if not password:
        return b''

    p1 = hashlib.sha256(password).digest()

The password must be in the form of string

Solution to the error of ora-06550 pls-00103 when Django connects Oracle to run PLSQL statement

Django connects Oracle and runs PLSQL statements

The code is as follows:

def exec_db():
    sql = """
    DECLARE
       v_money BINARY_INTEGER := 10;
    BEGIN
        dbms_output.put_line('Hello World');
       UPDATE TEST1 SET USER_SALERY=USER_SALERY+v_money;
       COMMIT;
    END; """
    # sql ='DECLARE v_money BINARY_INTEGER := 10; BEGIN UPDATE TEST1 SET USER_SALERY=USER_SALERY+v_money; COMMIT; END;'
    db_conn = connections['accounting']
    cursor = None
    try:
        cursor = db_conn.cursor()
        cursor.execute(sql)
        db_conn.commit()
    except:
        logger.error(traceback.format_exc())
    finally:
        if cursor:
            cursor.close()
        db_conn.close()

This SQL has no problem in the database connection tool, but the following error is reported in the code:

django.db.utils.DatabaseError: ORA-06550: line 8, column 7:

PLS-00103: Encountered the symbol “end-of-file” when expecting one of the following: ;

The symbol “;” was substituted for “end-of-file” to continue.

There are problems in writing SQL as multiple lines and single line.

Finally found the last; After that, add a space as the end. It’s going to work.

There’s no problem with one or more lines.

It’s very weird. Record it.

Solution of [errno 5] input / output error after Django is deployed on nginx

Knowledge map advanced must read: read how large-scale map data efficient storage and retrieval>>>

Environment: centos6.5 gunicorn + Django + nginx

After the configuration is completed and the project is running, the [errno 5] input/output error will be reported sometimes. At the beginning, print will report this error. After deletion, the same error will be reported in other places

my solution process and attempt are as follows:

1. The conf configuration file of nginx, and the path of configuration log

I saw an article mentioning this point, but he deployed it with uwsgi. The idea of the article is to suspect that there is no place for log files to go, which leads to IO errors. The solution is to increase log configuration
address http://shenwang.blog.ustc.edu.cn/freeshell%E4%B8%8A34218%E8%8A%82%E7%82%B9%E5%87%BA%E7%8E%B0django-errno-5-inputoutput-error/

According to this principle, I add log path configuration under the server node of nginx’s conf configuration file

access_log /home/webroot/www/public/XianyuApi/nginx.access.log;
​​​​​​​error_log /home/webroot/www/public/XianyuApi/nginx.error.log;

However, after setting this step, we restart nginx and gunicorn and find that they are the same. So I thought about the question of whether it would have authority

2. Set the access permission of the source code directory to 777
confirm the access permission of the source code folder, and recursively set the permission of all files to 777. When nginx is running, it is run by the user configured in nginx.conf, not by the user you are currently logged in to. Permissions can also lead to strange problems. This step must be confirmed at last. You may have set 777 at the beginning, but you may have added some configuration files to the directory in the middle, so check it at last< 3. Restart Dafa
but after this point is set, it will not work. After checking a lot of materials, in desperation, I restarted the Linux server. Then it’s ok…
you can also try to restart Dafa

as for which of the above steps led to the problem, I’m not sure. Anyway, I’ve done everything. If you encounter the same problem, you can try it step by step

Django Run Error: RuntimeError: maximum recursion depth exceeded while calling a Python object

Error when starting a django project

C:\Users\jerry.home-pc\PycharmProjects\mysite>python manage.py startapp app01
Traceback (most recent call last):
File “manage.py”, line 22, in <module>
execute_from_command_line(sys.argv)
File “C:\Python27\lib\site-packages\django\core\management\__init__.py”, line 363, in execute_from_command_line
utility.execute()
File “C:\Python27\lib\site-packages\django\core\management\__init__.py”, line 337, in execute
django.setup()
File “C:\Python27\lib\site-packages\django\__init__.py”, line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File “C:\Python27\lib\site-packages\django\apps\registry.py”, line 108, in populate
app_config.import_models()
File “C:\Python27\lib\site-packages\django\apps\config.py”, line 202, in import_models

RuntimeError: maximum recursion depth exceeded while calling a Python object

Command line can not be started, pycharm also can not be started

Analyze the cause: check the system python version number:.

C:\Users\jerry.home-pc\PycharmProjects\mysite>python -V
Python 2.7

Solution: Upgrade python to 2.7.5 (referenced from: https://stackoverflow.com/questions/16369637/maximum-recursion-depth-exceeded-in-cmp-error-while-executing-python-manage-py-r?rq=1)

To view the Python version number after upgrading.

C:\Users\jerry.home-pc\PycharmProjects\mysite>python -V
Python 2.7.5

Start successfully after upgrade:

C:\Users\jerry.home-pc\PycharmProjects\mysite>python manage.py startapp app01

Method 2: modify the functools.py file to achieve the same effect (not tested, you can try it yourself if you are interested)

Django path Error: ‘Specifying a namespace in include() without providing an app_name ‘

The specific error prompts are as follows:

django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_ name is not supported. Set the app_
name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_ name instead.

This is the error code in using Django:

Solution:

it can be seen from the include() function that this function has two parameters, an Arg and a namespace. I also have two parameters in the code, but the exception prompts that no app is provided_ Name, you also need to pass in a binary tuple, from the sixth line of code urlconf_ module, app_ Name = Arg, you can see that arg is the tuple, and give it to app_ Name is assigned a value, so we modify the code here as follows:

The modified code is as shown above, and the problem is solved

Reflection:

The error is that the include parameter is not set

When Django modifies the request attribute: this querydict instance is immutable

* * *

###Problem description

In many cases, if we want to modify the attribute value in the ‘request’ of the ‘Django’ project, an error will be reported to us:

“`
attributeerror: this querydict instance is immutable“`

That’s because in the official narration, the object is a non modifiable object. What should we do if we want to continue to try to modify the value in it

###Solutions

> This issue of push collates Python materials that beginners may use, including books/videos/online documents and editor/source
code. About the installation of ‘Python’, Qun: 850973621

“`
def medusa(request):
request.POST._ mutable = True

# or:
# request. Get_ Mutable = true
copy code
“`

At this point, when you need to modify the data value of the ‘request’ object, you can achieve the desired effect

Solve the problem of “typeerror: ‘bool’ object is not callable” in flash and Django

> Welcome to Flask’s large tutorial project! When it comes time to refactor the user model, run the script and it says :

TypeError: ‘bool’ object is not callable

This is the user model:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic')  @property def is_authenticated(self): return True  @property def is_active(self): return True  @property def is_anonymous(self): return False def get_id(self): try: return unicode(self.id) # python 2 except NameError: return str(self.id) # python 3 def __repr__(self): return '<User %r>' % (self.nickname) 

This is the code at the time of the call:

from flask import render_template, flash, redirect, session, url_for, request, g
from flask.ext.login import login_user, logout_user, current_user, login_required
from app import app, db, lm, oid from .forms import LoginForm from .models import User @app.route('/login', methods=['GET', 'POST']) @oid.loginhandler def login(): if g.user is not None and g.user.is_authenticated(): # error return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): session['remember_me'] = form.remember_me.data return oid.try_login(form.openid.data, ask_for=['nickname', 'email']) return render_template('login.html', title='Sign In', form=form, providers=app.config['OPENID_PROVIDERS']) 

is_authenticated is a property, not a method, as described in Resources, so just remove the parentheses. There are two typos in this section of the book. Please refer to the Git source code.

put the wrong place:
if g.user is not None and g.user.is_authenticated():
if g.user is not None and G.user. is_authenticated:
and then no error.

Example of Django model unique together

unique_ together

The set of field names used together must be unique:

 unique_together = (("driver", "restaurant"),)

This is a tuple of tuples and must be unique when considered together. It is used by Django administrators and is enforced at the database level (that is, unique statements contain the corresponding statements)CREATETABLE

For convenience, when dealing with a single set of fields, unique_ Together can be a single tuple:

  unique_ together = (“driver”, “restaurant”)

  

A manytomanyfield cannot be included in unique_ Together( It’s not clear what that even means!) If you need to verify the uniqueness associated with a manytomanyfield , try signal or explicit through model

In validation error when constraints are violated, the unique_ Together error code

Introduction to official documents

generally acts on:

the setting field is unique, but there is a combination form, and it is not repeated

save users as the only user and course, but a user has multiple courses, so this method is used to save

This metadata is very important! It is equivalent to the joint constraint of the database

For example, suppose there is a user table, which contains the user’s name, date of birth, gender, native place and so on. The only requirement is that all users do not repeat, but now there are several “Zhang Wei”. How can we distinguish them( Don’t talk to me. This is not the issue

We can set that two users can’t be born in the same place at the same time and both are called “Zhang Wei”. Using this kind of joint constraint, we can ensure that the database can add users repeatedly (don’t talk about small probability with me). How to implement this constraint in Django’s model

Using unique_ Together , that is to say, unite only

For example:

  unique_together = (('name', 'birth_day', 'address'),)

In this way, even if there are two Zhang Wei who were born on the same day, they have different native places, that is, two different users. Once all three are the same, it will be rejected by Django. This metadata is often used in the background of admin, and forced to be applied to the database level

  unique_ Together receives a two-dimensional tuple ((XX, XX, XX,…), (), (), ()…). Each element is a tuple, representing a group of joint unique constraints. Multiple groups of constraints can be set at the same time. For convenience, when there is only one set of constraints, one-dimensional elements can be simply used, for example:

  unique_together = ('name', 'birth_day', 'address')

Union only cannot work on ordinary many to many fields

  unique_ Together = ((‘username ‘,’password’), (‘age ‘,’date’),) ා union is unique. When all fields in any tuple parameter are the same, they cannot be added