Django - ValueError: plural forms expression could be dangerous - python

I'm working with Django 1.9 in Microsoft Visual Studio. Also I'm using a virtual env, where all the needed python packages are installed. When I try to compile messages in order to add translation function to the site, the following error is raised:
ValueError: plural forms expression could be dangerous
Update 1. Stacktrace:
Internal Server Error: /
Traceback (most recent call last):
File "C:\path-to-project\env\lib\site-packages\django\core\handlers\base.py", line 123, in get_response
response = middleware_method(request)
File "C:\path-to-project\env\lib\site-packages\django\middleware\locale.py", line 26, in process_request
translation.activate(language)
File "C:\path-to-project\env\lib\site-packages\django\utils\translation\__init__.py", line 154, in activate
return _trans.activate(language)
File "C:\path-to-project\env\lib\site-packages\django\utils\translation\trans_real.py", line 216, in activate
_active.value = translation(language)
File "C:\path-to-project\env\lib\site-packages\django\utils\translation\trans_real.py", line 205, in translation
_translations[language] = DjangoTranslation(language)
File "C:\path-to-project\env\lib\site-packages\django\utils\translation\trans_real.py", line 114, in __init__
self._add_installed_apps_translations()
File "C:\path-to-project\env\lib\site-packages\django\utils\translation\trans_real.py", line 160, in _add_installed_apps_translations
translation = self._new_gnu_trans(localedir)
File "C:\path-to-project\env\lib\site-packages\django\utils\translation\trans_real.py", line 140, in _new_gnu_trans
fallback=use_null_fallback)
File "C:\Python27\Lib\gettext.py", line 481, in translation
t = _translations.setdefault(key, class_(fp))
File "C:\Python27\Lib\gettext.py", line 182, in __init__
self._parse(fp)
File "C:\Python27\Lib\gettext.py", line 318, in _parse
self.plural = c2py(plural)
File "C:\Python27\Lib\gettext.py", line 95, in c2py
raise ValueError, 'plural forms expression could be dangerous'
ValueError: plural forms expression could be dangerous
I've read about that (plural forms expression could be dangerous and Django: gettext raises ValueError: 'plural forms expression could be dangerous'), but the only solution I found is to remove lines referred to plural translations, for example:
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
If I remove those lines in my translations files, it still raises the same error, because it takes into account other files located at the virtual env.
Update 2: If I run the server from the command line, using
python manage.py runserver
there's no problem, everything is going right. However, when I run the project from Visual Studio, the error is raised.
Is there any way to solve this problem?
Thanks in advance.

Related

Django/cookiecutter-django Error: "AttributeError: 'Path' object has no attribute 'endswith''" with manage.py makemigrations

I have been trying to set up Django with a cookiecutter-django project
with cookiecutter https://github.com/pydanny/cookiecutter-django.git
and I get this error output when I run ./manage.py makemigrations at the end.
My python version in the virturalenv is Python 3.5.2
This is the tail of console output and not from a file.
Stack overflow doesn't allow me to post all of the long error output without more of other text.
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/site-packages/django/db/models/base.py", line 156, in __new__
new_class.add_to_class(obj_name, obj)
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/site-packages/django/db/models/base.py", line 321, in add_to_class
value.contribute_to_class(cls, name)
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/site-packages/django/db/models/fields/related.py", line 1588, in contribute_to_class
self.remote_field.through = create_many_to_many_intermediary_model(self, cls)
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/site-packages/django/db/models/fields/related.py", line 1057, in create_many_to_many_intermediary_model
'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to},
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/site-packages/django/utils/functional.py", line 192, in __mod__
return str(self) % rhs
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/site-packages/django/utils/functional.py", line 156, in __text_cast
return func(*self.__args, **self.__kw)
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/site-packages/django/utils/translation/__init__.py", line 79, in gettext
return _trans.gettext(message)
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/site-packages/django/utils/translation/trans_real.py", line 285, in gettext
_default = _default or translation(settings.LANGUAGE_CODE)
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/site-packages/django/utils/translation/trans_real.py", line 198, in translation
_translations[language] = DjangoTranslation(language)
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/site-packages/django/utils/translation/trans_real.py", line 99, in __init__
self._add_local_translations()
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/site-packages/django/utils/translation/trans_real.py", line 151, in _add_local_translations
translation = self._new_gnu_trans(localedir)
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/site-packages/django/utils/translation/trans_real.py", line 123, in _new_gnu_trans
fallback=use_null_fallback,
File "/usr/lib/python3.5/gettext.py", line 428, in translation
mofiles = find(domain, localedir, languages, all=True)
File "/usr/lib/python3.5/gettext.py", line 396, in find
mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
File "/root/painlesslanguage/painlesslanguageenv/lib/python3.5/posixpath.py", line 84, in join
elif not path or path.endswith(sep):
AttributeError: 'Path' object has no attribute 'endswith'
I left the TIME_ZONE cookiecutter-django setup option blank if that matters.
this seems to be a difficult error to fix or even debug.
some users have gotten this error when they have not included the static url properly in settings.py of left a trailing comma in the INSTALLED_APPS declaration.
however i got this error just when i switched a python version.
I ended up somehow solving it (at the time) by reinstalling python and relinking pyenv python to brew.
however, now its returned. there must be a way to debug this.
all the stacktrace points to files in the python install or only to the settings file. but if your settings file looks fine, its really hard to know how to fix it. After checking your settings.py INSTALLED_APPS (to check there are no trailing commas) id suggest reinstalling python and see if that helps.
if that doesnt work, then what helped me was printing out the apps being installed. to do this you will have to add print lines into the python/django code where the errors are thrown. as by default this info isnt being sent to the application layer, though it should be. these will be removed if you ever change the py install again. so its kind of a temperoray/local way to help u debug. really the framework should send the name info if it fails to import an app. by adding these lines i found what was going wrong with my import.

