User object and session object usage.

2016-06-07 Thread learn django
Hi,

Am trying to write a customized authentication model.
In authenticate function I do the following.

def authenticate(self, username=None, password=None):
try:
# Check if this user is valid on the mail server
s.auth = HttpNtlmAuth(username, password, s)
except:
return None

try:
# Check if the user exists in Django's local database
user = User.objects.get(email=username)
except User.DoesNotExist:
# Create a user in Django's local database
user = User.objects.create_user(time.time(), username, 
'passworddoesntmatter')

return user


When does this user object get deleted eventually ?

Once the user is authenticated am going to associate it with session.
Will this authenticate function get called again and again if multiple 
requests are made in the same session ?

I want to take the logoff functionality out of the client so i will be 
setting expiry in the session.
When the session expires i.e expiry time is 0 or less, i will again 
authenticate the user and reset expiry time.
That way session remains intact. Is there a better approach to this ?

When clearsession is called session object will get deleted from DB, will 
it also trigger deletion of User object ? 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/af631185-ab5e-4dda-bacb-89fdcb2dd88e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Test fails when run in whole test suite - but not stand-alone?

2016-06-08 Thread learn django
Hi Adam,

I was hitting same issue but never got chance to debug it.
If the underneath database support database transactions then isn't that
each test will be treated as a separate transaction and transaction should 
be rolled back
after the test is over to keep the database sane ?

On Wednesday, June 8, 2016 at 1:43:40 AM UTC-7, Derek wrote:
>
> Thanks Adam, I will try that.  I think I have been lax in the use of 
> tearDown.
>
> On Thursday, 2 June 2016 21:47:00 UTC+2, Adam wrote:
>>
>> When I've had that happen before, it's because some previous test changed 
>> something (like a setting value or the site domain) that influenced the 
>> test that failed. To narrow it down, I would run all the tests up to and 
>> including the failed one. That should fail, then I start taking out half 
>> the tests before. If the test still fails, I keep cutting in half until I 
>> can determine which previous test is causing issues. If, after cutting out 
>> tests, the problem test passes, then I need to put back in what I took out 
>> since it was one of those.
>>
>> Once I figure out which previous test it was, I can start removing the 
>> individual tests to finally get to the code causing the problem. Usually, 
>> it's a case that a test changed something and I just have to add in the 
>> teardown function to restore the state of whatever was changed.
>>
>> On Thu, 2016-06-02 at 21:33 +0200, Derek wrote:
>>
>> I have a test that is failing when the file it is in is run as part of 
>> all the other test files by the test runner.
>>
>> If I just run only the file that contains this test -  then it passes.
>>
>> (pass/fail refers to the very last assert in the code below.)
>>
>> I'd appreciate any ideas or insights from anyone who can spot an obvious 
>> mistake - or suggest some options to explore.
>>
>> Thanks
>> Derek
>>
>>
>> # THIS IS AN EXTRACT OF RELEVANT CODE (not all of it...)
>> from django.contrib.messages.storage.fallback import FallbackStorage
>> from django.core.urlresolvers import reverse
>> from django.test import TestCase, Client
>> # ... various app-related imports ...
>>
>>
>> class MockRequest(object):
>> """No code needed."""
>> pass
>>
>>
>> REQUEST = MockRequest()
>> # see: https://stackoverflow.com/queI 
>> stions/11938164/why-dont-my-django-\
>> #  unittests-know-that-messagemiddleware-is-installed
>> setattr(REQUEST, 'session', 'session')
>> MESSAGES = FallbackStorage(REQUEST)
>> setattr(REQUEST, '_messages', MESSAGES)
>> setup_test_environment()
>>
>>
>> class PersonAdminTest(TestCase):
>>
>> def setUp(self):
>> self.user, password = utils.user_factory(model=None)
>> self.client = Client()
>> login_status = self.client.login(username=self.user.email, 
>> password=password)
>> self.assertEqual(login_status, True)
>>
>> def test_action_persons_make_unreal(self):
>> try:
>> change_url = reverse('admin:persons_realpersons_changelist')
>> except NoReverseMatch:
>> change_url = '/admin/persons/realpersons/'
>> sys.stderr.write('\n   WARNING: Unable to reverse URL! ... ')
>> response = self.client.get(change_url)
>> self.assertEqual(response.status_code, 200)
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com.
>> To post to this group, send email to django...@googlegroups.com.
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/CAF1Wu3MoGgm_dSToObDX9gH7GQJ%3DTZzGLV7RPOiZk4kvV-_Nbg%40mail.gmail.com
>>  
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>> -- 
>> Adam (ad...@csh.rit.edu)
>>
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ff76d73a-3baf-4053-b539-7734ba53e61d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Best approach to write unit tests involving rest apis.

