Re: Error with Tutorial - Writing your first Django app, part 1

2016-10-10 Thread Dylan Reinhold
In polls/url.py patterns is missing the N.

Dylan

On Mon, Oct 10, 2016 at 5:24 PM, Johnny McClung  wrote:

> Thank you. I've added the comma as you mentioned. Can't believe I missed
> that. But now I am getting a new error.
>
>
>
> E:\Dropbox\Python Scripts\mysite>python manage.py runserver
> Performing system checks...
>
> Unhandled exception in thread started by  check_errors..wrapper at 0x044B16A8>
> Traceback (most recent call last):
>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\
> lib\site-packages\django\urls\resolvers.py", line 315, in url_patterns
> iter(patterns)
> TypeError: 'module' object is not iterable
>
> During handling of the above exception, another exception occurred:
>
> Traceback (most recent call last):
>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\
> lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
> fn(*args, **kwargs)
>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\
> lib\site-packages\django\core\management\commands\runserver.py", line
> 121, in inner_run
> self.check(display_num_errors=True)
>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\
> lib\site-packages\django\core\management\base.py", line 374, in check
> include_deployment_checks=include_deployment_checks,
>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\
> lib\site-packages\django\core\management\base.py", line 361, in
> _run_checks
> return checks.run_checks(**kwargs)
>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\
> lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
> new_errors = check(app_configs=app_configs)
>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\
> lib\site-packages\django\core\checks\urls.py", line 14, in
> check_url_config
> return check_resolver(resolver)
>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\
> lib\site-packages\django\core\checks\urls.py", line 28, in check_resolver
> warnings.extend(check_resolver(pattern))
>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\
> lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
> for pattern in resolver.url_patterns:
>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\
> lib\site-packages\django\utils\functional.py", line 35, in __get__
> res = instance.__dict__[self.name] = self.func(instance)
>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\
> lib\site-packages\django\urls\resolvers.py", line 322, in url_patterns
> raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
> django.core.exceptions.ImproperlyConfigured: The included URLconf
> ' Scripts\\mysite\\polls\\urls.py'>' does not appear to have any patterns
> in it. If you see valid patterns in the file then the issue is probably
> caused by a circular import.
>
>
>
> --
> 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/c2742620-55fc-4db1-b92a-2dfc392d8903%40googlegroups.com
> 
> .
>
> 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/CAHtg44BuOP%3DwQZrgYUxBFK_gRHTSVAvJ_XzHKq4%2BKKuW%3De7b7Q%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Error with Tutorial - Writing your first Django app, part 1

2016-10-10 Thread Johnny McClung
Thank you. I've added the comma as you mentioned. Can't believe I missed 
that. But now I am getting a new error. 



E:\Dropbox\Python Scripts\mysite>python manage.py runserver
Performing system checks...

Unhandled exception in thread started by .wrapper at 0x044B16A8>
Traceback (most recent call last):
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py",
 
line 315, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\autoreload.py",
 
line 226, in wrapper
fn(*args, **kwargs)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\commands\runserver.py",
 
line 121, in inner_run
self.check(display_num_errors=True)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py",
 
line 374, in check
include_deployment_checks=include_deployment_checks,
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py",
 
line 361, in _run_checks
return checks.run_checks(**kwargs)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\registry.py",
 
line 81, in run_checks
new_errors = check(app_configs=app_configs)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\urls.py",
 
line 14, in check_url_config
return check_resolver(resolver)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\urls.py",
 
line 28, in check_resolver
warnings.extend(check_resolver(pattern))
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\urls.py",
 
line 24, in check_resolver
for pattern in resolver.url_patterns:
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\functional.py",
 
line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py",
 
line 322, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf '' 
does not appear to have any patterns in it. If you see valid patterns in 
the file then the issue is probably caused by a circular import.



-- 
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/c2742620-55fc-4db1-b92a-2dfc392d8903%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How to read the json file of a dinamical way in relation to their size structure

2016-10-10 Thread Bernardo Garcia


I have the following JSON file named ProcessedMetrics.json which is 
necessary read for send their values to some template:


 {
  "paciente": {
"id": 1234,
"nombre": "Pablo Andrés Agudelo Marenco",
"sesion": {
  "id": 12345,
  "juego": [
{
  "nombre": "bonzo",
  "nivel": [
{
  "id": 1234,
  "nombre": "caida libre",
  "segmento": [
{
  "id": 12345,
  "nombre": "Hombro",
  "movimiento": [
{
  "id": 1234,
  "nombre": "flexion",
  "metricas": [
{
  "min": 12,
  "max": 34,
  "media": 23,
  "moda": 20
}
  ]
}
  ]
}
  ],
  "___léeme___": "El array 'iteraciones' contiene las vitorias o 
derrotas con el tiempo en segundos de cada iteración",
  "iteraciones": [
{
  "victoria": true,
  "tiempo": 120
},
{
  "victoria": false,
  "tiempo": 232
}
  ]
}
  ]
}
  ]
}
  }}



