允许的HTTP方法
装饰器django.views.decorators.http可用于根据请求方法限制对视图的访问。如果不满足条件,这些装饰器将返回django.http.HttpResponseNotAllowed
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET", "POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
# ...
pass
django中@method_decorator用法
1、为整个视图增加装饰器方法
@method_decorator(login_required, name='dispatch')
class PuConfigCopyView(View):
pass
2、为整个视图增加特定装饰器方法
@method_decorator(login_required, name='get')
class PuConfigCopyView(View):
def get(request):
pass
3、为特定请求增加装饰器方法
class PuConfigCopyView(View):
@method_decorator(login_required) # 为get方法添加了装饰器
def get(request):
pass
迁移时PostgreSQL是最强大的,设置null=True即可
使用FileField或时 ImageField
class Car(models.Model):
photo = models.ImageField(upload_to='cars')
调用实例
>>> car = Car.objects.get(name="57 Chevy")
>>> car.photo
<ImageFieldFile: chevy.jpg>
>>> car.photo.name
'cars/chevy.jpg'
>>> car.photo.path
'/media/cars/chevy.jpg'
>>> car.photo.url
'http://media.example.com/cars/chevy.jpg'
创建用户密码使用哈希加密
u = User.objects.get(username='john')
u.set_password('new password')
Django重写authenticate
u = User.objects.get(username='john')
u.set_password('new password')class PhoneAuthenBackend(object):
"""
手机验证码认证用户
"""
def authenticate(self, phone=None):
try:
user = UserModel.objects.get(phone=phone)
if user.is_active:
return user
return None
except UserModel.DoesNotExist:
return None
except MultipleObjectsReturned:
return None
def get_user(self, user_id):
try:
return UserModel.objects.get(pk=user_id)
except UserModel.DoesNotExist:
return None
在settings中
AUTHENTICATION_BACKENDS = [
'account.authentication.PhoneAuthenBackend',
]
使用get_user_model()
get_user_model获取的是settings中的AUTH_USER_MODEL = 'account.MyUser'
Django时区问题
在Django的settings中,有两个配置参数是跟时间与时区有关---->TIME_ZONE和USE_TZ
USE_TZ为True,Django使用系统默认时区,即America/Chicago,此时TIME_ZONE不管有没有设置都不起作用。
USE_TZ为False,TIME_ZONE为None,Django会使用默认的America/Chicago时间。
USE_TZ为False,TIME_ZONE设置为其它时区,则要具体的程序运行环境。如果是Windows系统,则TIME_ZONE设置是没用的,Django会使用本机的所使用的时区。如果为其他系统,则使用TIME_ZONE设置的时区------>即USE_TZ = False, TIME_ZONE = ‘Asia/Shanghai’, 使用上海的UTC时间。
默认的Python Shell通过datetime.now返回的应该是当地时间,在这里即中国时区,但是当settings.TIME_ZONE设置为UTC的时候,通过datetime.now返回的就是UTC时间。
可以试试将TIME_ZONE设置成中国时区:此时datetime.now返回的就是中国时区了。
当使用timezone.now函数的时候,情况则不一样,在支持时区功能的时候,该函数返回的是一个带有UTC时区信息的aware datetime obeject,即它不受TIME_ZONE变量的影响。
Restframework返回指定异常信息
from rest_framework import serializers
try:
xxx
except Exception as e:
raise serializers.ValidationError({'xxx': 'xxxx})
django数据有效性验证方法
obj = models.UserInfo(username='11234', email='uu')
try:
print(obj.clean_fields())
except Exception as e:
print(e)