2015-12-02 Thread learn django
Hi,

My app uses rest framework.
I am writing test cases which involve standard requests like 
GET/POST/DELETE/PUT.
What is the best approach to write the test cases ?

Should I run the web server from unit test in setUp() (by running 'python 
manage.py runserver') so that http
request response can work. That way I can make sure my urls.py is correctly 
setup.

Or is there a better way to achieve the same ?

For now am calling my rest handlers directly by passing request (of type 
HttpRequest()) to it.
The request object is filled with required info which the backend code 
expects.

Since the handlers are called directly am unable to automate tests to make 
sure
urls are working fine.

Please give pointers as to how this can be done.
Thanks in advance.
  

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c7145ad6-cc76-4db6-ae1d-0167a5bc4fd5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Tests not passing in suite but pass individually

2015-12-02 Thread learn django
Below is the test file & logs.
No matter in which order (using --reverse) I run the suite it fails.
The database backend is postgres. Is that an issue ?

File:-
===
import datetime
import pdb

from rest_framework import status
from rest_framework.test import APIClient

from django.http import HttpRequest
from django.contrib.auth.models import User
from django.utils import timezone
from django.test import TestCase

from orca.models import *

import orca.handlers.customer_handler as ch

# Create your tests here.
class OrcaTestCase(TestCase):

def test_customer_create_modify_delete(self):
'''Test customer object create, modify and delete operations in 
 DB.'''
# Create.
CustomerDb.objects.create(c_name='Zoo', c_role='Admin',
  c_date_created=timezone.now(),
  c_date_updated=timezone.now())
customer_list = CustomerDb.objects.all()
self.assertEqual(len(customer_list), 1)

def test_launch(self):
'''Test launch.'''
CustomerDb.objects.create(c_name='Foo', c_role='Admin',
  c_date_created=timezone.now(),
  c_date_updated=timezone.now())
customer_list = CustomerDb.objects.all()
self.assertEqual(len(customer_list), 1)


Logs:-

==
FAIL: test_customer_create_modify_delete (orca.tests.tmp.OrcaTestCase)
Test customer object create, modify and delete operations in  DB.
--
Traceback (most recent call last):
  File "/home/sidhesh/workspace/sztp/orca/tests/tmp.py", line 26, in 
test_customer_create_modify_delete
self.assertEqual(len(customer_list), 1)
AssertionError: 2 != 1

--
Ran 2 tests in 0.014s

FAILED (failures=1)



On Wednesday, December 2, 2015 at 9:14:54 AM UTC-8, Tim Graham wrote:
>
> How does the test fail? Please show the entire test file including imports.
>
> On Wednesday, December 2, 2015 at 11:20:27 AM UTC-5, learn django wrote:
>>
>> Hi Tim,
>>
>> Below is what am trying to achieve.
>>
>> class OrcaTestCase(TestCase):
>>
>> def test_customer_create_modify_delete(self):
>> '''Test customer object create, modify and delete operations in 
>>  DB.'''
>> # Create.
>> CustomerDb.objects.create(c_name='Pnc', c_role='ADFS-Admin',
>>   c_date_created=timezone.now(),
>>   c_date_updated=timezone.now())
>> customer_list = CustomerDb.objects.all()
>>* self.assertEqual(len(customer_list), 1)*
>>
>> # Modify.
>> customer = CustomerDb.objects.get(c_name='Pnc')
>> self.assertNotEqual(customer, None)
>> setattr(customer, 'c_name', 'Zoo')
>> customer.save()
>> customer_list = CustomerDb.objects.all()
>> self.assertEqual(len(customer_list), 1)
>> self.assertEqual(str(customer_list[0]), 'Gap')
>>
>> # Delete.
>> customer = CustomerDb.objects.get(c_name='foo')
>> self.assertNotEqual(customer, None)
>> customer.delete()
>> customer_list = CustomerDb.objects.all()
>> self.assertEqual(len(customer_list), 0)
>>
>> def test_create_customer(self):
>> '''Handle customer create.'''
>> customer_list = CustomerDb.objects.all()
>> self.assertEqual(len(customer_list), 1)
>>
>> test_create_customer runs first, test_customer_create_modify_delete fails 
>> at the highlighted line.
>>
>> On Wednesday, December 2, 2015 at 6:28:06 AM UTC-8, Tim Graham wrote:
>>>
>>> It will be easier to help if you can provide a sample project that 
>>> reproduces the error.
>>>
>>> On Wednesday, December 2, 2015 at 3:01:31 AM UTC-5, Siddhi Divekar wrote:
>>>>
>>>> Hi,
>>>>
>>>> Am seeing that test case in suite are failing but passing when ran 
>>>> individually.
>>>> I have gone through most of the thread on the internet but did not find 
>>>> any solution.
>>>>
>>>> Below is the snip of what am trying to do.
>>>>
>>>> class A(TestCase):
>>>>   def test_a():
>>>>create an obj in db
>>>>

Re: Tests not passing in suite but pass individually

2015-12-02 Thread learn django
Will try to send minimal project by end of the day.
Hopefully I can discover the reason during this exercise.

On Wednesday, December 2, 2015 at 3:33:30 PM UTC-8, Tim Graham wrote:
>
> It looks correct. I'd like a minimal project I could download to reproduce 
> the issue. In putting that together, you might discover the reason for the 
> failure.
>
> On Wednesday, December 2, 2015 at 6:29:07 PM UTC-5, learn django wrote:
>>
>> Below is the test file & logs.
>> No matter in which order (using --reverse) I run the suite it fails.
>> The database backend is postgres. Is that an issue ?
>>
>> File:-
>> ===
>> import datetime
>> import pdb
>>
>> from rest_framework import status
>> from rest_framework.test import APIClient
>>
>> from django.http import HttpRequest
>> from django.contrib.auth.models import User
>> from django.utils import timezone
>> from django.test import TestCase
>>
>> from orca.models import *
>>
>> import orca.handlers.customer_handler as ch
>>
>> # Create your tests here.
>> class OrcaTestCase(TestCase):
>>
>> def test_customer_create_modify_delete(self):
>> '''Test customer object create, modify and delete operations in 
>>  DB.'''
>> # Create.
>> CustomerDb.objects.create(c_name='Zoo', c_role='Admin',
>>   c_date_created=timezone.now(),
>>   c_date_updated=timezone.now())
>> customer_list = CustomerDb.objects.all()
>> self.assertEqual(len(customer_list), 1)
>>
>> def test_launch(self):
>> '''Test launch.'''
>> CustomerDb.objects.create(c_name='Foo', c_role='Admin',
>>   c_date_created=timezone.now(),
>>   c_date_updated=timezone.now())
>> customer_list = CustomerDb.objects.all()
>> self.assertEqual(len(customer_list), 1)
>>
>>
>> Logs:-
>> 
>> ==
>> FAIL: test_customer_create_modify_delete (orca.tests.tmp.OrcaTestCase)
>> Test customer object create, modify and delete operations in  DB.
>> --
>> Traceback (most recent call last):
>>   File "/home/sidhesh/workspace/sztp/orca/tests/tmp.py", line 26, in 
>> test_customer_create_modify_delete
>> self.assertEqual(len(customer_list), 1)
>> AssertionError: 2 != 1
>>
>> --
>> Ran 2 tests in 0.014s
>>
>> FAILED (failures=1)
>>
>>
>>
>> On Wednesday, December 2, 2015 at 9:14:54 AM UTC-8, Tim Graham wrote:
>>>
>>> How does the test fail? Please show the entire test file including 
>>> imports.
>>>
>>> On Wednesday, December 2, 2015 at 11:20:27 AM UTC-5, learn django wrote:
>>>>
>>>> Hi Tim,
>>>>
>>>> Below is what am trying to achieve.
>>>>
>>>> class OrcaTestCase(TestCase):
>>>>
>>>> def test_customer_create_modify_delete(self):
>>>> '''Test customer object create, modify and delete operations in 
>>>>  DB.'''
>>>> # Create.
>>>> CustomerDb.objects.create(c_name='Pnc', c_role='ADFS-Admin',
>>>>   c_date_created=timezone.now(),
>>>>   c_date_updated=timezone.now())
>>>> customer_list = CustomerDb.objects.all()
>>>>* self.assertEqual(len(customer_list), 1)*
>>>>
>>>> # Modify.
>>>> customer = CustomerDb.objects.get(c_name='Pnc')
>>>> self.assertNotEqual(customer, None)
>>>> setattr(customer, 'c_name', 'Zoo')
>>>> customer.save()
>>>> customer_list = CustomerDb.objects.all()
>>>> self.assertEqual(len(customer_list), 1)
>>>> self.assertEqual(str(customer_list[0]), 'Gap')
>>>>
>>>> # Delete.
>>>> customer = CustomerDb.objects.get(c_name='foo')
>>>> self.assertNotEqual(customer, None)
>>>> customer.delete()
>>>>

Re: Best approach to write unit tests involving rest apis.

2015-12-02 Thread learn django
 On Wednesday, December 2, 2015 at 10:48:52 PM UTC-8, Xavier Ordoquy wrote:
>
> Hi, 
>
> > Le 3 déc. 2015 à 00:12, learn django  > a écrit : 
> > 
> > My app uses rest framework. 
> > I am writing test cases which involve standard requests like 
> GET/POST/DELETE/PUT. 
> > What is the best approach to write the test cases ? 
>
> Django REST framework comes with a test client named APIClient. 
> It will go through the middleware and urls before calling your API entry 
> points which seems to be what you’re looking for. 
> The documentation about it is available at 
> http://www.django-rest-framework.org/api-guide/testing/#apiclient 
>
> Regards, 
> Xavier, 
> Linovia. 
>
>
Hi Linovia,

Yes, I started with that.
Initially I was getting 403 (auth failure) since my backend handlers have 
@login_required decorator.

To overcome that i created a super user (python manage.py superuser) &
used those credentials as below.

# url = '/orca/api/v2/customer/'
# data = {'c_name':'Pnc', 'c_role':'API-Admin'}
# client = APIClient()
# client.login(username='admin', password='admin')
# response = client.post(url, data, format='json') 

After this I started was getting 302 (redirects).
Have you encountered similar issue before ?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d0dab1a9-6b99-462b-911e-f098a4aea79e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Tests not passing in suite but pass individually

2015-12-08 Thread learn django
Hi Tim,

My test case was working with new app in new project which was
using default database.

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

So I went back to my old app and debugged a bit.
If I make following changes in Database dictionary (commenting the bolded 
test) and
make my router for this app to point to default database the tests pass.
Is it because am using postgres that this issue is seen ?

DATABASES = {
'default': {
  *  'ENGINE': 'django.db.backends.sqlite3',*
*'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),*
*#'ENGINE': 'django.db.backends.postgresql_psycopg2',*
*#'USER': 'postgres',*
*#'NAME': 'testdb',*
*# 'PASSWORD':'v1ptela0212',*
*# 'HOST':'localhost',*
*# 'PORT':'',*
*#'TEST': {*
*#'NAME': 'testdb',*
*#},*
},
'sztp': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'sztpdb',
'USER':'postgres',
},
'orca': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'orcadb',
'USER':'postgres',
}
}