Through of the following class based view I am reading a JSON file:

class RehabilitationSessionDetail(LoginRequiredMixin,DetailView):
model = RehabilitationSession
template_name = 'rehabilitationsession_detail.html'

def get_context_data(self, **kwargs):
context=super(RehabilitationSessionDetail, 
self).get_context_data(**kwargs)
is_auth=False

user = self.request.user
if user.is_authenticated():
is_auth=True

with open('ProcessedMetrics.json') as data_file:
session_data=json.loads(data_file.read())

#Sending a data to template
   context.update({'is_auth':is_auth,
   'session_data':session_data
 })
   return context


In my template rehabilitationsession_detail.html I put my tag of this way:

{{session_data.paciente.sesion.juego}} 

Then I get the document json in my template:




In my template, I want get the dictionary(before json document) values of a 
separate way such as follow:










The idea is that without matter the nested levels of the json document I 
can get the values. 


Sometimes, the json document will have more identation levels in their 
structure and other times will be a json document more simple


I would that independently of the json document size (if this have more 
than one item in your arrays) will be possible read and get all the values.

I try accessing to the specific item from the RehabilitationSessionDetail view 
of this way:


segment = 
data["paciente"]["sesion"]["juego"][0]["nivel"][0]["segmento"][0]["nombre"]


And this works, but not always I will get the same json document structure.

In summary, How to can I get the values (nested and parents) of my json 
document for send them to the template?

I hope can be clear in my question. Any orientation is highly graceful



-- 
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/c5256c63-03e3-42ff-9e05-41b181292ee4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: EmailValidator and ipv4 or ipv6 address

2016-10-10 Thread Vineet Kothari
Domains are also mapped to ip only by DNS

On Fri, Oct 7, 2016 at 9:06 PM, Tim Graham  wrote:

> I'd take a look at the tests for the validator to see its expected inputs:
> https://github.com/django/django/blob/c60feb6999f83bfd1fdabff01f0dd4
> a26d72e158/tests/validators/tests.py#L48-L96
>
> By the way, there's a ticket to relax the validation and use whatever
> HTML5 validation uses:
> https://code.djangoproject.com/ticket/26423
>
> On Friday, October 7, 2016 at 7:31:06 AM UTC-4, Ilya Deynega wrote:
>>
>> Hello, I've encountered a strange behavior of
>> django.core.validators.EmailValidator, isn't it supposed to accept ip
>> address instead of domain? Like user...@1.1.1.1 instead instead of
>> user...@example.com. In fact, if you try to validate ip address as an
>> email domain part validation fails: 
>> EmailValidator().validate_domain_part('8.8.8.8')
>> is False. is it an error in validator or am I missing something?
>> Source code: https://docs.djangoproject.com/en/1.9/_modules/django/core/
>> validators/
>> Best regards, Ilya Deynega.
>>
> --
> 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/a76b73b4-027d-4397-9c4d-c4811d63f2d7%40googlegroups.com
> 
> .
> 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/CAAcansvbCJUPT%2BUM4By6wa3gUJfu9w67ws3excd7aGNDDLY80w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Multiple instances of a Django application operating on different data

2016-10-10 Thread Vineet Kothari
you can use classes refer from here
https://github.com/bmentges/django-cart
and see how he is using cart.py


On Sat, Oct 8, 2016 at 3:22 PM, hans.krebs42  wrote:

> I'm coding a Django web project. I've created an app and implemented its
> functionality - templates, models etc. The website needs to use this
> application in two places, and the only difference are the sets of data the
> instances will be operating on (for example, say it's a news app and I have
> two unrelated sections of the site, each needs to display news concerning
> completely different topics). Is there a clean (i.e. other than just
> copying all the code into another directory) way to achieve this in Django?
> Ideally I'd like to use one database and split the data into separate
> tables.
>
> --
> 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/713754f8-89ec-44cd-92d2-2017035e5cd1%40googlegroups.com
> 
> .
> 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/CAAcanstNRGVzG94yAk%3Da_A5LEdYJz0AKta23wRiQdK%2BFnnPQZA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Error with Tutorial - Writing your first Django app, part 1

2016-10-10 Thread Vineet Kothari
try to swap both statement


