Image don't shown in Django LFS - django

I've added image to product, but it not shown in product preview. Error message appears: "The request content cannot be loaded. Please try again later".
Web-page is located in localhost, DB is in UTF8_general_ci (MySQL), Django 1.8, Python 2.7.
Also when I try to open an attachement (i've put image there), I recieve an error, traceback il below that post:
Environment:
Request Method: GET
Request URL: http://localhost:8000/media/files/book1.png
Django Version: 1.8
Python Version: 2.7.6
Installed Applications:
('lfs_theme',
'compressor',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.flatpages',
'django.contrib.redirects',
'django.contrib.sitemaps',
'django_countries',
'pagination',
'reviews',
'portlets',
'lfs.addresses',
'lfs.caching',
'lfs.cart',
'lfs.catalog',
'lfs.checkout',
'lfs.core',
'lfs.criteria',
'lfs.customer',
'lfs.customer_tax',
'lfs.discounts',
'lfs.export',
'lfs.gross_price',
'lfs.mail',
'lfs.manage',
'lfs.marketing',
'lfs.manufacturer',
'lfs.net_price',
'lfs.order',
'lfs.page',
'lfs.payment',
'lfs.portlet',
'lfs.search',
'lfs.shipping',
'lfs.supplier',
'lfs.tax',
'lfs.tests',
'lfs.utils',
'lfs.voucher',
'lfs_contact',
'lfs_order_numbers',
'localflavor',
'postal',
'paypal.standard.ipn',
'paypal.standard.pdt')
Installed Middleware:
('django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
'pagination.middleware.PaginationMiddleware')
Traceback:
File "/home/stp/Рабочий стол/lfs-installer/eggs/Django-1.8-py2.7.egg/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/stp/Рабочий стол/lfs-installer/eggs/Django-1.8-py2.7.egg/django/views/static.py" in serve
54. fullpath = os.path.join(document_root, newpath)
File "/usr/lib/python2.7/posixpath.py" in join
80. path += '/' + b
Exception Type: UnicodeDecodeError at /media/files/book1.png
Exception Value: 'ascii' codec can't decode byte 0xd0 in position 10: ordinal not in range(128)

Your problem is that media root path contains non-ASCII characters, such as "Рабочий стол".
Posible solutions:
Move your project to ASCII-only (non-Cyrillic in your case) path
Use Python3 instead 2, which not have this Unicode problems
Change MEDIA_ROOT setting to Unicode string, e.g. u'/home/stp/Рабочий стол/myproject/media/'

To get image and override ANSII encoding I've done following:
Added string # -*- coding: utf-8 -*- at the beginning of the
settings.py in my LFS;
As Mr. Tikhonov said, changed MEDIA_ROOT string
After that images started to load normally.

Related

How to fix "django.contrib.gis.geoip2 has no attribute GeoIP2"

I am trying to retrieve my visitors' location.
After successfully retrieving the IP Adress I want to use
the GeoIP2 object to get information about the location.
https://docs.djangoproject.com/en/2.2/ref/contrib/gis/geoip2/#django.contrib.gis.geoip2.GeoIP2
In my settings.py file I added 'django.contrib.gis.geoip2' to my installed apps:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis.geoip2',
'web'
]
Using the shell everything works perfect [python3 manage.py shell]:
dir(django.contrib.gis.geoip2)
['GeoIP2', 'GeoIP2Exception', 'HAS_GEOIP2', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'base', 'geoip2', 'resources']
However trying to use the GeoIP2 object in my application 'web' I get the error: "django.contrib.gis.geoip2 has no attribute GeoIP2".
['HAS_GEOIP2', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
There is a dependency mentioned in the documentation you link to, which you are missing on your web server:
In order to perform IP-based geolocation, the GeoIP2 object requires the geoip2 Python library
You need to install this with pip install geoip2.
Note that the documentation also mentions other requirements which you also need to set in order to use this module.

ModuleNotFoundError: No module named 'django_tables2'

I am trying to use Django-tables2, but my project can't find this module.
Firstly, I installed it without a problem.
(acct) C:\Users\tsjee_000\dev\acct\src>pip install django-tables2
Requirement already satisfied: django-tables2 in c:\users\tsjee_000\dev\acct\lib\site-packages
Requirement already satisfied: Django>=1.11 in c:\users\tsjee_000\dev\acct\lib\site-packages (from django-tables2)
Requirement already satisfied: pytz in c:\users\tsjee_000\dev\acct\lib\site-packages (from Django>=1.11->django-tables2)
Secondly, I added this to 'INSTALLED_APPS' in settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_tables2',
'clients',
'companies',
'report',
]
Thirdly, views.py and html templates are updated according to the tutorial.
But when I run my project it doesn't work because of the error,
ModuleNotFoundError: No module named 'django_tables2'
I think this error happens in settings.py.
FYR, 'django_tables2'module can be imported correctly in the shell mode.
Assuming it has been installed correctly, are you sure you have activated your virtualenv? The supplied output above indicates you are using a virtualenv called acct.
Try
pip install django_tables2

django problems with i18n Python 3