On Wednesday, December 2, 2015 at 4:18:25 PM UTC-8, learn django wrote:
>
> Will try to send minimal project by end of the day.
> Hopefully I can discover the reason during this exercise.
>
> On Wednesday, December 2, 2015 at 3:33:30 PM UTC-8, Tim Graham wrote:
>>
>> It looks correct. I'd like a minimal project I could download to 
>> reproduce the issue. In putting that together, you might discover the 
>> reason for the failure.
>>
>> On Wednesday, December 2, 2015 at 6:29:07 PM UTC-5, learn django wrote:
>>>
>>> Below is the test file & logs.
>>> No matter in which order (using --reverse) I run the suite it fails.
>>> The database backend is postgres. Is that an issue ?
>>>
>>> File:-
>>> ===
>>> import datetime
>>> import pdb
>>>
>>> from rest_framework import status
>>> from rest_framework.test import APIClient
>>>
>>> from django.http import HttpRequest
>>> from django.contrib.auth.models import User
>>> from django.utils import timezone
>>> from django.test import TestCase
>>>
>>> from orca.models import *
>>>
>>> import orca.handlers.customer_handler as ch
>>>
>>> # Create your tests here.
>>> class OrcaTestCase(TestCase):
>>>
>>> def test_customer_create_modify_delete(self):
>>> '''Test customer object create, modify and delete operations in 
>>>  DB.'''
>>> # Create.
>>> CustomerDb.objects.create(c_name='Zoo', c_role='Admin',
>>>   c_date_created=timezone.now(),
>>>   c_date_updated=timezone.now())
>>> customer_list = CustomerDb.objects.all()
>>> self.assertEqual(len(customer_list), 1)
>>>
>>> def test_launch(self):
>>> '''Test launch.'''
>>> CustomerDb.objects.create(c_name='Foo', c_role='Admin',
>>>   c_date_created=timezone.now(),
>>>   c_date_updated=timezone.now())
>>> customer_list = CustomerDb.objects.all()
>>> self.assertEqual(len(customer_list), 1)
>>>
>>>
>>> Logs:-
>>> 
>>> ==
>>> FAIL: test_customer_create_modify_delete (orca.tests.tmp.OrcaTestCase)
>>> Test customer object create, modify and delete operations in  DB.
>>> --
>>> Traceback (most recent call last):
>>>   File "/home/sidhesh/workspace/sztp/orca/tests/tmp.py", line 26, in 
>>> test_customer_create_modify_delete
>>> self.assertEqual(len(customer_list), 1)
>>> AssertionError: 2 != 1
>>>
>>> --
>>> Ran 2 tests in 0.014s
>>>
>>> FAILED (failures

Re: Tests not passing in suite but pass individually

2015-12-09 Thread learn django
After making following change & pointing router to 'default' database test 
case is passing.

'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': 'postgres',
'NAME': '*mydb*',
'PASSWORD':'0212',
'HOST':'localhost',
'PORT':'',
'TEST': {
   'NAME': '*mytestdb*',
},
},

