Sort out the problems encountered in the process of learning Django
How to create a new user
- Create a new super user
python manage.py createsuperuser
In the command line, enter the user name, email address (optional, can be empty), password, and second confirmation password in sequence. The * sign will not be displayed when entering the password in the command line, so ensure that the passwords entered twice are the same. If the password is too short or the same as the account name, a prompt will appear, and you can force it by directly entering y.
- Create a new normal user
python manage.py shell
Directly use Django's shell command to create a new user, the specific operation is as follows
>>>from django.contrib.auth.user import User
>>>user = User.objects.create_user('用户名', '邮箱地址', '密码')
>>>user.save()
The email address can be empty, this method is applicable to Django 3.2, the official documentation is here
Errors related to database migration
ProgrammingError: relation “django_content_type” already exists. 报错
In versions after Django 1.8, virtual initialization can be used to skip existing database tables. The method of use is:
python manage.py migrate --fake-initial
You can skip all generated tables and continue to generate other ungenerated tables. The official documentation is here
Tables are not generated after project migration (tables cannot be generated from models, database modifications cannot be detected)
Generally, it is common to directly delete the database file, and the normal deletion of the database should be in the following order:
- To delete a table in a database, use
drop table
the command. - Comment out
model.py
unneeded models in the file. - Generate a new migration file and execute
python manage.py makemigration
,python manage.py migrate
In other cases, deleting the database may cause a problem that the table cannot be generated. Troubleshoot the problem in the following order:
- Delete all files
migrations
in the folder under the app except .__init__.py
- Use the tool to open the directory
db.sqlite3
, finddjango_migration
the table, and delete all the data in the table - Re-use the command to generate the migration file and execute it
python manage.py makemigration
,python manage.py migrate
Among them, macOS can use the built-in terminal function to modify the database
>>>sqlite3 数据库所在路径
>>>.table #用于查看所有的表
>>>delete * from django_migrations; #注意分号不能漏,执行完毕后即删除所有的迁移记录