Django开发示例配置及系列常见错误,如:AttributeError: module 'django.core.serializers.json' has no attribute 'loads'

关于Django开发中系列常见的错误,比如:AttributeError: module ‘django.core.serializers.json’ has no attribute ‘loads’。

1、提交表单报错:RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and you have APPEND_SLASH set.

解决方法:
RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and you have APPEND_SLASH set.
提示form的action地址最后不是/结尾的,而且APPEND_SLASH的值是Ture

将from的action地址改为/结尾的就可以了
或者
修改settings:APPEND_SLASH=False


2、当运行一个django项目后,出现了这样的一个错误,CSRF verification failed. Request aborted.

这是因为网页上会进行安全校验。

方法一:

我们可以在settings.py中注释掉一行即可。这一行大概在46行左右。
'django.middleware.csrf.CsrfViewMiddleware'

方法二:

在html页面的form标签下加上
{%csrf_token%}

方法三:

views.py上导入
from django.views.decorators.csrf import csrf_exempt

然后在自己写的函数上面加上
@csrf_exempt

3、Django 进行数据查询并返回jsons数据,中文乱码解决方法。很容易出现的一个错误是中文乱码,重点在于 json_data = serializers.serialize(“json”, products, ensure_ascii=False) 中第三个参数 ensure_ascii=False 。

django之处很多的序列化格式,有些需要你安装第三方支持的模块,xml,json和yaml是默认支持的。如果你是使用utf-8或者其他的非ascii编码数据,然后用json序列器,注意穿一个ensure_ascii参数进去,否则输出的编码将会不正常。比如:

json_serializer = serializers.get_serializer("json")()
json_serializer.serialize(queryset, ensure_ascii=False, stream=response)

4、使用md5加密:

import hashlib

upwd="123456"
md5 = hashlib.md5()
md5.update(upwd.encode("utf-8"))
print(md5.hexdigest())

5、出现(1146, “Table ‘charity_platform.django_session’ doesn’t exist”)
解决方法:
在控制台执行以下命令:

# python manage.py makemigrations sessions
# python manage.py migrate sessions

6、出现 get_session_auth_hash() missing 1 required positional argument: ‘self’

在创建的变量或者调用的方法后面跟上 () ,比如:

user=User()

7、出现 Cannot force an update in save() with no primary key.
操作的数据对象一定要给主键,且数据库中对应的表一定要有这个主键。


models 的示例:

from django.db import models
# -*- coding: utf-8 -*-
# Create your models here.


# 字段的含义
# 1、models.AutoField  自增列= int(11)
#   如果没有的话,默认会生成一个名称为 id 的列,如果要显示的自定义一个自增列,必须将给列设置为主键 primary_key=True。
# 2、models.CharField  字符串字段
#   必须 max_length 参数
# 3.models.DateField  日期类型 date
#   对于参数,auto_now =True则每次更新都会更新这个时间;auto_now_add 则只是第一次创建添加,之后的更新不再改变。
# 4.models.DateTimeField  日期类型 datetime
#   同DateField的参数
# 5.models.EmailField  字符串类型(正则表达式邮箱)=varchar
#   对字符串进行正则表达式
# 6.models.FloatField  浮点类型= double
# 7.models.IntegerField  整形
# 8.models.SmallIntegerField  数字
#   数据库中的字段有:tinyint、smallint、int、bigint
# 9、models.TextField  字符串=longtext
# 10、models.TimeField  时间 HH:MM[:ss[.uuuuuu]]
# 11、models.URLField  字符串,地址正则表达式
# 12、models.BinaryField  二进制
# 13、models.ImageField图片
# 14、models.FilePathField文件

# 参数的含义
# 1、null=True
#   数据库中字段是否可以为空
# 2、blank=True
#   django的Admin中添加数据时是否可允许空值
# 3、primary_key =False
#   主键,对AutoField设置主键后,就会代替原来的自增 id 列
# 4、auto_now 和 auto_now_add
#   auto_now 自动创建---无论添加或修改,都是当前操作的时间
#   auto_now_add 自动创建---永远是创建时的时间
# 5、choices
# GENDER_CHOICE =(
# (u'M', u'Male'),
# (u'F', u'Female'),
# )
# gender = models.CharField(max_length=2,choices = GENDER_CHOICE)
# 6、max_length
# 7、default  默认值
# 8、verbose_name  Admin中字段的显示名称
# 9、name|db_column  数据库中的字段名称
# 10、unique=True  不允许重复
# 11、db_index =True  数据库索引
# 12、editable=True  在Admin里是否可编辑




# Create your models here.
class NewsInfo(models.Model):
    id = models.IntegerField(max_length=20, db_column='id', primary_key=True)
    content = models.CharField(max_length=200, db_column='content')
    date = models.CharField(max_length=200, db_column='date')
    title = models.CharField(max_length=200, db_column='title')
    uid = models.CharField(max_length=200, db_column='user_id')
    remark = models.CharField(max_length=200, db_column='remark')

    class Meta:
        db_table = "news_info"


class CharityProject(models.Model):
    id = models.IntegerField(max_length=20, db_column='id', primary_key=True)
    code = models.CharField(max_length=200, db_column='project_code')
    name = models.CharField(max_length=200, db_column='project_name')
    content = models.CharField(max_length=2000, db_column='project_content')
    ptime = models.CharField(max_length=200, db_column='publish_time')
    puid = models.CharField(max_length=200, db_column='publish_user_id')
    puname = models.CharField(max_length=200, db_column='publish_user_name')
    puphone = models.CharField(max_length=200, db_column='publish_user_phone')
    auid = models.CharField(max_length=200, db_column='audit_user_id')
    atime = models.CharField(max_length=200, db_column='audit_time')
    status = models.IntegerField(max_length=20, db_column='project_status')
    level = models.IntegerField(max_length=20, db_column='project_level')
    remark = models.CharField(max_length=200, db_column='remark')

    class Meta:
        db_table = "charity_project"