However if I make router to point to app specific db which is defined as 
follows,
the test case still fails. I think its better not to keep on modifying the 
router.

Is there anything wrong with the app database definition below.

'orca': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '*orcadb*',
'USER':'postgres',
'PASSWORD':'0212',
'HOST':'localhost',
'PORT':'',
    'TEST': {
   'NAME': '*orcatestdb*',
},
}


On Wednesday, December 9, 2015 at 4:44:14 AM UTC-8, Tim Graham wrote:
>
> It seems a bit suspicious that you're using the same database name for 
> ['default']['NAME'] and ['default']['TEST']['NAME'] -- is that intentional?
>
> On Tuesday, December 8, 2015 at 8:30:05 PM UTC-5, learn django wrote:
>>
>> Hi Tim,
>>
>> My test case was working with new app in new project which was
>> using default database.
>>
>> DATABASES = {
>> 'default': {
>> 'ENGINE': 'django.db.backends.sqlite3',
>> 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
>> }
>> }
>>
>> So I went back to my old app and debugged a bit.
>> If I make following changes in Database dictionary (commenting the bolded 
>> test) and
>> make my router for this app to point to default database the tests pass.
>> Is it because am using postgres that this issue is seen ?
>>
>> DATABASES = {
>> 'default': {
>>   *  'ENGINE': 'django.db.backends.sqlite3',*
>> *'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),*
>> *#'ENGINE': 'django.db.backends.postgresql_psycopg2',*
>> *#'USER': 'postgres',*
>> *#'NAME': 'testdb',*
>> *# 'PASSWORD':'v1ptela0212',*
>> *# 'HOST':'localhost',*
>> *# 'PORT':'',*
>> *#'TEST': {*
>> *#'NAME': 'testdb',*
>> *#},*
>> },
>> 'sztp': {
>> 'ENGINE': 'django.db.backends.postgresql_psycopg2',
>> 'NAME': 'sztpdb',
>> 'USER':'postgres',
>> },
>> 'orca': {
>> 'ENGINE': 'django.db.backends.postgresql_psycopg2',
>> 'NAME': 'orcadb',
>> 'USER':'postgres',
>> }
>> }
>>
>>
>> On Wednesday, December 2, 2015 at 4:18:25 PM UTC-8, learn django wrote:
>>>
>>> Will try to send minimal project by end of the day.
>>> Hopefully I can discover the reason during this exercise.
>>>
>>> On Wednesday, December 2, 2015 at 3:33:30 PM UTC-8, Tim Graham wrote:
>>>>
>>>> It looks correct. I'd like a minimal project I could download to 
>>>> reproduce the issue. In putting that together, you might discover the 
>>>> reason for the failure.
>>>>
>>>> On Wednesday, December 2, 2015 at 6:29:07 PM UTC-5, learn django wrote:
>>>>>
>>>>> Below is the test file & logs.
>>>>> No matter in which order (using --reverse) I run the suite it fails.
>>>>> The database backend is postgres. Is that an issue ?
>>>>>
>>>>> File:-
>>>>> ===
>>>>> import datetime
>>>>> import pdb
>>>>>
>>>>> from rest_framework import status
>>>>> from rest_framework.test import APIClient
>>>>>
>>>>> from django.http import HttpReques

