gpt4 book ai didi

python django shell(ipython)意外行为或错误?

转载 作者:太空狗 更新时间:2023-10-29 23:59:41 27 4
gpt4 key购买 nike

在使用语言环境设置时,Django shell 的行为(至少对我而言)出乎意料。当从外部脚本调用时,逗号分隔的十进制字段的表单验证有效,而从 django shell (ipython) 调用时失败。

开始一个新项目我得到了以下文件:

local_forms/
├── local_forms
│   ├── __init__.py
│   ├── models.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
├── my_form.py
├── test_form.py

local_forms/models.py:

from django.db import models

class MyModel(models.Model):
val=models.DecimalField("value",max_digits=11,decimal_places=2)

我的表格.py

from django import forms
from django.conf import settings
from local_forms.models import MyModel


class MyForm(forms.ModelForm):
val = forms.DecimalField(localize=True)

def __init__(self,*args,**kwargs):
super(MyForm,self).__init__(*args,**kwargs)
self.fields['val'].localize=True
if __debug__:
print self.fields['val'].localize
print ("Separator: "+settings.DECIMAL_SEPARATOR)
print ("Language: " +settings.LANGUAGE_CODE)

class Meta:
model=MyModel

测试表格.py:

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "local_forms.settings")

import my_form

form=my_form.MyForm({'val':'0,2'})

print ("Is bound: %s" % form.is_bound)
print ("Form valid %s" % form.is_valid())
print("Errors in val: %s" % form['val'].errors)

调用 ./test_form.py 产生:

./test_form.py

True
Separator: .
Language: de-de
Is bound: True
Form valid True
Errors in val:

在 django shell 中做同样的事情: python manage.py shell

In [1]: import my_form as mf

In [2]: form=mf.MyForm({'val':'0,2'})
True
Separator: .
Language: de-de

In [3]: form.is_valid()
Out[3]: False

In [4]: form['val'].errors
Out[4]: [u'Enter a number.']

总结一下:如果我启动 django shell(在我的电脑上使用 ipython),语言环境不知何故不起作用。在脚本中执行完全相同的操作非常有效。你能解释一下这种行为吗?

最佳答案

Django 管理命令(包括 shell)将语言重置为 'en-us',因此出现了您的问题。此行为的解释在 the Django Documentation 中。 :

By default, the BaseCommand.execute() method sets the hardcoded ‘en-us’ locale because some commands shipped with Django perform several tasks (for example, user-facing content rendering and database population) that require a system-neutral string language (for which we use ‘en-us’).

如果您激活了正确的语言,您的示例就可以在 shell 中运行:

>>> from django.utils.translation import get_language
>>> get_language()
> 'en-us'
>>> import my_form as mf
>>> form=mf.MyForm({'val':'0,2'})
True
Separator: .
Language: de-de
>>> form.is_valid()
> False
>>> from django.utils.translation import activate
>>> activate('de-de')
>>> get_language()
> 'de-de'
>>> form=mf.MyForm({'val':'0,2'})
True
Separator: .
Language: de-de
>>> form.is_valid()
> True

附带说明一下,您应该始终使用 get_locale() 检查当前语言,而不是依赖于 settings

关于python django shell(ipython)意外行为或错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16243031/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com