On Tue, Oct 11, 2016 at 2:13 AM, Tim Graham  wrote:

> Add a comma after: url(r'^polls/', include('polls.urls'))
> (these are items in a list, separated by a comma)
>
>
> On Monday, October 10, 2016 at 4:42:30 PM UTC-4, Johnny McClung wrote:
>>
>> I am getting an error when I try to run the Django server.
>>
>> >> mysite >> polls >> urls.py
>> from django.conf.urls import url
>>
>>
>> from . import views
>>
>> urlpatters = [
>> url(r'^$', views.index, name='index'),
>> ]
>>
>>
>>
>>
>> >> mysite >> mysite >> urls.py
>> from django.conf.urls import include, url
>> from django.contrib import admin
>>
>> urlpatterns = [
>> url(r'^polls/', include('polls.urls'))
>> url(r'^admin/', admin.site.urls),
>> ]
>>
>>
>>
>> Error:
>>
>> E:\Dropbox\Python Scripts\mysite>python manage.py runserver
>> Performing system checks...
>>
>> Unhandled exception in thread started by > check_errors..wrapper at 0x03F616A8>
>> Traceback (most recent call last):
>>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib
>> \site-packages\django\utils\autoreload.py", line 226, in wrapper
>> fn(*args, **kwargs)
>>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib
>> \site-packages\django\core\management\commands\runserver.py", line 121,
>> in inner_run
>> self.check(display_num_errors=True)
>>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib
>> \site-packages\django\core\management\base.py", line 374, in check
>> include_deployment_checks=include_deployment_checks,
>>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib
>> \site-packages\django\core\management\base.py", line 361, in _run_checks
>> return checks.run_checks(**kwargs)
>>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib
>> \site-packages\django\core\checks\registry.py", line 81, in run_checks
>> new_errors = check(app_configs=app_configs)
>>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib
>> \site-packages\django\core\checks\urls.py", line 14, in check_url_config
>> return check_resolver(resolver)
>>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib
>> \site-packages\django\core\checks\urls.py", line 24, in check_resolver
>> for pattern in resolver.url_patterns:
>>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib
>> \site-packages\django\utils\functional.py", line 35, in __get__
>> res = instance.__dict__[self.name] = self.func(instance)
>>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib
>> \site-packages\django\urls\resolvers.py", line 313, in url_patterns
>> patterns = getattr(self.urlconf_module, "urlpatterns",
>> self.urlconf_module)
>>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib
>> \site-packages\django\utils\functional.py", line 35, in __get__
>> res = instance.__dict__[self.name] = self.func(instance)
>>   File "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib
>> \site-packages\django\urls\resolvers.py", line 306, in urlconf_module
>> return import_module(self.urlconf_name)
>>   File 
>> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py",
>> line 126, in import_module
>> return _bootstrap._gcd_import(name[level:], package, level)
>>   File "", line 986, in _gcd_import
>>   File "", line 969, in _find_and_load
>>   File "", line 958, in
>> _find_and_load_unlocked
>>   File "", line 673, in _load_unlocked
>>   File "", line 661, in exec_module
>>   File "", line 767, in get_code
>>   File "", line 727, in
>> source_to_code
>>   File "", line 222, in
>> _call_with_frames_removed
>>   File "E:\Dropbox\Python Scripts\mysite\mysite\urls.py", line 21
>> url(r'^admin/', admin.site.urls),
>>   ^
>> SyntaxError: invalid syntax
>>
>>
>> Any help would be appreciated. Thank you.
>>
>> --
> 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/a2fb5396-1818-4f92-8f45-7e78fd658dff%40googlegroups.com
> 
> .
>
> 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-use

Re: Error with Tutorial - Writing your first Django app, part 1

2016-10-10 Thread Tim Graham
Add a comma after: url(r'^polls/', include('polls.urls'))
(these are items in a list, separated by a comma)