Re: Multiple databases in Django 1.7

2015-12-09 Thread learn django
Hi LP.

Your allow_migrate function differs in the format from what is mentioned in 
the link below.
https://docs.djangoproject.com/en/dev/topics/db/multi-db/#topics-db-multi-db-routing

I have tried this last week and it works fine.

On Wednesday, December 9, 2015 at 2:47:42 AM UTC-8, Łukasz Pauszek wrote:
>
> Hello,
> I'm trying to configure project in Django 1.7 to use multiple databases, 
> for now I'm following official documentation to configure 2 dbs. 
> Problem is that when I run: ./manage.py makemigrations myapp only changes 
> in default database are detected. And ./manage.py migrate 
> --database=main_db doesn't see model which should be created in it. 
> What should I do to update second database?
> Below I'm pasting code which I think may be relevant:
>
> project/settings.py
> DATABASES = {
> 'default': {
> 'ENGINE': 'django.db.backends.sqlite3',
> 'NAME': os.path.join(BASE_DIR, 'default.sqlite3'),
> },
> 'main_db': {
> 'ENGINE': 'django.db.backends.sqlite3',
> 'NAME': os.path.join(BASE_DIR, 'main_db.sqlite3')
> }
> }
>
> DATABASE_ROUTERS = ['myapp.routers.SelectDatabaseRouter']
>
> myapp/models.py
> class TestingDefaultDatabase(models.Model):
>
> class Meta:
> verbose_name = "TestingDefaultDatabase"
> verbose_name_plural = "TestingDefaultDatabases"
>
> name = models.CharField(max_length=50)
> surname = models.CharField(max_length=50)
>
>
> class TestingMainDatabase(models.Model):
>
> class Meta:
> verbose_name = "TestingMainDatabase"
> verbose_name_plural = "TestingMainDatabases"
> app_label = 'main'
>
> name = models.CharField(max_length=50)
> surname = models.CharField(max_length=50)
>
> myapp/routers.py
> class SelectDatabaseRouter(object):
> def db_for_read(self, model, **hints):
> if model._meta.app_label == 'main':
> return 'main_db'
> return None
>
> def db_for_write(self, model, **hints):
> if model._meta.app_label == 'main':
> return 'main_db'
> return None
>
> def allow_relation(self, obj1, obj2, **hints):
> if obj1._meta.app_label == 'main' or \
> obj2._meta.app_label == 'main':
> return True
> return None
>
> def allow_migrate(self, db, model):
> if db == 'main_db':
> return model._meta.app_label == 'main'
> elif model._meta.app_label == 'main':
> return False
> return None
>
> Am I missing or incorrectly configured something? Or perhaps I'm not using 
> appropriate commands?
> Thank you for help.
> ŁP
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a89f9477-2241-4fd4-8506-283602693953%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Setting up django mailbox