Issue while installing pip python

i installed python 3.7.2 still pip was not installed,for pip there must be pip.exe in folder script in directory where python is installed but in my device there nothing in it.
later i tried to install it by running get-pip.py but it throws an exception in command prompt
Command prompt throws exception :-
Installing collected packages: pip, setuptools, wheel Exception: Traceback (most recent call last):
File "C:\Users\Del$in\AppData\Local\Programs\Python\Python37\lib\distutils\uti l.py", line 187, in subst_vars return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
File "C:\Users\Del$in\AppData\Local\Programs\Python\Python37\lib\re.py", line 192, in sub return _compile(pattern, flags).sub(repl, string, count)
File "C:\Users\Del$in\AppData\Local\Programs\Python\Python37\lib\distutils\uti l.py", line 184, in _subst return os.environ[var_name]
File "C:\Users\Del$in\AppData\Local\Programs\Python\Python37\lib\os.py", line 678, in getitem raise KeyError(key) from None KeyError: 'in'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Del$in\AppData\Local\Temp\tmpwzho1r2w\pip.zip\pip_internal\cli \base_command.py", line 179, in main status = self.run(options, args)
File "C:\Users\Del$in\AppData\Local\Temp\tmpwzho1r2w\pip.zip\pip_internal\com mands\install.py", line 393, in run use_user_site=options.use_user_site,
File "C:\Users\Del$in\AppData\Local\Temp\tmpwzho1r2w\pip.zip\pip_internal\req __init__.py", line 57, in install_given_reqs **kwargs
File "C:\Users\Del$in\AppData\Local\Temp\tmpwzho1r2w\pip.zip\pip_internal\req \req_install.py", line 913, in install use_user_site=use_user_site, pycompile=pycompile,
File "C:\Users\Del$in\AppData\Local\Temp\tmpwzho1r2w\pip.zip\pip_internal\req \req_install.py", line 445, in move_wheel_files warn_script_location=warn_script_location,
File "C:\Users\Del$in\AppData\Local\Temp\tmpwzho1r2w\pip.zip\pip_internal\whe el.py", line 320, in move_wheel_files prefix=prefix,
File "C:\Users\Del$in\AppData\Local\Temp\tmpwzho1r2w\pip.zip\pip_internal\loc ations.py", line 180, in distutils_scheme i.finalize_options()
File "C:\Users\Del$in\AppData\Local\Programs\Python\Python37\lib\distutils\com mand\install.py", line 307, in finalize_options self.expand_basedirs()
File "C:\Users\Del$in\AppData\Local\Programs\Python\Python37\lib\distutils\com mand\install.py", line 475, in expand_basedirs self._expand_attrs(['install_base', 'install_platbase', 'root'])
File "C:\Users\Del$in\AppData\Local\Programs\Python\Python37\lib\distutils\com mand\install.py", line 469, in _expand_attrs val = subst_vars(val, self.config_vars)
File "C:\Users\Del$in\AppData\Local\Programs\Python\Python37\lib\distutils\uti l.py", line 189, in subst_vars raise ValueError("invalid variable '$%s'" % var) ValueError: invalid variable '$'in''
I'm certain that your username is the reason for this error. Python is trying to create a string of your username but the $ is causing issues. You can see this in the line ValueError: invalid variable '$'in''. Although there are other solutions, changing your username to DelSin will prevent many other headaches too.
From the code in distutils/utils.py:
def subst_vars (s, local_vars):
"""Perform shell/Perl-style variable substitution on 'string'. Every
occurrence of '$' followed by a name is considered a variable, and
variable is substituted by the value found in the 'local_vars'
dictionary, or in 'os.environ' if it's not in 'local_vars'.
'os.environ' is first checked/augmented to guarantee that it contains
certain values: see 'check_environ()'. Raise ValueError for any
variables not found in either 'local_vars' or 'os.environ'.
"""
This is utilizing the utility that's quite common in bash/Perl scripting, where you can substitute in a value using $:
SOMEPATH='$HOME/somefolder'
echo($SOMEPATH)
# '/path/to/somefolder'
Your username, unfortunately, mimics this and will cause problems until it is changed