On Monday, October 10, 2016 at 4:42:30 PM UTC-4, Johnny McClung wrote:
>
> I am getting an error when I try to run the Django server. 
>
> >> mysite >> polls >> urls.py
> from django.conf.urls import url
>
>
> from . import views
>
> urlpatters = [
> url(r'^$', views.index, name='index'),
> ]
>
>
>
>
> >> mysite >> mysite >> urls.py
> from django.conf.urls import include, url
> from django.contrib import admin
>
> urlpatterns = [
> url(r'^polls/', include('polls.urls'))
> url(r'^admin/', admin.site.urls),
> ]
>
>
>
> Error:
>
> E:\Dropbox\Python Scripts\mysite>python manage.py runserver
> Performing system checks...
>
> Unhandled exception in thread started by  check_errors..wrapper at 0x03F616A8>
> Traceback (most recent call last):
>   File 
> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\autoreload.py",
>  
> line 226, in wrapper
> fn(*args, **kwargs)
>   File 
> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\commands\runserver.py",
>  
> line 121, in inner_run
> self.check(display_num_errors=True)
>   File 
> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py",
>  
> line 374, in check
> include_deployment_checks=include_deployment_checks,
>   File 
> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py",
>  
> line 361, in _run_checks
> return checks.run_checks(**kwargs)
>   File 
> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\registry.py",
>  
> line 81, in run_checks
> new_errors = check(app_configs=app_configs)
>   File 
> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\urls.py",
>  
> line 14, in check_url_config
> return check_resolver(resolver)
>   File 
> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\urls.py",
>  
> line 24, in check_resolver
> for pattern in resolver.url_patterns:
>   File 
> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\functional.py",
>  
> line 35, in __get__
> res = instance.__dict__[self.name] = self.func(instance)
>   File 
> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py",
>  
> line 313, in url_patterns
> patterns = getattr(self.urlconf_module, "urlpatterns", 
> self.urlconf_module)
>   File 
> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\functional.py",
>  
> line 35, in __get__
> res = instance.__dict__[self.name] = self.func(instance)
>   File 
> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py",
>  
> line 306, in urlconf_module
> return import_module(self.urlconf_name)
>   File 
> "C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py",
>  
> line 126, in import_module
> return _bootstrap._gcd_import(name[level:], package, level)
>   File "", line 986, in _gcd_import
>   File "", line 969, in _find_and_load
>   File "", line 958, in 
> _find_and_load_unlocked
>   File "", line 673, in _load_unlocked
>   File "", line 661, in exec_module
>   File "", line 767, in get_code
>   File "", line 727, in 
> source_to_code
>   File "", line 222, in 
> _call_with_frames_removed
>   File "E:\Dropbox\Python Scripts\mysite\mysite\urls.py", line 21
> url(r'^admin/', admin.site.urls),
>   ^
> SyntaxError: invalid syntax
>
>
> Any help would be appreciated. Thank you. 
>
>

-- 
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/a2fb5396-1818-4f92-8f45-7e78fd658dff%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Error with Tutorial - Writing your first Django app, part 1

2016-10-10 Thread Johnny McClung
I am getting an error when I try to run the Django server. 

>> mysite >> polls >> urls.py
from django.conf.urls import url


from . import views

urlpatters = [
url(r'^$', views.index, name='index'),
]




>> mysite >> mysite >> urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
url(r'^polls/', include('polls.urls'))
url(r'^admin/', admin.site.urls),
]



Error:

E:\Dropbox\Python Scripts\mysite>python manage.py runserver
Performing system checks...

Unhandled exception in thread started by .wrapper at 0x03F616A8>
Traceback (most recent call last):
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\autoreload.py",
 
line 226, in wrapper
fn(*args, **kwargs)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\commands\runserver.py",
 
line 121, in inner_run
self.check(display_num_errors=True)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py",
 
line 374, in check
include_deployment_checks=include_deployment_checks,
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py",
 
line 361, in _run_checks
return checks.run_checks(**kwargs)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\registry.py",
 
line 81, in run_checks
new_errors = check(app_configs=app_configs)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\urls.py",
 
line 14, in check_url_config
return check_resolver(resolver)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\urls.py",
 
line 24, in check_resolver
for pattern in resolver.url_patterns:
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\functional.py",
 
line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py",
 
line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", 
self.urlconf_module)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\functional.py",
 
line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py",
 
line 306, in urlconf_module
return import_module(self.urlconf_name)
  File 
"C:\Users\geek\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py",
 
line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
  File "", line 986, in _gcd_import
  File "", line 969, in _find_and_load
  File "", line 958, in _find_and_load_unlocked
  File "", line 673, in _load_unlocked
  File "", line 661, in exec_module
  File "", line 767, in get_code
  File "", line 727, in source_to_code
  File "", line 222, in 
_call_with_frames_removed
  File "E:\Dropbox\Python Scripts\mysite\mysite\urls.py", line 21
url(r'^admin/', admin.site.urls),
  ^
SyntaxError: invalid syntax


Any help would be appreciated. Thank you. 

-- 
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/9a44648b-dfc1-476a-be2f-12b74328e6d6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: template or javascript

2016-10-10 Thread ludovic coues
Personally, I pass a dict named current in the context. For the home
page, the dict is {'home': 'active'} and for about, it's {'about':
'active'}. Then the link to the home page is , the link to about is , etc...

