I am using Django translation for the first time, Please help me to fix the issue. According to the Django doc for translation
Using translations outside views and templates I have tried below code on shell but unfortunately thats not working:
>>> from django.utils import translation
>>> def welcome_translated(language):
cur_language = translation.get_language()
try:
translation.activate(language)
text = translation.gettext('welcome')
finally:
translation.activate(cur_language)
return text
>>> translation.get_language()
'en'
>>> welcome_translated('fa-ir')
'welcome'
Related
I am having trouble uploading excel file to my django application. It is a very simple application that should allow a user to upload an excel file with 3 columns. The application will read the contents of this file and process it into bunch of calculations
here is my forms.py:
class InputForm(forms.Form):
FileLocation = forms.FileField(label='Import Data',required=True,widget=forms.FileInput(attrs={'accept': ".xlsx"}))
settings.py:
FILE_UPLOAD_HANDLERS = ["django_excel.ExcelMemoryFileUploadHandler",
"django_excel.TemporaryExcelFileUploadHandler"]
views.py:
import xlrd
from django.shortcuts import render_to_response, render
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.template.context_processors import csrf
from io import TextIOWrapper
from WebApp.forms import *
from django.core.mail import send_mail
from django.utils.safestring import mark_safe
from django.db import connection
import os
import csv
def analyze(request):
if request.method == 'POST':
form = InputForm(request.POST,request.FILES['FileLocation'])
if form.is_valid():
book = xlrd.open_workbook(request.FILES('FileLocation'))
for sheet in book.sheets():
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
print(number_of_rows)
I upload the file in the form and it gives me an error:
AttributeError at /app/analyze/
'ExcelInMemoryUploadedFile' object has no attribute 'get'
Request Method: POST
Request URL: http://127.0.0.1:8000/data/analyze/
Django Version: 1.11
Exception Type: AttributeError
Exception Value:
Exception Location: C:\Python36\lib\site-packages\django\forms\widgets.py in value_from_datadict, line 367
Python Executable: C:\Python36\python.exe
Python Version: 3.6.4
I am also able to upload a .csv file successfully using the following views.py code:
def analyze(request):
c={}
context = RequestContext(request)
c.update(csrf(request))
abc=['a','b','c']
if request.method == 'POST':
form = InputForm(request.POST,request.FILES)
dataType = request.POST.get("DataType")
print(dataType)
if form.is_valid():
cd = form.cleaned_data #print (cd)
a = TextIOWrapper(request.FILES['FileLocation'].file,encoding='ascii',errors='replace')
#print (request.FILES.keys())
data = csv.reader(a)
row1csv = next(data)
region = row1csv[0]
metric = row1csv[2]
I have tried django-excel with same error.
You're correctly initialising your form for the .CSV case but not in your Excel case:
form = InputForm(request.POST, request.FILES)
Don't initialise using request.FILES['FileLocation'] as that's passing the wrong type to the form. It's expecting a MultiValueDict of uploaded files, not a single uploaded file. That's why it fails when calling get on it.
Next, you can't pass an ExcelInMemoryUploadedFile to xlrd.get_workbook(). You need to save the file to disk first, then pass it's path to the get_workbook() method. The documentation of django-excel gives some easier methods:
book = request.FILES['FileLocation'].get_book() # note the square brackets!
or to directly access a sheet:
sheet = request.FILES['FileLocation'].get_sheet('sheet1')
I am working on a Django project which is localized and works fine in many languages. Now for a reason I need to call ugettext from its shell.
Here is what I did:
>>> from django.conf import settings
>>> settings.LANGUAGE_CODE
u'fa-ir'
>>> from django.utils.translation import ugettext as _
>>> print _("Schedule & Details")
Schedule & Details
As you see the phrase "Schedule & Details" did not print in Persian language.
Is it possible to translate a phrase and then print it inside Django shell?
Django's normal translation feature depends on django.middleware.locale.LocaleMiddleware, but middleware runs as part of the request / response cycle. Since you are in an interactive shell and there is no request object the middleware can't do its job.
If you manually activate the language in your shell you should see translation behaving as expected:
>>> from django.utils.translation import activate, ugettext as _
>>>
>>> activate('fa-ir')
>>> print _("Schedule & Details")
Of course, instead of hard-coding 'fa-ir' you could load it from settings.LANGUAGE_CODE if you wish.
I am trying to use timesince from django but I want it shows "semana" instead of "week", as far as I knew we just need to set 2 things in settings and it should work
>>> from django.conf import settings
>>> settings.USE_I18N
True
>>> settings.LANGUAGE_CODE
'pt-br'
>>> timesince(datetime.now() - timedelta(days=7))
u'1 week'
What is wrong here?
More information: I am on Ubuntu 16 and I have a Mac where the code works
Try the following, see if there is any difference
from django.utils import translation
translation.activate('pt-br')
print timesince(datetime.now() - timedelta(days=7))
I am writing some tests which use the python unittest package (Python 2.7)
and I heavily rely on the xmlrunner.XMLTestRunner to dump the XML test output
Unfortunately, I fail to find some basic example which describes how one can pass some command line options to the test class to parametrise some of the tests.
Does someone have some hint on how I could achieve this (using xmlrunner)?
In addition, here is what I try to achieve:
I define my tests in a set of classes in the following myunittest.py file:
import unittest
class TestOne(unittest.TestCase):
def __init__(self, options=None):
unittest.TestCase.__init__(self)
self.__options = options
def A(self):
print self.__options.configXML # try to print the parameter
self.assertEqual(1, 1)
and call it from the main.py which looks like:
from optparse import OptionParser
import unittest
import xmlrunner
from uitest import *
def runit(opt):
suite = unittest.TestSuite()
suite.addTest(TestOne(options=opt))
testrunner = xmlrunner.XMLTestRunner(output='tests', descriptions=True)
unittest.main(testRunner=testrunner).run(suite)
if __name__ == "__main__":
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-c", "--configXML", dest="configXML", help="xml file")
options = parser.parse_args()
runit(opt=options)
Many thanks for your valuable help.
after several hours trying to figure it out, I came to this solution, which makes my day. I post it here, in case someone comes to the same issue.
The main drawback is that it seems I need to have everything in the same python file. and I run it like:
python test.py --xmlConfig=configFile.xml --xmlRunner
with test.py:
import unittest
import sys
from optparse import OptionParser
import xmlrunner
class MyTests(unittest.TestCase):
def testFirstThing(self):
xmlConfig=options.xmlConfig
self.assertEqual(xmlConfig,"configFile.xml")
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("--xmlRunner", "--xmlRunner", help="perform a unittest and generate XML", dest="xmlRunner", default=False, action='store_true')
parser.add_option("--xmlConfig", "--xmlConfig", type="string", help="configuration file", dest="xmlConfig", default="config.xml")
options, arguments = parser.parse_args()
if options.xmlRunner:
del sys.argv[1:]
unittest.main(testRunner=xmlrunner.XMLTestRunner(output='./xml'))
I am starting to write tests for a Django app, which relies on several environment variables. When I am testing it in the shell, I can import os and specify the variables and my tests work just fine. However, when I put them into tests.py, I still get a key error because those variables are not found. here's what my test looks like:
from django.utils import unittest
from django.test.utils import setup_test_environment
from django.test.client import Client
import os
os.environ['a'] = 'a'
os.environ['b'] = 'b'
class ViewTests(unittest.TestCase):
def setUp(self):
setup_test_environment()
def test_login_returning_right_template(self):
""" get / should return login.html template """
c = Client()
resp = c.get('/')
self.assertEqual(resp.templates[0].name, 'login.html')
Is this the wrong place to initialize those variables? I tried to do it on setUp, but with the same result - they are not found. Any suggestions on how to initialize environment variables before running a test suite?
Thanks!
Luka
You should not relay on os.envior in your views. If you have to, do It in your settings.py
MY_CUSTOM_SETTING = os.environ.get('a', 'default_value')
And in views use settings variable:
from django.conf.settings import MY_CUSTOM_SETTING
print MY_CUSTOM_SETTING
Then in your test you can set this setting:
from django.test import TestCase
class MyTestCase(TestCase):
def test_something(self):
with self.settings(MY_CUSTOM_SETTING='a'):
c = Client()
resp = c.get('/')
self.assertEqual(resp.templates[0].name, 'login.html')