class EvaluationInfo(models.Model):
    id = models.IntegerField(max_length=20, db_column='id', primary_key=True)
    pcode = models.CharField(max_length=200, db_column='project_code')
    euid = models.CharField(max_length=200, db_column='evaluation_user_id')
    content = models.CharField(max_length=200, db_column='evaluation_content')
    time = models.CharField(max_length=200, db_column='evaluation_time')
    status = models.IntegerField(max_length=20, db_column='evaluation_status')
    ouid = models.CharField(max_length=200, db_column='operate_user_id')
    remark = models.CharField(max_length=200, db_column='remark')

    class Meta:
        db_table = "evaluation_information"


class MaterialInfo(models.Model):
    id = models.IntegerField(max_length=20, db_column='id', primary_key=True)
    code = models.CharField(max_length=200, db_column='material_code')
    name = models.CharField(max_length=200, db_column='material_name')
    style = models.IntegerField(max_length=200, db_column='material_style')
    number = models.IntegerField(max_length=200, db_column='material_number')
    status = models.IntegerField(max_length=200, db_column='material_status')
    logistics = models.CharField(max_length=2000, db_column='material_logistics')
    duid = models.CharField(max_length=200, db_column='donate_user_id')
    dtime = models.CharField(max_length=200, db_column='donate_time')
    auid = models.CharField(max_length=200, db_column='accept_user_id')
    ustyle = models.CharField(max_length=200, db_column='use_style')
    atime = models.CharField(max_length=200, db_column='accept_time')
    remark = models.CharField(max_length=200, db_column='remark')

    class Meta:
        db_table = "material_information"

class UserInfo(models.Model):
    id = models.IntegerField(max_length=20, db_column='id', primary_key=True)
    age = models.IntegerField(max_length=20, db_column='age')
    email = models.CharField(max_length=20, db_column='email')
    lname = models.CharField(max_length=20, db_column='login_name')
    lpass = models.CharField(max_length=50, db_column='login_pass')
    operateid = models.CharField(max_length=50, db_column='operate_id')
    role = models.IntegerField(max_length=11, db_column='role')
    status = models.IntegerField(max_length=11, db_column='status')
    sex = models.CharField(max_length=50, db_column='sex')
    uname = models.CharField(max_length=50, db_column='user_name')
    nname = models.CharField(max_length=20, db_column='nick_name')
    phone = models.CharField(max_length=20, db_column='phone')
    remark = models.CharField(max_length=20, db_column='remark')

    class Meta:
        db_table = "user_info"



# python manage.py makemigrations  #这个命令记录我们对models.py的所有改动,并且将这个改动迁移到migrations这个文件下生成一个文件,因为现在并没有涉及models.py 的操作,所以不会有什么结果
# python manage.py migrate    #这个命令作用到数据库也就是执行migrations里面新改动的迁移文件更新数据库,也会创建系统其他模块的一些表,比如用户模块的一些数据表,执行该命令后可查看对应数据库的变化
# python manage.py createsuperuser  # 创建超级账号

# python manage.py makemigrations sessions
# python manage.py migrate sessions


# username: 用户名
# password: 密码
# first_name: 姓名
# last_name: 姓名
# email: 邮箱
# groups: Group类多对多的关系对象管理器
# user_permissions: Permission类多对多的关系对象管理器
# is_staff: 是否工作人员
# is_active: 是否激活
# is_superuser: 是否管理员
# last_login: 最近登录时间
# date_joined: 注册时间


settings的示例:

"""
Django settings for CharityPlatform project.

Generated by 'django-admin startproject' using Django 3.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'f9xj=g=+nr9@s61@3=s+m-izl0!iu9e2d%49m2f^anb%@4k&72'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'fastframe.apps.FastframeConfig',
    # 'fastframe',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'CharityPlatform.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'CharityPlatform.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # 数据库的类型
        'NAME': 'charity_platform',  # 所使用的的数据库的名字
        'USER': 'root',  # 数据库服务器的用户
        'PASSWORD': 'wdsjnsjydjy',   # 密码
        'HOST': 'localhost',  # 主机
        'PORT': '3306',   # 端口
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

# 静态资源的存放通过设置 STATIC_URL, STATICFILES_DIRS 来设置,一般STATIC_URL设置为:/static/
# 这个static 是在Django 具体APP下建立的static目录,用来存放静态资源。而STATICFILES_DIRS一般用来设置通用的静态资源,对应的目录不放在APP下,而是放在Project下
# 具体在模板文件中访问的时候,都是统一用:/static/资源名的方式,就可以访问到资源,不论具体的目录是APP下的static,还是project下的common_static, 都可以用/static/资源名的方式访问到。
# 为增强可移植性,在模板中可以用:STATIC_URL来代替具体的/static/来设置资源路径,但是需要在settings.py中2个地方进行设置,否则会发生取不到资源的错误:
# 1. INSTALLED_APPS 中,加入 'django.contrib.staticfiles'
# 2. TEMPLATES 中,context_processors中,加入django.template.context_processors.static
# 模板中调用时:
#  / 

STATIC_URL = '/static/'
STATICFILES_DIRS=[
    os.path.join(BASE_DIR, "common_static"),
                  ]



LOGIN_URL = '/index' #把这个页面设置成登录页面,只要没登录就会跳转这个页面

你可能感兴趣的:(Python相关,django,python,配置,加密,数据库)