It might not be the best way but it's pretty straightforward and
that's what I use when I need to highlight the current page.

I'm curious to read about how other django's user are doing it :)

2016-10-10 21:05 GMT+02:00 Lorenzo Bernardi :
> Hello,
>
>   I'm making a website with bootstrap and I use some menu items (in fact nav
> bars) and I was wondering what is the best practice to make a menu item
> highlighted when I am on the page connected with this menu item. I mean in
> bootstrap the nav bar has a  to highlight the fact that
> I'm on this page. I was wondering if I should use django context to give the
> information and set in the template {% if currentpage="home"  %}
> class="active" {% endif %} or if I should use some javascript code to look
> in which page I am and set the class="active". Sorry if this is not the
> correct mailing list to send this question but I don't know where to start
> looking so any information is welcome (for exemple if there is standard
> practice for this kind of things can someone give me some input?)
>
>
> sincerely
>
>
> L
>
> --
> 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/d3b54695-ecfd-afc6-26fc-0cb5adb5f31d%40lpn.cnrs.fr.
> For more options, visit https://groups.google.com/d/optout.



-- 

Cordialement, Coues Ludovic
+336 148 743 42

-- 
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/CAEuG%2BTYxvMUPs69DSU%2BHzxmu4iJAUcrt2pj4G8RN38Bsd7Kpdg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


template or javascript

2016-10-10 Thread Lorenzo Bernardi

Hello,

  I'm making a website with bootstrap and I use some menu items (in 
fact nav bars) and I was wondering what is the best practice to make a 
menu item highlighted when I am on the page connected with this menu 
item. I mean in bootstrap the nav bar has a  to 
highlight the fact that I'm on this page. I was wondering if I should 
use django context to give the information and set in the template {% if 
currentpage="home"  %} class="active" {% endif %} or if I should use 
some javascript code to look in which page I am and set the 
class="active". Sorry if this is not the correct mailing list to send 
this question but I don't know where to start looking so any information 
is welcome (for exemple if there is standard practice for this kind of 
things can someone give me some input?)



sincerely


L

--
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/d3b54695-ecfd-afc6-26fc-0cb5adb5f31d%40lpn.cnrs.fr.
For more options, visit https://groups.google.com/d/optout.


Re: Django app crashes with out of memory

2016-10-10 Thread James Schneider
On Mon, Oct 10, 2016 at 10:01 AM, Constantine Covtushenko <
constantine.covtushe...@gmail.com> wrote:

> Hi Dmitry,
>
> Please check that documentation page
> .
> As you can see iterator() loads all in the memory and after that returns
> an iterator.
>
> Try to fetch records say by 50 - 100 items.
>
> Hope that helps.
>
>
That's correct. The Queryset is evaluated (which means the entire result is
loaded into memory). The iterator() call only optimizes the access to the
result, not the result itself. 50 - 100 items may be a bit conservative
with the size of machine that you have, but it all depends on the size of
the objects and how utilized the server is. There is likely a point of
diminishing returns somewhere higher (probably in the thousands), but only
experimentation is going to help you find it.

I also wanted to draw attention to the note relating to DB caching, which
may be adding extra taxation on your server for large queryset results
(although I can't imagine a DB would try to cache a result that large
without specifically being tuned to do so).

Is there a reason this is run in a batch, rather than being performed
during the initial save() or an update() of the data? Seems like the
operation you are performing is pretty static and should be able to be
calculated as the data is created and/or updated. Might save you from
having to deal with this type of operation at all.

-James

-- 
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/CA%2Be%2BciWECBQxbxZwe60rNLoD0EMfM82Q4omu3w4KAj7wFzDEqw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django app crashes with out of memory

2016-10-10 Thread Constantine Covtushenko
Hi Dmitry,

Please check that documentation page
.
As you can see iterator() loads all in the memory and after that returns an
iterator.

Try to fetch records say by 50 - 100 items.

Hope that helps.

On Mon, Oct 10, 2016 at 2:14 PM, Горобец Дмитрий  wrote:

> Hello.
>
> Thanks for advices.
>
> Crash occures, when I run Django command through python manage.py
> my_command_name.
>
> It doesn't relate to nginx and even gunicorn, because, again, it's Django
> command, which I call from shell.
>
> I switched off redis caching (I use cacheops), but it' didn't help too.
>
> пятница, 7 октября 2016 г., 13:21:48 UTC+5 пользователь Горобец Дмитрий
> написал:
>
>> Hello.
>>
>> I have VPS with 2Gb RAM with django, gunicorn, mysql, nginx and redis.
>>
>> My app crashes with out of memory error, when I run django command on
>> model, which has approximately 7 million records. It takes each premise
>> object and updates one field by checking value with regular expression.
>> Please, help optimize that command.
>>
>> class Command(BaseCommand):
>> help = 'Updates premise.number_order'
>>
>> def handle(self, *args, **options):
>> for premise in Premise.objects.iterator():
>> premise.number_order = premise.set_number_order()
>> premise.save()
>>
>> self.stdout.write('Finished')
>>
>>
>> # Method of Premise model
>> def set_number_order(self):
>> tr = {
>> 'А': '.10',
>> 'A': '.10',
>> 'Б': '.20',
>> 'В': '.30',
>> 'Г': '.40',
>> 'Д': '.50',
>> 'Е': '.60',
>> 'Ж': '.70',
>> 'З': '.80',
>> 'И': '.90',
>> }
>>
>> only_digit = re.compile(r'^(?P[0-9]{1,9})$')
>> digit_with_separator = re.compile(r'^(?P[0-9]
>> {1,9})(?P[-|/])(?P\w+)$')
>> digit_with_letter = re.compile(r'^(?P[0-9]
>> {1,9})(?P[А-Яа-я]+)')
>> result = 0
>> title = self.title.strip().upper()
>>
>> if only_digit.match(title):
>> number = only_digit.match(title).group('number')
>> result = number + '.00'
>>
>> elif digit_with_separator.match(title):
>> number = digit_with_separator.match(title).group('number')
>> rest = digit_with_separator.match(title).group('rest')
>> if rest[0].isalpha():
>> floating = tr.get(rest[0], '.90')
>> result = number + floating
>>
>> elif rest[0].isdigit():
>> try:
>> if rest[1].isdigit():
>> result = number + '.{}'.format(rest[:2])
>> else:
>> result = number + '.0{}'.format(rest[0])
>> except IndexError:
>> result = number + '.0{}'.format(rest[0])
>>
>> elif digit_with_letter.match(title):
>> number = digit_with_letter.match(title).group('number')
>> letter = digit_with_letter.match(title).group('letter')[0]
>>
>> floating = tr.get(letter, '.90')
>> result = number + floating
>>
>> return Decimal(result)
>>
> --
> 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/2e87323c-294c-4b82-89dd-783e36e23291%40googlegroups.com
> 
> .
>
> 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/CAK52boUAy-8NfaoG8Hmvge2dNWps2baBc4tfHa0mOrV9MNEw8g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: model form does not work

2016-10-10 Thread ludovic coues
Most of the time, it help to provide the full stack trace that come
with the error. The one in the console where you started django should
be easier to copy and paste.

In your case, it look like a typo. In forms.py, it should be `class
Meta` and you wrote `class meta`.


An alternative is to use class based views. I wrote a few examples
covering the most useful case on stackoverflow [1]. For your code, it
boild down to replace the view with that:

from django.core.urlresolvers import reverse_lazy
from django.views.generic.edit import CreateView
from .models import Registerform

class RegisterView(CreateView):
template_name = "register.html"
model = Registerform
fields = ["FirstName", "LastName", "Myprofile", "Myresume",
"Bio", "State", "Country"]
success_url = reverse_lazy("app:views")

Then in your urls.py file, you use RegisterView.as_view() instead of
register. The RegisterView will take care of creating a form based on
the models, validating the data, saving the object in database,
handling get and post request.


[1] http://stackoverflow.com/documentation/django/1220/class-based-views

2016-10-10 11:16 GMT+02:00 prashant joshi :
> i created model form
>
>
>
>
> model.py
> from django.db import models
> from django.utils.encoding import python_2_unicode_compatible
> from django import forms
> from django.forms import ModelForm
>
>
>
> CATEGORIES = (
> ('mh', 'Maharashtra'),
> ('pb', 'Punjab'),
> ('gj', 'Gujarat'),
>
> )
> Country = (
> ('ind', 'India'),
> ('uk', 'United Kingdom'),
> ('sa', 'South Africa'),
>
> )
>
>
> class holidaytime(models.Model):
> MYdob= models.DateField()
> Time= models.DateTimeField()
> def __str__(self):
>  return self.name
> class Registerform(models.Model):
> FirstName = models.CharField(max_length=200)
> LastName = models.CharField(max_length=200)
> Myprofile = models.FileField(upload_to='uploads/')
> Myresume = models.FileField(upload_to='uploads/')
> Bio = models.TextField()
> State= models.CharField(max_length=3, choices=CATEGORIES)
> Country= models.CharField(max_length=3, choices=Country)
>
>
> def __str__(self):
>
>
>
>
>
>
>
>
> forms,py
>
> from django import forms
> from .models import Registerform
> from django.forms import ModelForm
>
> class Regform(forms.ModelForm):
> class meta:
> model=Registerform
>
> fields=["FirstName","LastName","Myprofile","Myresume","Bio","State","Country"]
>  return self.name
>
>
>
> views.py
>
>
> from django.shortcuts import render
> from .forms import Regform
> # Create your views here.
> def register(request):
> s=Regform(request.POST)
> return render(request, 'webpage/register.html',{"s":s})
>
>
>
> register.html
> 
> 
> 
> Registration Form
> 
> 
> Registration Form
> {% csrf_token %}
> {{form.as_p}}
> 
>
> 
> 
>
>
>
>
> it is not worked..it show
>
> ValueError at /task/
>
> ModelForm has no model class specified. this error
>
>
>
>
>
> --
> 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/6d5714b1-c526-4851-a6c9-4700498fc579%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



