最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Django中获取当前配置的参数出错:AttributeError dict object has no attribute

Django crifan 144浏览 0评论
折腾:
【未解决】Django中如何自定义返回分页数据
期间,想要获取:
/conf/development/settings.py
# django-restframework and jwt settings
REST_FRAMEWORK = {
...
    # 'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination',
    'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.CustomPagination',
    'PAGE_SIZE': 20,
}
中的PAGE_SIZE
用:
from django.conf import settings

def list(self, request, *args, **kwargs):
  logger.info("ScriptViewSet list: request=%s", request)
  logger.info("settings=%s", settings)
  logger.info("settings.REST_FRAMEWORK.PAGE_SIZE=%s", settings.REST_FRAMEWORK.PAGE_SIZE)
结果:
INFO|20180810 21:21:32|views:list:105|settings=<Settings "conf.development.settings">
File "/Users/crifan/dev/dev_root/company/xxx/projects/xxx/server/xxx/apps/script/views.py", line 106, in list
logger.info("settings.REST_FRAMEWORK.PAGE_SIZE=%s", settings.REST_FRAMEWORK.PAGE_SIZE)
AttributeError: 'dict' object has no attribute 'PAGE_SIZE'
现在想要获取Django的当前(development)中的配置
django app settings
Applications | Django documentation | Django
Django settings | Django documentation | Django
Settings | Django documentation | Django
Writing your first Django app, part 1 | Django documentation | Django
python – Include application in django settings.py – Stack Overflow
django get current settings
How do I reference a django settings variable in my models.py? – Stack Overflow
python – Django: Check if settings variable is set – Stack Overflow
好像是引用的写法搞错了,所以提示:
AttributeError: ‘dict’ object has no attribute ‘PAGE_SIZE’
因为:settings.REST_FRAMEWORK提示是dict,应该用:
logger.info('settings.REST_FRAMEWORK["PAGE_SIZE"]=%s', settings.REST_FRAMEWORK["PAGE_SIZE"])
page = request.query_params.get('page', 1)
page_size = request.query_params.get('page_size', settings.REST_FRAMEWORK["PAGE_SIZE"])
然后就可以了:
INFO|20180810 21:29:13|views:list:106|settings.REST_FRAMEWORK["PAGE_SIZE"]=20
【总结】
Django中引用当前配置其实就是:
from django.conf import settings
不过对于:
REST_FRAMEWORK = {
    'PAGE_SIZE': 20,
}
的写法,注意不是:
settings.REST_FRAMEWORK.PAGE_SIZE
而是:
settings.REST_FRAMEWORK["
PAGE_SIZE
"]
因为:settings.REST_FRAMEWORK是个dict。

转载请注明:在路上 » 【已解决】Django中获取当前配置的参数出错:AttributeError dict object has no attribute

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
86 queries in 0.107 seconds, using 20.71MB memory