We are writing a complex website with i18n.
To make translation easier we hold the translations in models.
Our staff writes and edits the translations via django-admin.
When the translation is completed a management script is started which writes the po-files and executes afterwards djangos compilemessages for all of them.
I know, the po-files have to be writen using utf-8.
But after opening the app I still get the error "'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)" when using languages with special characters like spanish or frensh.
What am I doing wrong?
Here is my (shortened) code:
class Command(NoArgsCommand):
def handle_noargs(self, **options):
languages = XLanguage.objects.all()
currPath = os.getcwd()
for lang in languages:
path = "{}/framework/locale/{}/LC_MESSAGES/".format(currPath, lang.langToplevel)
# check and create path
create_path(path)
# add filename
path = path + "django.po"
with codecs.open(path, "w", encoding='utf-8') as file:
# select all textitems for this language from XTranslation
translation = XTranslation.objects.filter(langID=lang)
for item in translation:
# check if menu-item
if item.textID.templateID:
msgid = u"menu_{}_label".format(item.textID.templateID.id)
else:
msgid = u"{}".format (item.textID.text_id)
trans = u"{}".format (item.textTranslate)
text = u'msgid "{}" msgstr "{}"\n'.format(msgid, trans)
file.write(text)
file.close()
Traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.7
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'simple_history',
'datetimewidget',
'payroll',
'framework',
'portal',
'pool',
'billing')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'simple_history.middleware.HistoryRequestMiddleware')
Traceback:
File "c:\python34\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\python\sarlex\framework\views.py" in init
34. activate("de")
File "c:\python34\lib\site-packages\django\utils\translation\__init__.py" in activate
145. return _trans.activate(language)
File "c:\python34\lib\site-packages\django\utils\translation\trans_real.py" in activate
225. _active.value = translation(language)
File "c:\python34\lib\site-packages\django\utils\translation\trans_real.py" in translation
210. current_translation = _fetch(language, fallback=default_translation)
File "c:\python34\lib\site-packages\django\utils\translation\trans_real.py" in _fetch
195. res = _merge(apppath)
File "c:\python34\lib\site-packages\django\utils\translation\trans_real.py" in _merge
177. t = _translation(path)
File "c:\python34\lib\site-packages\django\utils\translation\trans_real.py" in _translation
159. t = gettext_module.translation('django', path, [loc], DjangoTranslation)
File "c:\python34\lib\gettext.py" in translation
410. t = _translations.setdefault(key, class_(fp))
File "c:\python34\lib\site-packages\django\utils\translation\trans_real.py" in __init__
107. gettext_module.GNUTranslations.__init__(self, *args, **kw)
File "c:\python34\lib\gettext.py" in __init__
160. self._parse(fp)
File "c:\python34\lib\gettext.py" in _parse
300. catalog[str(msg, charset)] = str(tmsg, charset)
Exception Type: UnicodeDecodeError at /
Exception Value: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)
Whenever you have an encoding/decoding error, it means you are handling Unicode incorrectly. This is most often when you mix Unicode with byte strings, which will prompt Python 2.x to implicitly decode your byte strings to Unicode with the default encoding, 'ascii', which is why you get errors like these:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)
The best way to avoid these errors is to work with ONLY Unicode within your program, i.e. you have to explicitly decode all input byte strings to Unicode with 'utf-8' (or another Unicode encoding of your choice), and mark the strings in your code as type Unicode with the prefix u''. When you write out to file, explicitly, encode these back to byte string with 'utf-8'.
Specifically to your code, my guess is either
msgid = "menu_{}_label".format(item.textID.templateID.id)
or
text = 'msgid "{}" msgstr "{}"\n'.format(msgid, item.textTranslate)
is throwing the error. Try making msgid and text Unicode strings instead of byte strings by declaring them like so:
msgid = u"menu_{}_label".format(item.textID.templateID.id)
and
text = u'msgid "{}" msgstr "{}"\n'.format(msgid, item.textTranslate)
I'm assuming that the values of item.textID.templateID.id and item.textTranslate are both in Unicode. If they aren't (i.e. they are byte strings), you'd have to decode them first.
Lastly, this is a very good presentation on how to handle Unicode in Python: http://nedbatchelder.com/text/unipain.html. I highly recommend you go thru it if you do a lot of i18n work.
EDIT 1: since item.textID.templateID.id and item.textTranslate are byte strings, your code should be:
for item in translation:
# check if menu-item
if item.textID.templateID:
msgid = u"menu_{}_label".format(item.textID.templateID.id.decode('utf-8'))
else:
msgid = item.textID.text_id.decode('utf-8') # you don't need to do u"{}".format() here since there's only one replacement field
trans = item.textTranslate.decode('utf-8') # same here, no need for u"{}".format()
text = u'msgid "{}" msgstr "{}"\n'.format(msgid, trans) # msgid and trans should both be Unicode at this point
file.write(text)
EDIT 2: Original code was in Python 3.x, so all of the above is NOT applicable.
I had the same error and this helped me https://stackoverflow.com/a/23278373/2571607
Basically, for me, it's an issue with python. My solution is, open C:\Python27\Lib\mimetypes.py
replace
‘default_encoding = sys.getdefaultencoding()’
with
if sys.getdefaultencoding() != 'gbk':
reload(sys)
sys.setdefaultencoding('gbk')
default_encoding = sys.getdefaultencoding()
Soluction found!
I was writing msgid and msgstr in one line separated with space to make it more readable.
This works in english but throws an error in languages with special characters like spanish or frensh.
After writing msgid and msgstr in 2 lines it works.