-- 

Cordialement, Coues Ludovic
+336 148 743 42

-- 
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/CAEuG%2BTaJHFQSi8pmm9mKMBEr_89KK4T%2B%3DJJpQbH_oqjSjScx%3DQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django app crashes with out of memory

2016-10-10 Thread Горобец Дмитрий
Hello. 

Thanks for advices. 

Crash occures, when I run Django command through python manage.py 
my_command_name.

It doesn't relate to nginx and even gunicorn, because, again, it's Django 
command, which I call from shell.

I switched off redis caching (I use cacheops), but it' didn't help too.

пятница, 7 октября 2016 г., 13:21:48 UTC+5 пользователь Горобец Дмитрий 
написал:
>
> Hello.
>
> I have VPS with 2Gb RAM with django, gunicorn, mysql, nginx and redis. 
>
> My app crashes with out of memory error, when I run django command on 
> model, which has approximately 7 million records. It takes each premise 
> object and updates one field by checking value with regular expression. 
> Please, help optimize that command.
>
> class Command(BaseCommand):
> help = 'Updates premise.number_order'
>
> def handle(self, *args, **options):
> for premise in Premise.objects.iterator():
> premise.number_order = premise.set_number_order()
> premise.save()
>
> self.stdout.write('Finished')
>
>
> # Method of Premise model
> def set_number_order(self):
> tr = {
> 'А': '.10',
> 'A': '.10',
> 'Б': '.20',
> 'В': '.30',
> 'Г': '.40',
> 'Д': '.50',
> 'Е': '.60',
> 'Ж': '.70',
> 'З': '.80',
> 'И': '.90',
> }
>
> only_digit = re.compile(r'^(?P[0-9]{1,9})$')
> digit_with_separator = 
> re.compile(r'^(?P[0-9]{1,9})(?P[-|/])(?P\w+)$')
> digit_with_letter = 
> re.compile(r'^(?P[0-9]{1,9})(?P[А-Яа-я]+)')
> result = 0
> title = self.title.strip().upper()
>
> if only_digit.match(title):
> number = only_digit.match(title).group('number')
> result = number + '.00'
>
> elif digit_with_separator.match(title):
> number = digit_with_separator.match(title).group('number')
> rest = digit_with_separator.match(title).group('rest')
> if rest[0].isalpha():
> floating = tr.get(rest[0], '.90')
> result = number + floating
>
> elif rest[0].isdigit():
> try:
> if rest[1].isdigit():
> result = number + '.{}'.format(rest[:2])
> else:
> result = number + '.0{}'.format(rest[0])
> except IndexError:
> result = number + '.0{}'.format(rest[0])
>
> elif digit_with_letter.match(title):
> number = digit_with_letter.match(title).group('number')
> letter = digit_with_letter.match(title).group('letter')[0]
>
> floating = tr.get(letter, '.90')
> result = number + floating
>
> return Decimal(result)
>

-- 
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/2e87323c-294c-4b82-89dd-783e36e23291%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


model form does not work

2016-10-10 Thread prashant joshi
i created model form




model.py
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django import forms
from django.forms import ModelForm



CATEGORIES = (  
('mh', 'Maharashtra'),
('pb', 'Punjab'),
('gj', 'Gujarat'),

)
Country = (  
('ind', 'India'),
('uk', 'United Kingdom'),
('sa', 'South Africa'),

)


class holidaytime(models.Model):
MYdob= models.DateField()
Time= models.DateTimeField()
def __str__(self):
 return self.name