How to fix "plural forms could be dangerous" django error?

I don't get it. If I set the Accept-Language header to anything other than "en" (de, pl, es) or even something that doesn't exist (like xxs), the app doesn't spit out this error, but it does when I set it to "en". It happens only on windows (newest gettext tools). Here's the stack trace:
Traceback (most recent call last):
File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\core\han
dlers\exception.py", line 39, in inner
response = get_response(request)
File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\core\han
dlers\base.py", line 244, in _legacy_get_response
response = middleware_method(request)
File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\middlewa
re\locale.py", line 29, in process_request
translation.activate(language)
File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\utils\tr
anslation\__init__.py", line 161, in activate
return _trans.activate(language)
File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\utils\tr
anslation\trans_real.py", line 238, in activate
_active.value = translation(language)
File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\utils\tr
anslation\trans_real.py", line 227, in translation
_translations[language] = DjangoTranslation(language)
File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\utils\tr
anslation\trans_real.py", line 129, in __init__
self._add_installed_apps_translations()
File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\utils\tr
anslation\trans_real.py", line 176, in _add_installed_apps_translations
translation = self._new_gnu_trans(localedir)
File "E:\projekty\python\myapp_api\_env\lib\site-packages\django\utils\tr
anslation\trans_real.py", line 156, in _new_gnu_trans
fallback=use_null_fallback)
File "C:\Python35\lib\gettext.py", line 426, in translation
t = _translations.setdefault(key, class_(fp))
File "C:\Python35\lib\gettext.py", line 162, in __init__
self._parse(fp)
File "C:\Python35\lib\gettext.py", line 297, in _parse
self.plural = c2py(plural)
File "C:\Python35\lib\gettext.py", line 76, in c2py
raise ValueError('plural forms expression could be dangerous')
ValueError: plural forms expression could be dangerous
I have plural-forms set up correctly in my django.po file:
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
Why does this happen and how to fix it?
I found an answer - the reason for that error is my incompetence :). I ran django-admin makemessages command in the root of my project, so next to _env and all the packages inside. This command created language files for a couple of projects with the default django.po file template, so they contained something like plural-forms=INTEGER and other stuff and this was causing the above error.
Here I will give you all the details about Plural-forms:
See this link Plural-forms.It will helps to you.
Note:This just link give a simple idea about plural
It surely helps to others
Your plural expression (n != 1) is most likely considered dangerous because it's too inclusive. n doesn't equal 1 means any value except 1 will evaluate to True including booleans, strings or None.
Try changing your expression to use equals, greater than and less than operations to narrow down the scope of the expression.

ansible unexpected exception no escaped character