Interpreting Django Traceback

I'm getting the following message. I somewhat understand that my project server cannot find the templates. However, I have no idea exactly what it's complaining about the templates. Would be great to hear alternate explanations of what's happening.
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/1/
Django Version: 1.4
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
'django.contrib.admin')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
/home/stanley/mytemplates/polls/detail.html, polls/poll_detail.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
/usr/local/lib/python2.7/dist-packages/django/contrib/auth/templates/polls/detail.html, polls/poll_detail.html (File does not exist)
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/polls/detail.html, polls/poll_detail.html (File does not exist)
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
136. response = response.render()
File "/usr/local/lib/python2.7/dist-packages/django/template/response.py" in render
104. self._set_content(self.rendered_content)
File "/usr/local/lib/python2.7/dist-packages/django/template/response.py" in rendered_content
79. template = self.resolve_template(self.template_name)
File "/usr/local/lib/python2.7/dist-packages/django/template/response.py" in resolve_template
55. return loader.select_template(template)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in select_template
193. raise TemplateDoesNotExist(', '.join(not_found))
Exception Type: TemplateDoesNotExist at /polls/1/
Exception Value: polls/detail.html, polls/poll_detail.html
I'll try to answer this in a bit more depth, especially to react to your statement "I think i got the templates in the wrong place." This can be easily solved using the traceback you posted.
First thing it tells you is some stuff about your environment - you can simply ignore this. This is not usefull for a TemplateLoaderError. It can be important though if any of your apps requires a special version of Python or something the like.
Next thing to spot is what kind of error has ocurred, and this one is extremely helpfull for your special case:
Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
/home/stanley/mytemplates/polls/detail.html, polls/poll_detail.html (File does not exist)
If you take a closer look at this one, it tells you exactly where Django tried to find the specified templates, and what happened while it was looking for them (File does not exist). This will help you to find a solution to check if you really got your templates in the wrong place (which will happen quite often, even to a bit more experienced Django developers).
The next part is the traceback. You can savely ignore it in your case, because there is no file involved that is located in your project folder. If it was, that would mean you possibly screwed up something in the named file, and Django even tells you in which line your code did (possibly) provoke the exception.
Last part is information about the exception that has been raised, in your case TemplateDoesNotExist. Django has some special exceptions that you can find here . Other than these Django raises the standard Python exceptions.
Hope i didn't tell you too much you allready knew.
Do you have something like this in your settings?
PROJECT_ROOT = path.dirname(path.abspath(__file__)) #gets directory settings is in
TEMPLATE_DIRS = (
PROJECT_ROOT+'/templates',
)
You might have specified some path in your TEMPLATE_DIRS tuple in settings.py file.Django searches the html templates only in those directories.So add the following path to your TEMPLATE_DIRS.
TEMPLATE_DIRS = ('/polls',)

non-consistent django error

I'm running django on Dreamhost right now with fastcgi, and I'm getting really weird behavior. First, the server runs Python 2.3. On my computer, I'm running 2.6 and all my source code works. When I put it on my host though, nothing works. Right now, when I pkill python and then load a page, the first error complains about a syntax error at 'class Item_list()' line:
from dtms.models import *
class Item_list():
def __init__(self, list = None, house_id = None):
self.list = list
self.house_id = house_id
def ret_list(self):
return self.list
Then, if I reload it again without changing anything, I get this error:
Django Version: 1.1 alpha 1 SVN-10114
Python Version: 2.3.5
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mysite.dtms']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Traceback:
File "/home/victor/django/django_src/django/core/handlers/base.py" in get_response
82. callback, callback_args, callback_kwargs = resolver.resolve(
File "/home/victor/django/django_src/django/core/urlresolvers.py" in resolve
184. for pattern in self.url_patterns:
File "/home/victor/django/django_src/django/core/urlresolvers.py" in _get_url_patterns
212. raise ImproperlyConfigured("The included urlconf %s doesn't have any"
Exception Type: ImproperlyConfigured at /dtms/login/
Exception Value: The included urlconf mysite.urls doesn't have anypatterns in it
Any ideas?
class Item_list():
You can't include an empty inheritance list in Python 2.3. There seems to have been a change in the grammar that allows it now but not then.
It would normally be written:
class Item_list:
if you don't want any base classes. But generally these days you'd want to derive from object to get new-style classes.
I don't know much about your deployment environment, but in general when you've tried to import something and got an exception, it can leave behind partially-initialised modules in sys.modules that will frustrate future attempts to import them, resulting in otherwise inexplicable errors where properties and actions of the module are not where they were expected.
In general once an import has failed you should consider the environment lost and start again, but I don't know how your Django deployment copes with errors like that and process-restarting issues. Maybe the original error has left an interpreter running without having written the expected stuff to url_patterns, or something.