class Registerform(models.Model):
FirstName = models.CharField(max_length=200)
LastName = models.CharField(max_length=200)
Myprofile = models.FileField(upload_to='uploads/')
Myresume = models.FileField(upload_to='uploads/')
Bio = models.TextField()
State= models.CharField(max_length=3, choices=CATEGORIES)
Country= models.CharField(max_length=3, choices=Country)


def __str__(self):








forms,py

from django import forms
from .models import Registerform
from django.forms import ModelForm

class Regform(forms.ModelForm):
class meta:
model=Registerform

fields=["FirstName","LastName","Myprofile","Myresume","Bio","State","Country"]
 return self.name



views.py


from django.shortcuts import render
from .forms import Regform
# Create your views here.
def register(request):
s=Regform(request.POST)
return render(request, 'webpage/register.html',{"s":s})



register.html



Registration Form


Registration Form
{% csrf_token %}
{{form.as_p}}








it is not worked..it show
ValueError at /task/ 

ModelForm has no model class specified. this error





-- 
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/6d5714b1-c526-4851-a6c9-4700498fc579%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Extracting results of a join

2016-10-10 Thread Sanjay Bhangar
On Mon, Oct 10, 2016 at 12:56 PM, Geoff Kuenning  wrote:

>
>
> So is there a way to get Django to issue this join and collect the
> results into an aggregate set?  I've read through the docs and
> experimented with different filter and double-underscore notations,
> without success.  It seems silly to do the work with a loop when a
> correctly written join can do it so much faster.  (And I'll note that if
> AlbumOrder had more entries, the loop would take far longer.)
>
>
Hi Geoff,

Have you looked at the docs for `select_related` and `prefetch_related`? It
sounds like they maybe what you're looking for here:

https://docs.djangoproject.com/en/1.10/ref/models/querysets/#select-related

So your example query:

> for photo in photos.filter(albumorder__album = album.key):
photo.ordering = photo.albumorder_set.filter(album = album.key)

Would be something like `for photo in photos.filter(albumorder__album =
album.key).select_related('albumorder'): ...`

You need to tell Django which related tables to include in the initial SQL
query, and select_related and prefetch_related accomplish this, in subtly
different ways (will let you read the docs to figure that out since I
haven't quite myself ;-) )

Hope this helps! select_related has gotten me out of many DB optimization
issues in the past and now I'll never ship code without carefully examining
where all using a `select_related` would significantly speed up queries.

-Sanjay

-- 
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/CAG3W7ZEWsyZ4pdtURVXiRummSpOMkHHZSOte--3FrrM2VX7XxQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Extracting results of a join

2016-10-10 Thread Geoff Kuenning
I have a table, Photos, which contains pretty much what you'd expect.  A
second table, Albums, contains a field named "key", a title, and other
information.  The two are related by a ManyToManyField through
AlbumMembers, which relates the photo ID to the album key ("album").  I
mention AlbumMembers for completeness; it doesn't enter into this
question.

Finally, I have a very sparse table, AlbumOrder, which contains a photo
(ID) and a numeric "order" field.  That table has only 44 rows total, 22
for the album I'm testing with.

When I need to collect a list of photos and their order fields (when
specified) I first select the photos from an album into a query set
named "photos" and then use code somewhat like this (I've removed some
error checking that's not relevant here):

for photo in photos.filter(albumorder__album = album.key):
photo.ordering = photo.albumorder_set.filter(album = album.key)

I've timed this code, and for a large album with 65K photos it takes
several seconds to complete.  I presume that the problem is that each
filtration inside the loop needs a separate interaction with the SQL
server.

On the other hand, I can pick up the same information in SQL with a join:

SELECT photos.id, `order`, album FROM photos LEFT JOIN album_order ON 
album_order.photo = photos.id WHERE album = '' OR album IS NULL;

That takes only 0.27 seconds even including the time needed to output
65K lines to the screen.

So is there a way to get Django to issue this join and collect the
results into an aggregate set?  I've read through the docs and
experimented with different filter and double-underscore notations,
without success.  It seems silly to do the work with a loop when a
correctly written join can do it so much faster.  (And I'll note that if
AlbumOrder had more entries, the loop would take far longer.)

(I've thought about issuing the join directly from my code and reading
from a database cursor, but that seems un-Djangoish.)
-- 
Geoff Kuenning   ge...@cs.hmc.edu   http://www.cs.hmc.edu/~geoff/

Software, like bridges, should be elegant and visually pleasing as
well as functional.  Ugly constructs, designs, and languages should be
avoided like the plague.

-- 
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/pni37k44qcg.fsf%40bow.cs.hmc.edu.
For more options, visit https://groups.google.com/d/optout.