2016-02-04 Thread learn django
Hi,

Am trying to setup django mailbox  from admin page and seeing issues.

My email address is f...@company.com. We use google.com for our email 
service.

My username is "a...@company.com", name is "abc abc" and password is 
"abc1234".

Am putting following details on django_mailbox page.

Name: "abc abc"
URI: "imap+ssl://abc%40company.com:abc1...@imap.company.com"
>From email: "a...@company.com"

I see following traceback on running "python manage.py getmail".
I have enabled imap under setting under google for my account.

$ python manage.py getmail
/usr/local/lib/python2.7/dist-packages/djangosaml2/conf.py:20: 
RemovedInDjango19Warning: django.utils.importlib will be removed in Django 
1.9.
  from django.utils.importlib import import_module

Traceback (most recent call last):
  File "manage.py", line 10, in 
execute_from_command_line(sys.argv)
  File 
"/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", 
line 338, in execute_from_command_line
utility.execute()
  File 
"/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", 
line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
  File 
"/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", 
line 390, in run_from_argv
self.execute(*args, **cmd_options)
  File 
"/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", 
line 441, in execute
output = self.handle(*args, **options)
  File 
"/usr/local/lib/python2.7/dist-packages/django_mailbox/management/commands/getmail.py",
 
line 24, in handle
messages = mailbox.get_new_mail()
  File "/usr/local/lib/python2.7/dist-packages/django_mailbox/models.py", 
line 393, in get_new_mail
connection = self.get_connection()
  File "/usr/local/lib/python2.7/dist-packages/django_mailbox/models.py", 
line 229, in get_connection
conn.connect(self.username, self.password)
  File 
"/usr/local/lib/python2.7/dist-packages/django_mailbox/transports/imap.py", 
line 41, in connect
typ, msg = self.server.login(username, password)
  File "/usr/lib/python2.7/imaplib.py", line 519, in login
raise self.error(dat[-1])
imaplib.error: Login failed.

Am unable to figure out what is happening here.
Any help is appreciated.
Thanks in advance.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b600ce76-0881-4281-8a93-30697f3dc7d3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Setting up django mailbox

2016-02-04 Thread learn django
I tried both but no luck.