I am fairly new to Ansible and to configuration management tools in general. I've been playing around with it for the last two days and for the life of me I can't get past typing out ansible testserver. It comes back with an error message that says Unexpected Exception: No escaped character. The full error message is:
mac-dgarcia:playbooks dgarcia$ ansible testserver -i hosts -m ping -vvv
Using /Users/dgarcia/Documents/Playbooks/ansible.cfg as config file
Unexpected Exception: No escaped character
the full traceback was:
Traceback (most recent call last):
File "/Users/dgarcia/Documents/Playbooks/ansible/bin/ansible", line 79, in <module>
sys.exit(cli.run())
File "/Users/dgarcia/Documents/Playbooks/ansible/lib/ansible/cli/adhoc.py", line 106, in run
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=self.options.inventory)
File "/Users/dgarcia/Documents/Playbooks/ansible/lib/ansible/inventory/__init__.py", line 135, in __init__
self.parser = InventoryParser(filename=host_list)
File "/Users/dgarcia/Documents/Playbooks/ansible/lib/ansible/inventory/ini.py", line 45, in __init__
self._parse()
File "/Users/dgarcia/Documents/Playbooks/ansible/lib/ansible/inventory/ini.py", line 49, in _parse
self._parse_base_groups()
File "/Users/dgarcia/Documents/Playbooks/ansible/lib/ansible/inventory/ini.py", line 107, in _parse_base_groups
tokens = shlex.split(line)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 279, in split
return list(lex)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 269, in next
token = self.get_token()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 96, in get_token
raw = self.read_token()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 191, in read_token
raise ValueError, "No escaped character"
ValueError: No escaped character
Have searched everywhere I can on Google and came back with nothing. Any ideas?
I had the same issue and changing my host file to have only one line fixed the problem.
My host file looks like the following:
testserver ansible_ssh_host=128.0.0.1 ansible_ssh_port=2222 \
ansible_ssh_user=vagrant \
ansible_ssh_private_key_file=/home/bibryam/Desktop/.vagrant/machines/fabric/virtualbox/private_key

How can I fix these errors in Django?

I am a python/django noob and can't get my code to run while trying to learn. Please let me know how I can fix both the below errors I'm getting, thanks.
In my root folder for my new project, I type this on the command line and this is what happens:
python manage.py runserver
Validating models...
>/Users/MyClean/anaconda/lib/python2.7/site-packages/django/utils/hashcompat.py:9: DeprecationWarning: django.utils.hashcompat is deprecated; use hashlib instead
DeprecationWarning)
>Unhandled exception in thread started by <bound method Command.inner_run of <django.core.management.commands.runserver.Command object at 0x101a00c50>>
Traceback (most recent call last):
File "/Users/MyClean/anaconda/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 92, in inner_run
self.validate(display_num_errors=True)
File "/Users/MyClean/anaconda/lib/python2.7/site-packages/django/core/management/base.py", line 280, in validate
num_errors = get_validation_errors(s, app)
File "/Users/MyClean/anaconda/lib/python2.7/site-packages/django/core/management/validation.py", line 35, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/Users/MyClean/anaconda/lib/python2.7/site-packages/django/db/models/loading.py", line 166, in get_app_errors
self._populate()
File "/Users/MyClean/anaconda/lib/python2.7/site-packages/django/db/models/loading.py", line 72, in _populate
self.load_app(app_name, True)
File "/Users/MyClean/anaconda/lib/python2.7/site-packages/django/db/models/loading.py", line 96, in load_app
models = import_module('.models', app_name)
File "/Users/MyClean/anaconda/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Users/MyClean/anaconda/lib/python2.7/site-packages/djangodblog/models.py", line 40, in <module>
class ErrorBase(Model):
File "/Users/MyClean/anaconda/lib/python2.7/site-packages/djangodblog/models.py", line 46, in ErrorBase
url = models.URLField(verify_exists=False, null=True, blank=True)
File "/Users/MyClean/anaconda/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1277, in __init__
CharField.__init__(self, verbose_name, name, **kwargs)
File "/Users/MyClean/anaconda/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 626, in __init__
super(CharField, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'verify_exists''
I have looked at my project's code (it's very basic) and don't see any typos. I'm copying from a book that is 3 years old so I think this is a compatibility issue.
I'm copying from a book that is 3 years old so I think this is a
compatibility issue.
3 years is a very long time.
In django 1.4, the verify_exists option was deprecated (this means it was marked for removal), and in 1.5 it was completely removed.
Since 1.5 is the current version, when you install django this is the version that is installed.
As you are going by a book, try to use the same version of django as the book. Otherwise you'll run into a lot more of these issues.
Or, use a more updated reference. Why not try the official tutorial?

Categories

Resources