python django shell(ipython)意外的行为还是bug? [英] python django shell (ipython) unexpected behavior or bug?

查看:144
本文介绍了python django shell(ipython)意外的行为还是bug?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用区域设置时,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 / model.py:

 从django.db导入模型

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



$ d




$ b从django.conf导入设置
从local_forms.models导入MyModel


类MyForm(forms.ModelForm):
val = forms.Decima
超级(MyForm,self).__ init __(* args,** kwargs)$ b $($ args,** kwargs)
b self.fields ['val']。localize = True
如果__debug__:
print self.fields ['val']。localize
print(Separator:+ settings.DECIMAL_SEPARATOR)
print(Language:+ settings.LANGUAGE_CODE)

class Meta:
model = MyModel

test_form.py:

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

如果__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(Val:%s%form ['val']。errors)

调用./test_form.py产生:

  ./ test_form.py 

True
分隔符:。
语言:de-de
绑定:True
表单有效True
val中的错误:

在django shell中执行相同的操作:
python manage.py shell

 在[1]中:将my_form导入为mf 

在[2]中:form = mf.MyForm({'val':'0,2'})
True
分离器:。
语言:de-de

在[3]中:form.is_valid()
Out [3]:False

在[4]中:形式['val']。错误
输出[4]:[u'Enter a number。']

总结一下:如果我启动django shell(在我的电脑上使用ipython),这个区域设置不行。在脚本中完全一样的工作完美。
你能解释一下这个行为吗?

解决方案

Django管理命令包括 shell ,将语言重置为'en-us',因此您的问题。对此行为的解释是 Django文档


默认情况下,BaseCommand.execute()方法设置硬编码的en-us区域设置,因为有些Django附带的命令执行需要系统中性字符串语言的几个任务(例如,面向用户的内容呈现和数据库)(对于我们使用'en-us')。


如果您激活正确的语言,您的示例在shell中工作:

 >>> from django.utils.translation import get_language 
>>> get_language()
> 'en-us'
>>>将my_form导入为mf
>>> form = mf.MyForm({'val':'0,2'})
True
分隔符:。
语言:de-de
>>> form.is_valid()
> False
>>>>来自django.utils.translation import activate
>>> activate('de-de')
>>> get_language()
> 'de-de'
>>> form = mf.MyForm({'val':'0,2'})
True
分隔符:。
语言:de-de
>>> form.is_valid()
> True

在旁注中,您应该始终使用 get_locale检查当前语言()而不是依赖设置


Django shell behaves (at least for me) unexpected when working with locale settings. Form validation of a comma separated decimal field works when calling from external script and fails on calling from django shell (ipython).

Starting a new Project I got the following files:

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)

my_form.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

test_form.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)

Calling ./test_form.py yields:

./test_form.py

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

Doing the same thing in 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.']

To sum up: If i start the django shell (which on my pc uses ipython) the locale somehow does not work. Doing exactly the same in a script works perfectly. Can you please explain this behavior?

解决方案

The Django management commands, including shell, reset the language to 'en-us', hence your issue. The explanation of this behaviour is in 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’).

Your example does work in the shell if you activate the proper language:

>>> 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

On a side note, you should always check the current language using get_locale() instead of relying on settings.

这篇关于python django shell(ipython)意外的行为还是bug?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