On Thursday, February 4, 2016 at 3:49:48 PM UTC-8, Dheerendra Rathor wrote:
>
> Are you sure imap.company.com is handling your imap server and not 
> imap.google.com?
>
> On Thu, 4 Feb 2016 at 23:24 Daniel Chimeno  > wrote:
>
>> Hello,
>> If you are writing about his project: 
>> https://github.com/coddingtonbear/django-mailbox I guess
>> it's better to ask in the issues page of that project: 
>> https://github.com/coddingtonbear/django-mailbox/issues
>>
>>  
>>
>> El jueves, 4 de febrero de 2016, 23:02:36 (UTC+1), learn django escribió:
>>
>>> Hi,
>>>
>>> Am trying to setup django mailbox  from admin page and seeing issues.
>>>
>>> My email address is f...@company.com. We use google.com for our email 
>>> service.
>>>
>>> My username is "a...@company.com", name is "abc abc" and password is 
>>> "abc1234".
>>>
>>
>>> Am putting following details on django_mailbox page.
>>>
>>> Name: "abc abc"
>>>
>> URI: "imap+ssl://abc%40company.com:abc1...@imap.company.com"
>>> From email: "a...@company.com"
>>>
>>
>>> I see following traceback on running "python manage.py getmail".
>>> I have enabled imap under setting under google for my account.
>>>
>>> $ python manage.py getmail
>>> /usr/local/lib/python2.7/dist-packages/djangosaml2/conf.py:20: 
>>> RemovedInDjango19Warning: django.utils.importlib will be removed in Django 
>>> 1.9.
>>>   from django.utils.importlib import import_module
>>>
>>> Traceback (most recent call last):
>>>   File "manage.py", line 10, in 
>>> execute_from_command_line(sys.argv)
>>>   File 
>>> "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py",
>>>  
>>> line 338, in execute_from_command_line
>>> utility.execute()
>>>   File 
>>> "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py",
>>>  
>>> line 330, in execute
>>> self.fetch_command(subcommand).run_from_argv(self.argv)
>>>   File 
>>> "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", 
>>> line 390, in run_from_argv
>>> self.execute(*args, **cmd_options)
>>>   File 
>>> "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", 
>>> line 441, in execute
>>> output = self.handle(*args, **options)
>>>   File 
>>> "/usr/local/lib/python2.7/dist-packages/django_mailbox/management/commands/getmail.py",
>>>  
>>> line 24, in handle
>>> messages = mailbox.get_new_mail()
>>>   File 
>>> "/usr/local/lib/python2.7/dist-packages/django_mailbox/models.py", line 
>>> 393, in get_new_mail
>>> connection = self.get_connection()
>>>   File 
>>> "/usr/local/lib/python2.7/dist-packages/django_mailbox/models.py", line 
>>> 229, in get_connection
>>> conn.connect(self.username, self.password)
>>>   File 
>>> "/usr/local/lib/python2.7/dist-packages/django_mailbox/transports/imap.py", 
>>> line 41, in connect
>>> typ, msg = self.server.login(username, password)
>>>   File "/usr/lib/python2.7/imaplib.py", line 519, in login
>>> raise self.error(dat[-1])
>>> imaplib.error: Login failed.
>>>
>>> Am unable to figure out what is happening here.
>>> Any help is appreciated.
>>> Thanks in advance.
>>>
>>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/7d0e657f-a3b0-42e4-821e-9b9c2c7ad15a%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/7d0e657f-a3b0-42e4-821e-9b9c2c7ad15a%40googlegroups.com?utm_medium=email&utm_source=footer>
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/06c547d8-a4fd-4ea8-b3e9-dfab2a699117%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Setting up django mailbox

2016-02-05 Thread learn django
Hi All,

I was able to resolve the issue yesterday night.
Forgot to send an email.

I had to reduce the security level of gmail so that app can access it.

Thanks for all the help.

On Thursday, February 4, 2016 at 11:58:03 PM UTC-8, Daniel Chimeno wrote:
>
> This are the settings you should put:
>
> https://support.google.com/mail/troubleshooter/1668960?rd=1#ts=1665018%2C1665144
>
>
> El viernes, 5 de febrero de 2016, 2:04:44 (UTC+1), learn django escribió:
>>
>> I tried both but no luck.
>>
>> On Thursday, February 4, 2016 at 3:49:48 PM UTC-8, Dheerendra Rathor 
>> wrote:
>>>
>>> Are you sure imap.company.com is handling your imap server and not 
>>> imap.google.com?
>>>
>>> On Thu, 4 Feb 2016 at 23:24 Daniel Chimeno  wrote:
>>>
>>>> Hello,
>>>> If you are writing about his project: 
>>>> https://github.com/coddingtonbear/django-mailbox I guess
>>>> it's better to ask in the issues page of that project: 
>>>> https://github.com/coddingtonbear/django-mailbox/issues
>>>>
>>>>  
>>>>
>>>> El jueves, 4 de febrero de 2016, 23:02:36 (UTC+1), learn django 
>>>> escribió:
>>>>
>>>>> Hi,
>>>>>
>>>>> Am trying to setup django mailbox  from admin page and seeing issues.
>>>>>
>>>>> My email address is f...@company.com. We use google.com for our email 
>>>>> service.
>>>>>
>>>>> My username is "a...@company.com", name is "abc abc" and password is 
>>>>> "abc1234".
>>>>>
>>>>
>>>>> Am putting following details on django_mailbox page.
>>>>>
>>>>> Name: "abc abc"
>>>>>
>>>> URI: "imap+ssl://abc%40company.com:abc1...@imap.company.com"
>>>>> From email: "a...@company.com"
>>>>>
>>>>
>>>>> I see following traceback on running "python manage.py getmail".
>>>>> I have enabled imap under setting under google for my account.
>>>>>
>>>>> $ python manage.py getmail
>>>>> /usr/local/lib/python2.7/dist-packages/djangosaml2/conf.py:20: 
>>>>> RemovedInDjango19Warning: django.utils.importlib will be removed in 
>>>>> Django 
>>>>> 1.9.
>>>>>   from django.utils.importlib import import_module
>>>>>
>>>>> Traceback (most recent call last):
>>>>>   File "manage.py", line 10, in 
>>>>> execute_from_command_line(sys.argv)
>>>>>   File 
>>>>> "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py",
>>>>>  
>>>>> line 338, in execute_from_command_line
>>>>> utility.execute()
>>>>>   File 
>>>>> "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py",
>>>>>  
>>>>> line 330, in execute
>>>>> self.fetch_command(subcommand).run_from_argv(self.argv)
>>>>>   File 
>>>>> "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", 
>>>>> line 390, in run_from_argv
>>>>> self.execute(*args, **cmd_options)
>>>>>   File 
>>>>> "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", 
>>>>> line 441, in execute
>>>>> output = self.handle(*args, **options)
>>>>>   File 
>>>>> "/usr/local/lib/python2.7/dist-packages/django_mailbox/management/commands/getmail.py",
>>>>>  
>>>>> line 24, in handle
>>>>> messages = mailbox.get_new_mail()
>>>>>   File 
>>>>> "/usr/local/lib/python2.7/dist-packages/django_mailbox/models.py", line 
>>>>> 393, in get_new_mail
>>>>> connection = self.get_connection()
>>>>>   File 
>>>>> "/usr/local/lib/python2.7/dist-packages/django_mailbox/models.py", line 
>>>>> 229, in get_connection
>>>>> conn.connect(self.username, self.password)
>>>>>   File 
>>>>> "/usr/local/lib/python2.7/dist-packages/django_mailbox/transports/imap.py",
>>>>>  
>>>>> line 41, in connect
>>>>> typ, msg = self.server.login(username, password)
>>>>

Right place to decrypt/decode data from DB before passing it to UI without affect data in DB itself.

2016-02-08 Thread learn django
Hi,

I store some data like email text, headers and from email address in 
encoded format in the database.
I want to have a  page where I can display all this information in readonly 
format.

What is the ideal place & way to decode this information and pass it to 
django UI.

I was thinking of reading all the information in my views.py.
But then I don't want to affect my DB. aka information in DB should remain 
encoded.

eg.

class FooViewSet(viewsets.ModelViewSet):
queryset = Message.objects.all()

Message object has headers, body and from fields which are encoded before 
storing in db.
If I perform any operation on queryset those changes will be reflected in 
DB so I cannot do that.

If I do something like below then I get exception for using list as 
queryset becomes a list object instead of queryset object.

class FooViewSet(viewsets.ModelViewSet):
queryset = list(Message.objects.all())
for obj in queryset:
body = base64.b64decode(obj.body)
obj.body = body

--089e01183b7099cbb7052b01766b--

Traceback (most recent call last):
  File "sztp/wsgi.py", line 16, in 
application = get_wsgi_application()
  File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 
14, in get_wsgi_application
django.setup()
  File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 
18, in setup
apps.populate(settings.INSTALLED_APPS)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", 
line 115, in populate
app_config.ready()
  File "/usr/local/lib/python2.7/dist-packages/debug_toolbar/apps.py", line 
15, in ready
dt_settings.patch_all()
  File "/usr/local/lib/python2.7/dist-packages/debug_toolbar/settings.py", 
line 232, in patch_all
patch_root_urlconf()
  File "/usr/local/lib/python2.7/dist-packages/debug_toolbar/settings.py", 
line 220, in patch_root_urlconf
reverse('djdt:render_panel')
  File 
"/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 
550, in reverse
app_list = resolver.app_dict[ns]
  File 
"/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 
352, in app_dict
self._populate()
  File 
"/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 
285, in _populate
for pattern in reversed(self.url_patterns):
  File 
"/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 
402, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", 
self.urlconf_module)
  File 
"/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 
396, in urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
  File "./sztp/urls.py", line 52, in 
url(r'^orca/', include('orca.urls.urls')),
  File 
"/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py", line 
33, in include
urlconf_module = import_module(urlconf_module)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
  File "./orca/urls/urls.py", line 26, in 
router.register(r'notification', views.NotificationViewSet)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/routers.py", 
line 61, in register
base_name = self.get_default_base_name(viewset)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/routers.py", 
line 140, in get_default_base_name
return queryset.model._meta.object_name.lower()
AttributeError: 'list' object has no attribute 'model'

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ce9b3654-6c73-4582-aae6-104d4145b466%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.