code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F, Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M, Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.1667, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.4444, 0.0556, 0, 0...
[ "DATE_FORMAT = 'j F, Y'", "TIME_FORMAT = 'g:i:s A'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'j M, Y'", "DECIMAL_SEPARATOR = '.'", "THOUSAND_SEPARATOR = ','" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'Y-m-d' SHORT_DATETIME_FORMAT = 'Y-m-d H:i' FIRST_DAY_OF_WEEK = 1 DATE_INPUT_FORMATS = ( '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y', # '10/25/06' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1429, 0.0286, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1714, 0.0286, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2, 0.0286, 0, 0.66...
[ "DATE_FORMAT = 'j F Y'", "TIME_FORMAT = 'H:i'", "DATETIME_FORMAT = 'j F Y H:i'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'Y-m-d'", "SHORT_DATETIME_FORMAT = 'Y-m-d H:i'", "FIRST_DAY_OF_WEEK = 1", "DATE_INPUT_FORMATS = (\n '%Y-%m-%d', # '2006-10-25...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # DATE_FORMAT = # TIME_FORMAT = # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = # MONTH_DAY_FORMAT = # SHORT_DATE_FORMAT = # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
[]
[]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = r'\N\gà\y d \t\há\n\g n \nă\m Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = r'H:i:s \N\gà\y d \t\há\n\g n \nă\m Y' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'H:i:s d-m-Y' # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.125, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3889, 0.0556, 0, 0....
[ "DATE_FORMAT = r'\\N\\gà\\y d \\t\\há\\n\\g n \\nă\\m Y'", "TIME_FORMAT = 'H:i:s'", "DATETIME_FORMAT = r'H:i:s \\N\\gà\\y d \\t\\há\\n\\g n \\nă\\m Y'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'd-m-Y'", "SHORT_DATETIME_FORMAT = 'H:i:s d-m-Y'", "DECIMAL_SEPARATOR =...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'N j, Y' TIME_FORMAT = 'P' DATETIME_FORMAT = 'N j, Y, P' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'F j' SHORT_DATE_FORMAT = 'm/d/Y' SHORT_DATETIME_FORMAT = 'm/d/Y P' FIRST_DAY_OF_WEEK = 0 # Sunday DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1316, 0.0263, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1579, 0.0263, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1842, 0.0263, 0, 0...
[ "DATE_FORMAT = 'N j, Y'", "TIME_FORMAT = 'P'", "DATETIME_FORMAT = 'N j, Y, P'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'F j'", "SHORT_DATE_FORMAT = 'm/d/Y'", "SHORT_DATETIME_FORMAT = 'm/d/Y P'", "FIRST_DAY_OF_WEEK = 0 # Sunday", "DATE_INPUT_FORMATS = (\n '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j. F Y H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i:s' FIRST_DAY_OF_WEEK = 1 # Monday DATE_INPUT_FORMATS = ( '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06' '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25' # '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1562, 0.0312, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1875, 0.0312, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2188, 0.0312, 0, 0...
[ "DATE_FORMAT = 'j. F Y'", "TIME_FORMAT = 'H:i:s'", "DATETIME_FORMAT = 'j. F Y H:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'd.m.Y'", "SHORT_DATETIME_FORMAT = 'd.m.Y H:i:s'", "FIRST_DAY_OF_WEEK = 1 # Monday", "DATE_INPUT_FORMATS = (\n '%d.%m.%Y', '%d.%m.%...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j ខែ F ឆ្នាំ Y' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'j ខែ F ឆ្នាំ Y, G:i:s' # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' SHORT_DATETIME_FORMAT = 'j M Y, G:i:s' # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.1429, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3889, 0.0556, 0, 0...
[ "DATE_FORMAT = 'j ខែ F ឆ្នាំ Y'", "TIME_FORMAT = 'G:i:s'", "DATETIME_FORMAT = 'j ខែ F ឆ្នាំ Y, G:i:s'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'j M Y'", "SHORT_DATETIME_FORMAT = 'j M Y, G:i:s'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = '.'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = r'j \de F \de Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = r'j \de F \de Y à\s H:i' YEAR_MONTH_FORMAT = r'F \de Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 0 # Sunday DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%d/%m/%Y', '%d/%m/%y', # '2006-10-25', '25/10/2006', '25/10/06' # '%d de %b de %Y', '%d de %b, %Y', # '25 de Out de 2006', '25 Out, 2006' # '%d de %B de %Y', '%d de %B, %Y', # '25 de Outubro de 2006', '25 de Outubro, 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%d/%m/%y', # '25/10/06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1429, 0.0286, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1714, 0.0286, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2, 0.0286, 0, 0.66...
[ "DATE_FORMAT = r'j \\de F \\de Y'", "TIME_FORMAT = 'H:i:s'", "DATETIME_FORMAT = r'j \\de F \\de Y à\\s H:i'", "YEAR_MONTH_FORMAT = r'F \\de Y'", "MONTH_DAY_FORMAT = r'j \\de F'", "SHORT_DATE_FORMAT = 'd/m/Y'", "SHORT_DATETIME_FORMAT = 'd/m/Y H:i'", "FIRST_DAY_OF_WEEK = 0 # Sunday", "DATE_INPUT_FORM...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j. F Y.' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j. F Y. H:i' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y.' SHORT_DATETIME_FORMAT = 'j.m.Y. H:i' FIRST_DAY_OF_WEEK = 1 DATE_INPUT_FORMATS = ( '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y.', '%d.%m.%y.', # '25.10.2006.', '25.10.06.' '%d. %m. %Y.', '%d. %m. %y.', # '25. 10. 2006.', '25. 10. 06.' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' '%d.%m.%Y.', # '25.10.2006.' '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' '%d.%m.%y. %H:%M', # '25.10.06. 14:30' '%d.%m.%y.', # '25.10.06.' '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' '%d. %m. %Y.', # '25. 10. 2006.' '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' '%d. %m. %y.', # '25. 10. 06.' ) DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
[ [ 14, 0, 0.119, 0.0238, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1429, 0.0238, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1667, 0.0238, 0, 0....
[ "DATE_FORMAT = 'j. F Y.'", "TIME_FORMAT = 'H:i:s'", "DATETIME_FORMAT = 'j. F Y. H:i'", "YEAR_MONTH_FORMAT = 'F Y.'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'j.m.Y.'", "SHORT_DATETIME_FORMAT = 'j.m.Y. H:i'", "FIRST_DAY_OF_WEEK = 1", "DATE_INPUT_FORMATS = (\n '%Y-%m-%d', ...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F، Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd‏/m‏/Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.1667, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.4444, 0.0556, 0, 0...
[ "DATE_FORMAT = 'j F، Y'", "TIME_FORMAT = 'g:i:s A'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'd‏/m‏/Y'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = '.'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F Y' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'j F Y, G:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' SHORT_DATETIME_FORMAT = 'j M Y, G:i:s' # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.125, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3889, 0.0556, 0, 0....
[ "DATE_FORMAT = 'j F Y'", "TIME_FORMAT = 'G:i:s'", "DATETIME_FORMAT = 'j F Y, G:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'j M Y'", "SHORT_DATETIME_FORMAT = 'j M Y, G:i:s'", "DECIMAL_SEPARATOR = '.'", "THOUSAND_SEPARATOR = ','" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 DATE_INPUT_FORMATS = ( '%d.%m.%Y', # '25.10.2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1923, 0.0385, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2308, 0.0385, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2692, 0.0385, 0, 0...
[ "DATE_FORMAT = 'j. F Y'", "TIME_FORMAT = 'H:i'", "DATETIME_FORMAT = 'j. F Y H:i'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'd.m.Y'", "SHORT_DATETIME_FORMAT = 'd.m.Y H:i'", "FIRST_DAY_OF_WEEK = 1", "DATE_INPUT_FORMATS = (\n '%d.%m.%Y', ...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = r'Y. \g\a\d\a j. F' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = r'Y. \g\a\d\a j. F, H:i:s' YEAR_MONTH_FORMAT = r'Y. \g. F' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = r'j.m.Y' SHORT_DATETIME_FORMAT = 'j.m.Y H:i:s' FIRST_DAY_OF_WEEK = 1 #Monday DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' '%H.%M.%S', # '14.30.59' '%H.%M', # '14.30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y %H.%M.%S', # '25.10.06 14.30.59' '%d.%m.%y %H.%M', # '25.10.06 14.30' '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1389, 0.0278, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1667, 0.0278, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1944, 0.0278, 0, 0...
[ "DATE_FORMAT = r'Y. \\g\\a\\d\\a j. F'", "TIME_FORMAT = 'H:i:s'", "DATETIME_FORMAT = r'Y. \\g\\a\\d\\a j. F, H:i:s'", "YEAR_MONTH_FORMAT = r'Y. \\g. F'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = r'j.m.Y'", "SHORT_DATETIME_FORMAT = 'j.m.Y H:i:s'", "FIRST_DAY_OF_WEEK = 1 #Monday", "DATE_INPUT...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'N j, Y' # 'Oct. 25, 2006' TIME_FORMAT = 'P' # '2:30 pm' DATETIME_FORMAT = 'N j, Y, P' # 'Oct. 25, 2006, 2:30 pm' YEAR_MONTH_FORMAT = 'F Y' # 'October 2006' MONTH_DAY_FORMAT = 'F j' # 'October 25' SHORT_DATE_FORMAT = 'd/m/Y' # '25/10/2006' SHORT_DATETIME_FORMAT = 'd/m/Y P' # '25/10/2006 2:30 pm' FIRST_DAY_OF_WEEK = 0 # Sunday DATE_INPUT_FORMATS = ( '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' '%Y-%m-%d', # '2006-10-25' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%d/%m/%y', # '25/10/06' ) DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1282, 0.0256, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1538, 0.0256, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1795, 0.0256, 0, 0...
[ "DATE_FORMAT = 'N j, Y' # 'Oct. 25, 2006'", "TIME_FORMAT = 'P' # '2:30 pm'", "DATETIME_FORMAT = 'N j, Y, P' # 'Oct. 25, 2006, 2:30 pm'", "YEAR_MONTH_FORMAT = 'F Y' # 'October 2006'", "MONTH_DAY_FORMAT = 'F j' # 'October 25'", "S...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = r'Y \m. F j \d.' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = # MONTH_DAY_FORMAT = SHORT_DATE_FORMAT = 'Y.m.d' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.25, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.5556, 0.0556, 0, 0.6...
[ "DATE_FORMAT = r'Y \\m. F j \\d.'", "TIME_FORMAT = 'H:i:s'", "SHORT_DATE_FORMAT = 'Y.m.d'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = '.'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'd F Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.1667, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.4444, 0.0556, 0, 0...
[ "DATE_FORMAT = 'd F Y'", "TIME_FORMAT = 'g:i:s A'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'd M Y'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = '.'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'j. F Y G:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y G:i:s' FIRST_DAY_OF_WEEK = 1 # Monday DATE_INPUT_FORMATS = ( '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06' '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25' # '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1562, 0.0312, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1875, 0.0312, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2188, 0.0312, 0, 0...
[ "DATE_FORMAT = 'j. F Y'", "TIME_FORMAT = 'G:i:s'", "DATETIME_FORMAT = 'j. F Y G:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'd.m.Y'", "SHORT_DATETIME_FORMAT = 'd.m.Y G:i:s'", "FIRST_DAY_OF_WEEK = 1 # Monday", "DATE_INPUT_FORMATS = (\n '%d.%m.%Y', '%d.%m.%...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F Y г.' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'j F Y г. G:i:s' YEAR_MONTH_FORMAT = 'F Y г.' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday DATE_INPUT_FORMATS = ( '%d.%m.%Y', # '25.10.2006' '%d.%m.%y', # '25.10.06' '%Y-%m-%d', # '2006-10-25' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y', # '25.10.06' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1429, 0.0286, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1714, 0.0286, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2, 0.0286, 0, 0.66...
[ "DATE_FORMAT = 'j F Y г.'", "TIME_FORMAT = 'G:i:s'", "DATETIME_FORMAT = 'j F Y г. G:i:s'", "YEAR_MONTH_FORMAT = 'F Y г.'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'd.m.Y'", "SHORT_DATETIME_FORMAT = 'd.m.Y H:i'", "FIRST_DAY_OF_WEEK = 1 # Monday", "DATE_INPUT_FORMATS = (\n '%d.%m.%Y', # ...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'N j, Y' TIME_FORMAT = 'P' DATETIME_FORMAT = 'N j, Y, P' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'F j' SHORT_DATE_FORMAT = 'm/d/Y' SHORT_DATETIME_FORMAT = 'm/d/Y P' FIRST_DAY_OF_WEEK = 0 # Sunday DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1316, 0.0263, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1579, 0.0263, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1842, 0.0263, 0, 0...
[ "DATE_FORMAT = 'N j, Y'", "TIME_FORMAT = 'P'", "DATETIME_FORMAT = 'N j, Y, P'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'F j'", "SHORT_DATE_FORMAT = 'm/d/Y'", "SHORT_DATETIME_FORMAT = 'm/d/Y P'", "FIRST_DAY_OF_WEEK = 0 # Sunday", "DATE_INPUT_FORMATS = (\n '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j. F Y.' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y. H:i' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y.' SHORT_DATETIME_FORMAT = 'j.m.Y. H:i' FIRST_DAY_OF_WEEK = 1 DATE_INPUT_FORMATS = ( '%d.%m.%Y.', '%d.%m.%y.', # '25.10.2006.', '25.10.06.' '%d. %m. %Y.', '%d. %m. %y.', # '25. 10. 2006.', '25. 10. 06.' '%Y-%m-%d', # '2006-10-25' # '%d. %b %y.', '%d. %B %y.', # '25. Oct 06.', '25. October 06.' # '%d. %b \'%y.', '%d. %B \'%y.', # '25. Oct '06.', '25. October '06.' # '%d. %b %Y.', '%d. %B %Y.', # '25. Oct 2006.', '25. October 2006.' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' '%d.%m.%Y.', # '25.10.2006.' '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' '%d.%m.%y. %H:%M', # '25.10.06. 14:30' '%d.%m.%y.', # '25.10.06.' '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' '%d. %m. %Y.', # '25. 10. 2006.' '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' '%d. %m. %y.', # '25. 10. 06.' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1136, 0.0227, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1364, 0.0227, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1591, 0.0227, 0, 0...
[ "DATE_FORMAT = 'j. F Y.'", "TIME_FORMAT = 'H:i'", "DATETIME_FORMAT = 'j. F Y. H:i'", "YEAR_MONTH_FORMAT = 'F Y.'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'j.m.Y.'", "SHORT_DATETIME_FORMAT = 'j.m.Y. H:i'", "FIRST_DAY_OF_WEEK = 1", "DATE_INPUT_FORMATS = (\n '%d.%m.%Y.', '%d.%m.%y.', ...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = r'j \de F \de Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = r'j \de F \de Y \a \l\a\s H:i' YEAR_MONTH_FORMAT = r'F \de Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday DATE_INPUT_FORMATS = ( # '31/12/2009', '31/12/09' '%d/%m/%Y', '%d/%m/%y' ) TIME_INPUT_FORMATS = ( # '14:30:59', '14:30' '%H:%M:%S', '%H:%M' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M', ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1667, 0.0333, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2, 0.0333, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2333, 0.0333, 0, 0.66...
[ "DATE_FORMAT = r'j \\de F \\de Y'", "TIME_FORMAT = 'H:i:s'", "DATETIME_FORMAT = r'j \\de F \\de Y \\a \\l\\a\\s H:i'", "YEAR_MONTH_FORMAT = r'F \\de Y'", "MONTH_DAY_FORMAT = r'j \\de F'", "SHORT_DATE_FORMAT = 'd/m/Y'", "SHORT_DATETIME_FORMAT = 'd/m/Y H:i'", "FIRST_DAY_OF_WEEK = 1 # Monday", "DATE_IN...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.2, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.5, 0.0556, 0, 0.66, ...
[ "DATE_FORMAT = 'j F Y'", "TIME_FORMAT = 'H:i:s'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'j M Y'", "DECIMAL_SEPARATOR = '.'", "THOUSAND_SEPARATOR = ','" ]
DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%j.%m.%Y', '%j.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' '%Y-%m-%j', # '2006-10-25', # '%j. %b %Y', '%j %b %Y', # '25. okt 2006', '25 okt 2006' # '%j. %b. %Y', '%j %b. %Y', # '25. okt. 2006', '25 okt. 2006' # '%j. %B %Y', '%j %B %Y', # '25. oktober 2006', '25 oktober 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%Y-%m-%j', # '2006-10-25' '%j.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%j.%m.%Y %H:%M', # '25.10.2006 14:30' '%j.%m.%Y', # '25.10.2006' '%j.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%j.%m.%y %H:%M', # '25.10.06 14:30' '%j.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
[ [ 14, 0, 0.0294, 0.0294, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0588, 0.0294, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0882, 0.0294, 0, 0...
[ "DATE_FORMAT = 'j. F Y'", "TIME_FORMAT = 'H:i'", "DATETIME_FORMAT = 'j. F Y H:i'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'd.m.Y'", "SHORT_DATETIME_FORMAT = 'd.m.Y H:i'", "FIRST_DAY_OF_WEEK = 1 # Monday", "DATE_INPUT_FORMATS = (\n '%Y-%m-%d', '%j.%m.%Y', '%...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'l, j F, Y' TIME_FORMAT = 'h:i:s a' DATETIME_FORMAT = 'j F, Y h:i:s a' YEAR_MONTH_FORMAT = 'F, Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j.M.Y' SHORT_DATETIME_FORMAT = 'j.M.Y H:i:s' FIRST_DAY_OF_WEEK = 1 # (Monday) DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' # '%d %b %Y', '%d %b, %Y', '%d %b. %Y', # '25 Oct 2006', '25 Oct, 2006', '25 Oct. 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' # '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y', # '25.10.06' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = " " NUMBER_GROUPING = 3
[ [ 14, 0, 0.119, 0.0238, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1429, 0.0238, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1667, 0.0238, 0, 0....
[ "DATE_FORMAT = 'l, j F, Y'", "TIME_FORMAT = 'h:i:s a'", "DATETIME_FORMAT = 'j F, Y h:i:s a'", "YEAR_MONTH_FORMAT = 'F, Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'j.M.Y'", "SHORT_DATETIME_FORMAT = 'j.M.Y H:i:s'", "FIRST_DAY_OF_WEEK = 1 # (Monday)", "DATE_INPUT_FORMATS = (\n '%Y-%m-%d',...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j F Y H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j N Y' SHORT_DATETIME_FORMAT = 'j N Y H:i:s' FIRST_DAY_OF_WEEK = 1 # Monday DATE_INPUT_FORMATS = ( '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' '%d.%m.%Y', '%d.%m.%y', # Swiss (fr_CH), '25.10.2006', '25.10.06' '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25' # '%d %B %Y', '%d %b %Y', # '25 octobre 2006', '25 oct. 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d.%m.%Y %H:%M:%S', # Swiss (fr_CH), '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # Swiss (fr_CH), '25.10.2006 14:30' '%d.%m.%Y', # Swiss (fr_CH), '25.10.2006' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1389, 0.0278, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1667, 0.0278, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1944, 0.0278, 0, 0...
[ "DATE_FORMAT = 'j F Y'", "TIME_FORMAT = 'H:i:s'", "DATETIME_FORMAT = 'j F Y H:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'j N Y'", "SHORT_DATETIME_FORMAT = 'j N Y H:i:s'", "FIRST_DAY_OF_WEEK = 1 # Monday", "DATE_INPUT_FORMATS = (\n '%d/%m/%Y', '%d/%m/%y',...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = r'j N Y' TIME_FORMAT = r'H:i:s' DATETIME_FORMAT = r'j N Y H:i:s' YEAR_MONTH_FORMAT = r'F Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = r'd/m/Y' SHORT_DATETIME_FORMAT = r'd/m/Y H:i' FIRST_DAY_OF_WEEK = 0 # 0: Sunday, 1: Monday DATE_INPUT_FORMATS = ( '%d/%m/%Y', # '31/12/2009' '%d/%m/%y', # '31/12/09' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M', ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1724, 0.0345, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2069, 0.0345, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2414, 0.0345, 0, 0...
[ "DATE_FORMAT = r'j N Y'", "TIME_FORMAT = r'H:i:s'", "DATETIME_FORMAT = r'j N Y H:i:s'", "YEAR_MONTH_FORMAT = r'F Y'", "MONTH_DAY_FORMAT = r'j \\de F'", "SHORT_DATE_FORMAT = r'd/m/Y'", "SHORT_DATETIME_FORMAT = r'd/m/Y H:i'", "FIRST_DAY_OF_WEEK = 0 # 0: Sunday, 1: Monday", "DATE_INPUT_FORMATS = (\n ...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j. F Y.' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y. H:i' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y.' SHORT_DATETIME_FORMAT = 'j.m.Y. H:i' FIRST_DAY_OF_WEEK = 1 DATE_INPUT_FORMATS = ( '%d.%m.%Y.', '%d.%m.%y.', # '25.10.2006.', '25.10.06.' '%d. %m. %Y.', '%d. %m. %y.', # '25. 10. 2006.', '25. 10. 06.' '%Y-%m-%d', # '2006-10-25' # '%d. %b %y.', '%d. %B %y.', # '25. Oct 06.', '25. October 06.' # '%d. %b \'%y.', '%d. %B \'%y.', # '25. Oct '06.', '25. October '06.' # '%d. %b %Y.', '%d. %B %Y.', # '25. Oct 2006.', '25. October 2006.' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' '%d.%m.%Y.', # '25.10.2006.' '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' '%d.%m.%y. %H:%M', # '25.10.06. 14:30' '%d.%m.%y.', # '25.10.06.' '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' '%d. %m. %Y.', # '25. 10. 2006.' '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' '%d. %m. %y.', # '25. 10. 06.' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1136, 0.0227, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1364, 0.0227, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1591, 0.0227, 0, 0...
[ "DATE_FORMAT = 'j. F Y.'", "TIME_FORMAT = 'H:i'", "DATETIME_FORMAT = 'j. F Y. H:i'", "YEAR_MONTH_FORMAT = 'F Y.'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'j.m.Y.'", "SHORT_DATETIME_FORMAT = 'j.m.Y. H:i'", "FIRST_DAY_OF_WEEK = 1", "DATE_INPUT_FORMATS = (\n '%d.%m.%Y.', '%d.%m.%y.', ...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F, Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M, Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.3333, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.5, 0.0556, 0, 0.66...
[ "DATE_FORMAT = 'j F, Y'", "TIME_FORMAT = 'g:i:s A'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'j M, Y'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.3333, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.5, 0.0556, 0, 0.66...
[ "DATE_FORMAT = 'j F Y'", "TIME_FORMAT = 'g:i:s A'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'j M Y'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = r'j \de N \de Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = r'j \de N \de Y à\s H:i' YEAR_MONTH_FORMAT = r'F \de Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 0 # Sunday DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%d/%m/%Y', '%d/%m/%y', # '2006-10-25', '25/10/2006', '25/10/06' # '%d de %b de %Y', '%d de %b, %Y', # '25 de Out de 2006', '25 Out, 2006' # '%d de %B de %Y', '%d de %B, %Y', # '25 de Outubro de 2006', '25 de Outubro, 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%d/%m/%y', # '25/10/06' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1429, 0.0286, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1714, 0.0286, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2, 0.0286, 0, 0.66...
[ "DATE_FORMAT = r'j \\de N \\de Y'", "TIME_FORMAT = 'H:i'", "DATETIME_FORMAT = r'j \\de N \\de Y à\\s H:i'", "YEAR_MONTH_FORMAT = r'F \\de Y'", "MONTH_DAY_FORMAT = r'j \\de F'", "SHORT_DATE_FORMAT = 'd/m/Y'", "SHORT_DATETIME_FORMAT = 'd/m/Y H:i'", "FIRST_DAY_OF_WEEK = 0 # Sunday", "DATE_INPUT_FORMAT...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.2, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.5, 0.0556, 0, 0.66, ...
[ "DATE_FORMAT = 'j F Y'", "TIME_FORMAT = 'g:i:s A'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'd-m-Y'", "DECIMAL_SEPARATOR = '.'", "THOUSAND_SEPARATOR = ','" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F Y р.' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.1667, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.4444, 0.0556, 0, 0...
[ "DATE_FORMAT = 'j F Y р.'", "TIME_FORMAT = 'H:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'j M Y'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = ' '" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'G.i.s' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.n.Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.1667, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.4444, 0.0556, 0, 0...
[ "DATE_FORMAT = 'j. F Y'", "TIME_FORMAT = 'G.i.s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'j.n.Y'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = ' '" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'Y年n月j日' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'Y年n月j日G:i:s' YEAR_MONTH_FORMAT = 'Y年n月' MONTH_DAY_FORMAT = 'n月j日' SHORT_DATE_FORMAT = 'Y/m/d' SHORT_DATETIME_FORMAT = 'Y/m/d G:i:s' # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.125, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3889, 0.0556, 0, 0....
[ "DATE_FORMAT = 'Y年n月j日'", "TIME_FORMAT = 'G:i:s'", "DATETIME_FORMAT = 'Y年n月j日G:i:s'", "YEAR_MONTH_FORMAT = 'Y年n月'", "MONTH_DAY_FORMAT = 'n月j日'", "SHORT_DATE_FORMAT = 'Y/m/d'", "SHORT_DATETIME_FORMAT = 'Y/m/d G:i:s'", "DECIMAL_SEPARATOR = '.'", "THOUSAND_SEPARATOR = ','" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F Y' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'j F Y، ساعت G:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'Y/n/j' SHORT_DATETIME_FORMAT = 'Y/n/j،‏ G:i:s' # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.125, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3889, 0.0556, 0, 0....
[ "DATE_FORMAT = 'j F Y'", "TIME_FORMAT = 'G:i:s'", "DATETIME_FORMAT = 'j F Y، ساعت G:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'Y/n/j'", "SHORT_DATETIME_FORMAT = 'Y/n/j،‏ G:i:s'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = '.'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = r'Yeko M\re\n d\a' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = # MONTH_DAY_FORMAT = SHORT_DATE_FORMAT = 'Y M j' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.25, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.5556, 0.0556, 0, 0.6...
[ "DATE_FORMAT = r'Yeko M\\re\\n d\\a'", "TIME_FORMAT = 'H:i:s'", "SHORT_DATE_FORMAT = 'Y M j'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = '.'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j F Y, H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y, H:i:s' # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.125, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3889, 0.0556, 0, 0....
[ "DATE_FORMAT = 'j F Y'", "TIME_FORMAT = 'H:i:s'", "DATETIME_FORMAT = 'j F Y, H:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'd.m.Y'", "SHORT_DATETIME_FORMAT = 'd.m.Y, H:i:s'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = '.'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j F Y H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s' FIRST_DAY_OF_WEEK = 1 # Monday DATE_INPUT_FORMATS = ( '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06' '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25' # '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1562, 0.0312, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1875, 0.0312, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2188, 0.0312, 0, 0...
[ "DATE_FORMAT = 'j F Y'", "TIME_FORMAT = 'H:i:s'", "DATETIME_FORMAT = 'j F Y H:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'd-m-Y'", "SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s'", "FIRST_DAY_OF_WEEK = 1 # Monday", "DATE_INPUT_FORMATS = (\n '%d.%m.%Y', '%d.%m.%y'...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'd F Y' TIME_FORMAT = 'g.i.s.A' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'Y-m-d' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.1667, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.4444, 0.0556, 0, 0...
[ "DATE_FORMAT = 'd F Y'", "TIME_FORMAT = 'g.i.s.A'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'Y-m-d'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = '.'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j N Y' DATETIME_FORMAT = "j N Y, G:i:s" TIME_FORMAT = 'G:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'd-m-Y G:i:s' FIRST_DAY_OF_WEEK = 1 #Monday DATE_INPUT_FORMATS = ( '%d-%m-%y', '%d/%m/%y', # '25-10-09' , 25/10/09' '%d-%m-%Y', '%d/%m/%Y', # '25-10-2009' , 25/10/2009' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d-%m-%Y %H:%M:%S', # '25-10-2009 14:30:59' '%d-%m-%Y %H:%M', # '25-10-2009 14:30' '%d-%m-%Y', # '25-10-2009' '%d-%m-%y %H:%M:%S', # '25-10-09' 14:30:59' '%d-%m-%y %H:%M', # '25-10-09' 14:30' '%d-%m-%y', # '25-10-09'' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' '%m/%d/%Y %H:%M:%S', # '25/10/2009 14:30:59' '%m/%d/%Y %H:%M', # '25/10/2009 14:30' '%m/%d/%Y', # '10/25/2009' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1163, 0.0233, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1395, 0.0233, 0, 0.66, 0.0769, 146, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1628, 0.0233, 0, 0...
[ "DATE_FORMAT = 'j N Y'", "DATETIME_FORMAT = \"j N Y, G:i:s\"", "TIME_FORMAT = 'G:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'd-m-Y'", "SHORT_DATETIME_FORMAT = 'd-m-Y G:i:s'", "FIRST_DAY_OF_WEEK = 1 #Monday", "DATE_INPUT_FORMATS = (\n '%d-%m-%y', '%d/%m/%y...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = r'j \de F \de Y' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = r'j \de F \de Y \a \le\s G:i' YEAR_MONTH_FORMAT = r'F \de\l Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y G:i' FIRST_DAY_OF_WEEK = 1 # Monday DATE_INPUT_FORMATS = ( # '31/12/2009', '31/12/09' '%d/%m/%Y', '%d/%m/%y' ) TIME_INPUT_FORMATS = ( # '14:30:59', '14:30' '%H:%M:%S', '%H:%M' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M', ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1667, 0.0333, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2, 0.0333, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2333, 0.0333, 0, 0.66...
[ "DATE_FORMAT = r'j \\de F \\de Y'", "TIME_FORMAT = 'G:i:s'", "DATETIME_FORMAT = r'j \\de F \\de Y \\a \\le\\s G:i'", "YEAR_MONTH_FORMAT = r'F \\de\\l Y'", "MONTH_DAY_FORMAT = r'j \\de F'", "SHORT_DATE_FORMAT = 'd/m/Y'", "SHORT_DATETIME_FORMAT = 'd/m/Y G:i'", "FIRST_DAY_OF_WEEK = 1 # Monday", "DATE_I...
DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%j.%m.%Y', '%j.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' '%Y-%m-%j', # '2006-10-25', # '%j. %b %Y', '%j %b %Y', # '25. okt 2006', '25 okt 2006' # '%j. %b. %Y', '%j %b. %Y', # '25. okt. 2006', '25 okt. 2006' # '%j. %B %Y', '%j %B %Y', # '25. oktober 2006', '25 oktober 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%Y-%m-%j', # '2006-10-25' '%j.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%j.%m.%Y %H:%M', # '25.10.2006 14:30' '%j.%m.%Y', # '25.10.2006' '%j.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%j.%m.%y %H:%M', # '25.10.06 14:30' '%j.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
[ [ 14, 0, 0.0294, 0.0294, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0588, 0.0294, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0882, 0.0294, 0, 0...
[ "DATE_FORMAT = 'j. F Y'", "TIME_FORMAT = 'H:i'", "DATETIME_FORMAT = 'j. F Y H:i'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'd.m.Y'", "SHORT_DATETIME_FORMAT = 'd.m.Y H:i'", "FIRST_DAY_OF_WEEK = 1 # Monday", "DATE_INPUT_FORMATS = (\n '%Y-%m-%d', '%j.%m.%Y', '%...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'd F Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = # MONTH_DAY_FORMAT = SHORT_DATE_FORMAT = 'j M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.5, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.5556, 0.0556, 0, 0.66...
[ "DATE_FORMAT = 'd F Y'", "TIME_FORMAT = 'g:i:s A'", "SHORT_DATE_FORMAT = 'j M Y'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'd F Y' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M, Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.1667, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.4444, 0.0556, 0, 0...
[ "DATE_FORMAT = 'd F Y'", "TIME_FORMAT = 'H:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'j M, Y'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = '.'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j F Y' TIME_FORMAT = 'h:i:s A' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.3333, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.5, 0.0556, 0, 0.66...
[ "DATE_FORMAT = 'j F Y'", "TIME_FORMAT = 'h:i:s A'", "MONTH_DAY_FORMAT = 'j F'", "SHORT_DATE_FORMAT = 'j M Y'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j בF Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j בF Y H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j בF' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i:s' # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.125, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3889, 0.0556, 0, 0....
[ "DATE_FORMAT = 'j בF Y'", "TIME_FORMAT = 'H:i:s'", "DATETIME_FORMAT = 'j בF Y H:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j בF'", "SHORT_DATE_FORMAT = 'd/m/Y'", "SHORT_DATETIME_FORMAT = 'd/m/Y H:i:s'", "DECIMAL_SEPARATOR = '.'", "THOUSAND_SEPARATOR = ','" ]
DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%j.%m.%Y', '%j.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' '%Y-%m-%j', # '2006-10-25', # '%j. %b %Y', '%j %b %Y', # '25. okt 2006', '25 okt 2006' # '%j. %b. %Y', '%j %b. %Y', # '25. okt. 2006', '25 okt. 2006' # '%j. %B %Y', '%j %B %Y', # '25. oktober 2006', '25 oktober 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%Y-%m-%j', # '2006-10-25' '%j.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%j.%m.%Y %H:%M', # '25.10.2006 14:30' '%j.%m.%Y', # '25.10.2006' '%j.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%j.%m.%y %H:%M', # '25.10.06 14:30' '%j.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
[ [ 14, 0, 0.0294, 0.0294, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0588, 0.0294, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0882, 0.0294, 0, 0...
[ "DATE_FORMAT = 'j. F Y'", "TIME_FORMAT = 'H:i'", "DATETIME_FORMAT = 'j. F Y H:i'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'd.m.Y'", "SHORT_DATETIME_FORMAT = 'd.m.Y H:i'", "FIRST_DAY_OF_WEEK = 1 # Monday", "DATE_INPUT_FORMATS = (\n '%Y-%m-%d', '%j.%m.%Y', '%...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'd F Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'd F Y H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'd F' SHORT_DATE_FORMAT = 'd M Y' SHORT_DATETIME_FORMAT = 'd M Y H:i:s' FIRST_DAY_OF_WEEK = 1 # Pazartesi DATE_INPUT_FORMATS = ( '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25' # '%d %B %Y', '%d %b. %Y', # '25 Ekim 2006', '25 Eki. 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1562, 0.0312, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1875, 0.0312, 0, 0.66, 0.0769, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.2188, 0.0312, 0, 0...
[ "DATE_FORMAT = 'd F Y'", "TIME_FORMAT = 'H:i:s'", "DATETIME_FORMAT = 'd F Y H:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'd F'", "SHORT_DATE_FORMAT = 'd M Y'", "SHORT_DATETIME_FORMAT = 'd M Y H:i:s'", "FIRST_DAY_OF_WEEK = 1 # Pazartesi", "DATE_INPUT_FORMATS = (\n '%d/%m/%Y', '%d/%m/%...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.n.Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.1667, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.4444, 0.0556, 0, 0...
[ "DATE_FORMAT = 'j. F Y'", "TIME_FORMAT = 'H:i:s'", "YEAR_MONTH_FORMAT = 'F Y'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'j.n.Y'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = '.'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'd. F Y' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j. M. Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.2, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.5, 0.0556, 0, 0.66, ...
[ "DATE_FORMAT = 'd. F Y'", "TIME_FORMAT = 'H:i:s'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'j. M. Y'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = '.'" ]
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'Y년 n월 j일' TIME_FORMAT = 'A g:i:s' DATETIME_FORMAT = 'Y년 n월 j일 g:i:s A' YEAR_MONTH_FORMAT = 'Y년 F월' MONTH_DAY_FORMAT = 'F월 j일' SHORT_DATE_FORMAT = 'Y-n-j.' SHORT_DATETIME_FORMAT = 'Y-n-j H:i' # FIRST_DAY_OF_WEEK = DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' '%Y년 %m월 %d일', # '2006년 10월 25일', with localized suffix. ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' '%H시 %M분 %S초', # '14시 30분 59초' '%H시 %M분', # '14시 30분' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' '%Y년 %m월 %d일 %H시 %M분 %S초', # '2006년 10월 25일 14시 30분 59초' '%Y년 %m월 %d일 %H시 %M분', # '2006년 10월 25일 14시 30분' ) DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
[ [ 14, 0, 0.1136, 0.0227, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1364, 0.0227, 0, 0.66, 0.0833, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1591, 0.0227, 0, 0...
[ "DATE_FORMAT = 'Y년 n월 j일'", "TIME_FORMAT = 'A g:i:s'", "DATETIME_FORMAT = 'Y년 n월 j일 g:i:s A'", "YEAR_MONTH_FORMAT = 'Y년 F월'", "MONTH_DAY_FORMAT = 'F월 j일'", "SHORT_DATE_FORMAT = 'Y-n-j.'", "SHORT_DATETIME_FORMAT = 'Y-n-j H:i'", "DATE_INPUT_FORMATS = (\n '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10...
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'j. N Y.' TIME_FORMAT = 'G:i' DATETIME_FORMAT = 'j. N. Y. G:i T' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'Y M j' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
[ [ 14, 0, 0.2778, 0.0556, 0, 0.66, 0, 843, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3333, 0.0556, 0, 0.66, 0.1429, 662, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.3889, 0.0556, 0, 0...
[ "DATE_FORMAT = 'j. N Y.'", "TIME_FORMAT = 'G:i'", "DATETIME_FORMAT = 'j. N. Y. G:i T'", "YEAR_MONTH_FORMAT = 'F Y.'", "MONTH_DAY_FORMAT = 'j. F'", "SHORT_DATE_FORMAT = 'Y M j'", "DECIMAL_SEPARATOR = ','", "THOUSAND_SEPARATOR = '.'" ]
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
[ [ 1, 0, 0.1818, 0.0909, 0, 0.66, 0, 879, 0, 1, 0, 0, 879, 0, 0 ], [ 7, 0, 0.5, 0.5455, 0, 0.66, 0.5, 0, 0, 1, 0, 0, 0, 0, 2 ], [ 1, 1, 0.3636, 0.0909, 1, 0.8, 0...
[ "from django.core.management import execute_manager", "try:\n import settings # Assumed to be in the same directory.\nexcept ImportError:\n import sys\n sys.stderr.write(\"Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\\nYou'll have to run dj...
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
[ [ 1, 0, 0.1818, 0.0909, 0, 0.66, 0, 879, 0, 1, 0, 0, 879, 0, 0 ], [ 7, 0, 0.5, 0.5455, 0, 0.66, 0.5, 0, 0, 1, 0, 0, 0, 0, 2 ], [ 1, 1, 0.3636, 0.0909, 1, 0.18, ...
[ "from django.core.management import execute_manager", "try:\n import settings # Assumed to be in the same directory.\nexcept ImportError:\n import sys\n sys.stderr.write(\"Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\\nYou'll have to run dj...
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/', include(admin.site.urls)), )
[ [ 1, 0, 0.0625, 0.0625, 0, 0.66, 0, 341, 0, 1, 0, 0, 341, 0, 0 ], [ 14, 0, 0.7188, 0.625, 0, 0.66, 1, 990, 3, 1, 0, 0, 75, 10, 1 ] ]
[ "from django.conf.urls.defaults import *", "urlpatterns = patterns('',\n # Example:\n # (r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # (r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Un...
# Django settings for {{ project_name }} project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/static/" STATICFILES_ROOT = '' # URL that handles the static files served from STATICFILES_ROOT. # Example: "http://static.lawrence.com/", "http://example.com/static/" STATICFILES_URL = '/static/' # URL prefix for admin media -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/' # A list of locations of additional static files STATICFILES_DIRS = () # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = '{{ project_name }}.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request':{ 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
[ [ 14, 0, 0.0216, 0.0072, 0, 0.66, 0, 309, 1, 0, 0, 0, 0, 4, 0 ], [ 14, 0, 0.0288, 0.0072, 0, 0.66, 0.0435, 7, 2, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0504, 0.0216, 0, 0.6...
[ "DEBUG = True", "TEMPLATE_DEBUG = DEBUG", "ADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)", "MANAGERS = ADMINS", "DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': '', ...
from django.conf.urls.defaults import * urlpatterns = patterns('django.views', (r'^(?P<content_type_id>\d+)/(?P<object_id>.*)/$', 'defaults.shortcut'), )
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 341, 0, 1, 0, 0, 341, 0, 0 ], [ 14, 0, 0.8, 0.6, 0, 0.66, 1, 990, 3, 2, 0, 0, 75, 10, 1 ] ]
[ "from django.conf.urls.defaults import *", "urlpatterns = patterns('django.views',\n (r'^(?P<content_type_id>\\d+)/(?P<object_id>.*)/$', 'defaults.shortcut'),\n)" ]
from django.core.urlresolvers import RegexURLPattern, RegexURLResolver from django.core.exceptions import ImproperlyConfigured __all__ = ['handler404', 'handler500', 'include', 'patterns', 'url'] handler404 = 'django.views.defaults.page_not_found' handler500 = 'django.views.defaults.server_error' def include(arg, namespace=None, app_name=None): if isinstance(arg, tuple): # callable returning a namespace hint if namespace: raise ImproperlyConfigured('Cannot override the namespace for a dynamic module that provides a namespace') urlconf_module, app_name, namespace = arg else: # No namespace hint - use manually provided namespace urlconf_module = arg return (urlconf_module, app_name, namespace) def patterns(prefix, *args): pattern_list = [] for t in args: if isinstance(t, (list, tuple)): t = url(prefix=prefix, *t) elif isinstance(t, RegexURLPattern): t.add_prefix(prefix) pattern_list.append(t) return pattern_list def url(regex, view, kwargs=None, name=None, prefix=''): if isinstance(view, (list,tuple)): # For include(...) processing. urlconf_module, app_name, namespace = view return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace) else: if isinstance(view, basestring): if not view: raise ImproperlyConfigured('Empty URL pattern view name not permitted (for pattern %r)' % regex) if prefix: view = prefix + '.' + view return RegexURLPattern(regex, view, kwargs, name)
[ [ 1, 0, 0.0238, 0.0238, 0, 0.66, 0, 749, 0, 2, 0, 0, 749, 0, 0 ], [ 1, 0, 0.0476, 0.0238, 0, 0.66, 0.1429, 160, 0, 1, 0, 0, 160, 0, 0 ], [ 14, 0, 0.0952, 0.0238, 0, ...
[ "from django.core.urlresolvers import RegexURLPattern, RegexURLResolver", "from django.core.exceptions import ImproperlyConfigured", "__all__ = ['handler404', 'handler500', 'include', 'patterns', 'url']", "handler404 = 'django.views.defaults.page_not_found'", "handler500 = 'django.views.defaults.server_erro...
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^setlang/$', 'django.views.i18n.set_language'), )
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 341, 0, 1, 0, 0, 341, 0, 0 ], [ 14, 0, 0.8, 0.6, 0, 0.66, 1, 990, 3, 2, 0, 0, 75, 10, 1 ] ]
[ "from django.conf.urls.defaults import *", "urlpatterns = patterns('',\n (r'^setlang/$', 'django.views.i18n.set_language'),\n)" ]
# Default Django settings. Override these with settings in the module # pointed-to by the DJANGO_SETTINGS_MODULE environment variable. # This is defined here as a do-nothing function because we can't import # django.utils.translation -- that module depends on the settings. gettext_noop = lambda s: s #################### # CORE # #################### DEBUG = False TEMPLATE_DEBUG = False # Whether the framework should propagate raw exceptions rather than catching # them. This is useful under some testing siutations and should never be used # on a live site. DEBUG_PROPAGATE_EXCEPTIONS = False # Whether to use the "Etag" header. This saves bandwidth but slows down performance. USE_ETAGS = False # People who get code error notifications. # In the format (('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com')) ADMINS = () # Tuple of IP addresses, as strings, that: # * See debug comments, when DEBUG is true # * Receive x-headers INTERNAL_IPS = () # Local time zone for this installation. All choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all # systems may support all possibilities). TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' # Languages we provide translations for, out of the box. The language name # should be the utf-8 encoded local name for the language. LANGUAGES = ( ('ar', gettext_noop('Arabic')), ('bg', gettext_noop('Bulgarian')), ('bn', gettext_noop('Bengali')), ('bs', gettext_noop('Bosnian')), ('ca', gettext_noop('Catalan')), ('cs', gettext_noop('Czech')), ('cy', gettext_noop('Welsh')), ('da', gettext_noop('Danish')), ('de', gettext_noop('German')), ('el', gettext_noop('Greek')), ('en', gettext_noop('English')), ('en-gb', gettext_noop('British English')), ('es', gettext_noop('Spanish')), ('es-ar', gettext_noop('Argentinian Spanish')), ('et', gettext_noop('Estonian')), ('eu', gettext_noop('Basque')), ('fa', gettext_noop('Persian')), ('fi', gettext_noop('Finnish')), ('fr', gettext_noop('French')), ('fy-nl', gettext_noop('Frisian')), ('ga', gettext_noop('Irish')), ('gl', gettext_noop('Galician')), ('he', gettext_noop('Hebrew')), ('hi', gettext_noop('Hindi')), ('hr', gettext_noop('Croatian')), ('hu', gettext_noop('Hungarian')), ('id', gettext_noop('Indonesian')), ('is', gettext_noop('Icelandic')), ('it', gettext_noop('Italian')), ('ja', gettext_noop('Japanese')), ('ka', gettext_noop('Georgian')), ('km', gettext_noop('Khmer')), ('kn', gettext_noop('Kannada')), ('ko', gettext_noop('Korean')), ('lt', gettext_noop('Lithuanian')), ('lv', gettext_noop('Latvian')), ('mk', gettext_noop('Macedonian')), ('ml', gettext_noop('Malayalam')), ('mn', gettext_noop('Mongolian')), ('nl', gettext_noop('Dutch')), ('no', gettext_noop('Norwegian')), ('nb', gettext_noop('Norwegian Bokmal')), ('nn', gettext_noop('Norwegian Nynorsk')), ('pa', gettext_noop('Punjabi')), ('pl', gettext_noop('Polish')), ('pt', gettext_noop('Portuguese')), ('pt-br', gettext_noop('Brazilian Portuguese')), ('ro', gettext_noop('Romanian')), ('ru', gettext_noop('Russian')), ('sk', gettext_noop('Slovak')), ('sl', gettext_noop('Slovenian')), ('sq', gettext_noop('Albanian')), ('sr', gettext_noop('Serbian')), ('sr-latn', gettext_noop('Serbian Latin')), ('sv', gettext_noop('Swedish')), ('ta', gettext_noop('Tamil')), ('te', gettext_noop('Telugu')), ('th', gettext_noop('Thai')), ('tr', gettext_noop('Turkish')), ('uk', gettext_noop('Ukrainian')), ('vi', gettext_noop('Vietnamese')), ('zh-cn', gettext_noop('Simplified Chinese')), ('zh-tw', gettext_noop('Traditional Chinese')), ) # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI = ("he", "ar", "fa") # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True LOCALE_PATHS = () LANGUAGE_COOKIE_NAME = 'django_language' # If you set this to True, Django will format dates, numbers and calendars # according to user current locale USE_L10N = False # Not-necessarily-technical managers of the site. They get broken link # notifications and other various e-mails. MANAGERS = ADMINS # Default content type and charset to use for all HttpResponse objects, if a # MIME type isn't manually specified. These are used to construct the # Content-Type header. DEFAULT_CONTENT_TYPE = 'text/html' DEFAULT_CHARSET = 'utf-8' # Encoding of files read from disk (template and initial SQL files). FILE_CHARSET = 'utf-8' # E-mail address that error messages come from. SERVER_EMAIL = 'root@localhost' # Whether to send broken-link e-mails. SEND_BROKEN_LINK_EMAILS = False # Database connection info. # Legacy format DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = '' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. DATABASE_OPTIONS = {} # Set to empty dictionary for default. # New format DATABASES = { } # Classes used to implement db routing behaviour DATABASE_ROUTERS = [] # The email backend to use. For possible shortcuts see django.core.mail. # The default is to use the SMTP backend. # Third-party backends can be specified by providing a Python path # to a module that defines an EmailBackend class. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending e-mail. EMAIL_HOST = 'localhost' # Port for sending e-mail. EMAIL_PORT = 25 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False # List of strings representing installed apps. INSTALLED_APPS = () # List of locations of the template source files, in search order. TEMPLATE_DIRS = () # List of callables that know how to import templates from various sources. # See the comments in django/core/template/loader.py for interface # documentation. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) # List of processors used by RequestContext to populate the context. # Each one should be a callable that takes the request object as its # only parameter and returns a dictionary to add to the context. TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', # 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', 'django.contrib.staticfiles.context_processors.staticfiles', ) # Output to use in template system for invalid (e.g. misspelled) variables. TEMPLATE_STRING_IF_INVALID = '' # Default e-mail address to use for various automated correspondence from # the site managers. DEFAULT_FROM_EMAIL = 'webmaster@localhost' # Subject-line prefix for email messages send with django.core.mail.mail_admins # or ...mail_managers. Make sure to include the trailing space. EMAIL_SUBJECT_PREFIX = '[Django] ' # Whether to append trailing slashes to URLs. APPEND_SLASH = True # Whether to prepend the "www." subdomain to URLs that don't have it. PREPEND_WWW = False # Override the server-derived value of SCRIPT_NAME FORCE_SCRIPT_NAME = None # List of compiled regular expression objects representing User-Agent strings # that are not allowed to visit any page, systemwide. Use this for bad # robots/crawlers. Here are a few examples: # import re # DISALLOWED_USER_AGENTS = ( # re.compile(r'^NaverBot.*'), # re.compile(r'^EmailSiphon.*'), # re.compile(r'^SiteSucker.*'), # re.compile(r'^sohu-search') # ) DISALLOWED_USER_AGENTS = () ABSOLUTE_URL_OVERRIDES = {} # Tuple of strings representing allowed prefixes for the {% ssi %} tag. # Example: ('/home/html', '/var/www') ALLOWED_INCLUDE_ROOTS = () # If this is a admin settings module, this should be a list of # settings modules (in the format 'foo.bar.baz') for which this admin # is an admin. ADMIN_FOR = () # 404s that may be ignored. IGNORABLE_404_STARTS = ('/cgi-bin/', '/_vti_bin', '/_vti_inf') IGNORABLE_404_ENDS = ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi', 'favicon.ico', '.php') # A secret key for this particular Django installation. Used in secret-key # hashing algorithms. Set this in your settings, or Django will complain # loudly. SECRET_KEY = '' # Default file storage mechanism that holds media. DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. # Example: "http://media.lawrence.com" MEDIA_URL = '' # List of upload handler classes to be applied in order. FILE_UPLOAD_HANDLERS = ( 'django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ) # Maximum size, in bytes, of a request before it will be streamed to the # file system instead of into memory. FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Directory in which upload streamed files will be temporarily saved. A value of # `None` will make Django use the operating system's default temporary directory # (i.e. "/tmp" on *nix systems). FILE_UPLOAD_TEMP_DIR = None # The numeric mode to set newly-uploaded files to. The value should be a mode # you'd pass directly to os.chmod; see http://docs.python.org/lib/os-file-dir.html. FILE_UPLOAD_PERMISSIONS = None # Python module path where user will place custom format definition. # The directory where this setting is pointing should contain subdirectories # named as the locales, containing a formats.py file # (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use) FORMAT_MODULE_PATH = None # Default formatting for date objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'N j, Y' # Default formatting for datetime objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATETIME_FORMAT = 'N j, Y, P' # Default formatting for time objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date TIME_FORMAT = 'P' # Default formatting for date objects when only the year and month are relevant. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date YEAR_MONTH_FORMAT = 'F Y' # Default formatting for date objects when only the month and day are relevant. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date MONTH_DAY_FORMAT = 'F j' # Default short formatting for date objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATE_FORMAT = 'm/d/Y' # Default short formatting for datetime objects. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATETIME_FORMAT = 'm/d/Y P' # Default formats to be used when parsing dates from input boxes, in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) # Default formats to be used when parsing times from input boxes, in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) # Default formats to be used when parsing dates and times from input boxes, # in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) # First day of week, to be used on calendars # 0 means Sunday, 1 means Monday... FIRST_DAY_OF_WEEK = 0 # Decimal separator symbol DECIMAL_SEPARATOR = '.' # Boolean that sets whether to add thousand separator when formatting numbers USE_THOUSAND_SEPARATOR = False # Number of digits that will be together, when spliting them by # THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands... NUMBER_GROUPING = 0 # Thousand separator symbol THOUSAND_SEPARATOR = ',' # Do you want to manage transactions manually? # Hint: you really don't! TRANSACTIONS_MANAGED = False # The User-Agent string to use when checking for URL validity through the # isExistingURL validator. from django import get_version URL_VALIDATOR_USER_AGENT = "Django/%s (http://www.djangoproject.com)" % get_version() # The tablespaces to use for each model when not specified otherwise. DEFAULT_TABLESPACE = '' DEFAULT_INDEX_TABLESPACE = '' ############## # MIDDLEWARE # ############## # List of middleware classes to use. Order is important; in the request phase, # this middleware classes will be applied in the order given, and in the # response phase the middleware will be applied in reverse order. MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # 'django.middleware.http.ConditionalGetMiddleware', # 'django.middleware.gzip.GZipMiddleware', ) ############ # SESSIONS # ############ SESSION_COOKIE_NAME = 'sessionid' # Cookie name. This can be whatever you want. SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # Age of cookie, in seconds (default: 2 weeks). SESSION_COOKIE_DOMAIN = None # A string like ".lawrence.com", or None for standard domain cookie. SESSION_COOKIE_SECURE = False # Whether the session cookie should be secure (https:// only). SESSION_COOKIE_PATH = '/' # The path of the session cookie. SESSION_SAVE_EVERY_REQUEST = False # Whether to save the session data on every request. SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether a user's session cookie expires when the Web browser is closed. SESSION_ENGINE = 'django.contrib.sessions.backends.db' # The module to store session data SESSION_FILE_PATH = None # Directory to store session files if using the file session module. If None, the backend will use a sensible default. ######### # CACHE # ######### # The cache backend to use. See the docstring in django.core.cache for the # possible values. CACHE_BACKEND = 'locmem://' CACHE_MIDDLEWARE_KEY_PREFIX = '' CACHE_MIDDLEWARE_SECONDS = 600 #################### # COMMENTS # #################### COMMENTS_ALLOW_PROFANITIES = False # The profanities that will trigger a validation error in the # 'hasNoProfanities' validator. All of these should be in lowercase. PROFANITIES_LIST = () # The group ID that designates which users are banned. # Set to None if you're not using it. COMMENTS_BANNED_USERS_GROUP = None # The group ID that designates which users can moderate comments. # Set to None if you're not using it. COMMENTS_MODERATORS_GROUP = None # The group ID that designates the users whose comments should be e-mailed to MANAGERS. # Set to None if you're not using it. COMMENTS_SKETCHY_USERS_GROUP = None # The system will e-mail MANAGERS the first COMMENTS_FIRST_FEW comments by each # user. Set this to 0 if you want to disable it. COMMENTS_FIRST_FEW = 0 # A tuple of IP addresses that have been banned from participating in various # Django-powered features. BANNED_IPS = () ################## # AUTHENTICATION # ################## AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) LOGIN_URL = '/accounts/login/' LOGOUT_URL = '/accounts/logout/' LOGIN_REDIRECT_URL = '/accounts/profile/' # The number of days a password reset link is valid for PASSWORD_RESET_TIMEOUT_DAYS = 3 ######## # CSRF # ######## # Dotted path to callable to be used as view when a request is # rejected by the CSRF middleware. CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure' # Name and domain for CSRF cookie. CSRF_COOKIE_NAME = 'csrftoken' CSRF_COOKIE_DOMAIN = None ############ # MESSAGES # ############ # Class to use as messges backend MESSAGE_STORAGE = 'django.contrib.messages.storage.user_messages.LegacyFallbackStorage' # Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within # django.contrib.messages to avoid imports in this settings file. ########### # LOGGING # ########### # The callable to use to configure logging LOGGING_CONFIG = 'django.utils.log.dictConfig' # The default logging configuration. This sends an email to # the site admins on every HTTP 500 error. All other log # records are sent to the bit bucket. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request':{ 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } ########### # TESTING # ########### # The name of the class to use to run the test suite TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner' # The name of the database to use for testing purposes. # If None, a name of 'test_' + DATABASE_NAME will be assumed TEST_DATABASE_NAME = None # Strings used to set the character set and collation order for the test # database. These values are passed literally to the server, so they are # backend-dependent. If None, no special settings are sent (system defaults are # used). TEST_DATABASE_CHARSET = None TEST_DATABASE_COLLATION = None ############ # FIXTURES # ############ # The list of directories to search for fixtures FIXTURE_DIRS = () ############### # STATICFILES # ############### # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/static/" STATICFILES_ROOT = '' # URL that handles the static files served from STATICFILES_ROOT. # Example: "http://media.lawrence.com/static/" STATICFILES_URL = '/static/' # A list of locations of additional static files STATICFILES_DIRS = () # The default file storage backend used during the build process STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # URL prefix for admin media -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/'
[ [ 14, 0, 0.0103, 0.0017, 0, 0.66, 0, 651, 9, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0207, 0.0017, 0, 0.66, 0.0082, 309, 1, 0, 0, 0, 0, 4, 0 ], [ 14, 0, 0.0224, 0.0017, 0, 0...
[ "gettext_noop = lambda s: s", "DEBUG = False", "TEMPLATE_DEBUG = False", "DEBUG_PROPAGATE_EXCEPTIONS = False", "USE_ETAGS = False", "ADMINS = ()", "INTERNAL_IPS = ()", "TIME_ZONE = 'America/Chicago'", "LANGUAGE_CODE = 'en-us'", "LANGUAGES = (\n ('ar', gettext_noop('Arabic')),\n ('bg', gettex...
from django.db import models # Create your models here.
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 40, 0, 1, 0, 0, 40, 0, 0 ] ]
[ "from django.db import models" ]
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
[ [ 8, 0, 0.1522, 0.2609, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.3478, 0.0435, 0, 0.66, 0.3333, 944, 0, 1, 0, 0, 944, 0, 0 ], [ 3, 0, 0.5435, 0.2609, 0, 0.66...
[ "\"\"\"\nThis file demonstrates two different styles of tests (one doctest and one\nunittest). These will both pass when you run \"manage.py test\".\n\nReplace these with more appropriate tests for your application.\n\"\"\"", "from django.test import TestCase", "class SimpleTest(TestCase):\n def test_basic_a...
# Create your views here.
[]
[]
""" Parser and utilities for the smart 'if' tag """ import operator # Using a simple top down parser, as described here: # http://effbot.org/zone/simple-top-down-parsing.htm. # 'led' = left denotation # 'nud' = null denotation # 'bp' = binding power (left = lbp, right = rbp) class TokenBase(object): """ Base class for operators and literals, mainly for debugging and for throwing syntax errors. """ id = None # node/token type name value = None # used by literals first = second = None # used by tree nodes def nud(self, parser): # Null denotation - called in prefix context raise parser.error_class( "Not expecting '%s' in this position in if tag." % self.id ) def led(self, left, parser): # Left denotation - called in infix context raise parser.error_class( "Not expecting '%s' as infix operator in if tag." % self.id ) def display(self): """ Returns what to display in error messages for this node """ return self.id def __repr__(self): out = [str(x) for x in [self.id, self.first, self.second] if x is not None] return "(" + " ".join(out) + ")" def infix(bp, func): """ Creates an infix operator, given a binding power and a function that evaluates the node """ class Operator(TokenBase): lbp = bp def led(self, left, parser): self.first = left self.second = parser.expression(bp) return self def eval(self, context): try: return func(context, self.first, self.second) except Exception: # Templates shouldn't throw exceptions when rendering. We are # most likely to get exceptions for things like {% if foo in bar # %} where 'bar' does not support 'in', so default to False return False return Operator def prefix(bp, func): """ Creates a prefix operator, given a binding power and a function that evaluates the node. """ class Operator(TokenBase): lbp = bp def nud(self, parser): self.first = parser.expression(bp) self.second = None return self def eval(self, context): try: return func(context, self.first) except Exception: return False return Operator # Operator precedence follows Python. # NB - we can get slightly more accurate syntax error messages by not using the # same object for '==' and '='. # We defer variable evaluation to the lambda to ensure that terms are # lazily evaluated using Python's boolean parsing logic. OPERATORS = { 'or': infix(6, lambda context, x, y: x.eval(context) or y.eval(context)), 'and': infix(7, lambda context, x, y: x.eval(context) and y.eval(context)), 'not': prefix(8, lambda context, x: not x.eval(context)), 'in': infix(9, lambda context, x, y: x.eval(context) in y.eval(context)), 'not in': infix(9, lambda context, x, y: x.eval(context) not in y.eval(context)), '=': infix(10, lambda context, x, y: x.eval(context) == y.eval(context)), '==': infix(10, lambda context, x, y: x.eval(context) == y.eval(context)), '!=': infix(10, lambda context, x, y: x.eval(context) != y.eval(context)), '>': infix(10, lambda context, x, y: x.eval(context) > y.eval(context)), '>=': infix(10, lambda context, x, y: x.eval(context) >= y.eval(context)), '<': infix(10, lambda context, x, y: x.eval(context) < y.eval(context)), '<=': infix(10, lambda context, x, y: x.eval(context) <= y.eval(context)), } # Assign 'id' to each: for key, op in OPERATORS.items(): op.id = key class Literal(TokenBase): """ A basic self-resolvable object similar to a Django template variable. """ # IfParser uses Literal in create_var, but TemplateIfParser overrides # create_var so that a proper implementation that actually resolves # variables, filters etc is used. id = "literal" lbp = 0 def __init__(self, value): self.value = value def display(self): return repr(self.value) def nud(self, parser): return self def eval(self, context): return self.value def __repr__(self): return "(%s %r)" % (self.id, self.value) class EndToken(TokenBase): lbp = 0 def nud(self, parser): raise parser.error_class("Unexpected end of expression in if tag.") EndToken = EndToken() class IfParser(object): error_class = ValueError def __init__(self, tokens): # pre-pass necessary to turn 'not','in' into single token l = len(tokens) mapped_tokens = [] i = 0 while i < l: token = tokens[i] if token == "not" and i + 1 < l and tokens[i+1] == "in": token = "not in" i += 1 # skip 'in' mapped_tokens.append(self.translate_token(token)) i += 1 self.tokens = mapped_tokens self.pos = 0 self.current_token = self.next() def translate_token(self, token): try: op = OPERATORS[token] except (KeyError, TypeError): return self.create_var(token) else: return op() def next(self): if self.pos >= len(self.tokens): return EndToken else: retval = self.tokens[self.pos] self.pos += 1 return retval def parse(self): retval = self.expression() # Check that we have exhausted all the tokens if self.current_token is not EndToken: raise self.error_class("Unused '%s' at end of if expression." % self.current_token.display()) return retval def expression(self, rbp=0): t = self.current_token self.current_token = self.next() left = t.nud(self) while rbp < self.current_token.lbp: t = self.current_token self.current_token = self.next() left = t.led(left, self) return left def create_var(self, value): return Literal(value)
[ [ 8, 0, 0.0097, 0.0146, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0194, 0.0049, 0, 0.66, 0.1, 616, 0, 1, 0, 0, 616, 0, 0 ], [ 3, 0, 0.1286, 0.1456, 0, 0.66, ...
[ "\"\"\"\nParser and utilities for the smart 'if' tag\n\"\"\"", "import operator", "class TokenBase(object):\n \"\"\"\n Base class for operators and literals, mainly for debugging and for throwing\n syntax errors.\n \"\"\"\n id = None # node/token type name\n value = None # used by literals\n ...
""" Wrapper class that takes a list of template loaders as an argument and attempts to load templates from them in order, caching the result. """ from django.core.exceptions import ImproperlyConfigured from django.template import TemplateDoesNotExist from django.template.loader import BaseLoader, get_template_from_string, find_template_loader, make_origin from django.utils.hashcompat import sha_constructor from django.utils.importlib import import_module class Loader(BaseLoader): is_usable = True def __init__(self, loaders): self.template_cache = {} self._loaders = loaders self._cached_loaders = [] @property def loaders(self): # Resolve loaders on demand to avoid circular imports if not self._cached_loaders: for loader in self._loaders: self._cached_loaders.append(find_template_loader(loader)) return self._cached_loaders def find_template(self, name, dirs=None): for loader in self.loaders: try: template, display_name = loader(name, dirs) return (template, make_origin(display_name, loader, name, dirs)) except TemplateDoesNotExist: pass raise TemplateDoesNotExist(name) def load_template(self, template_name, template_dirs=None): key = template_name if template_dirs: # If template directories were specified, use a hash to differentiate key = '-'.join([template_name, sha_constructor('|'.join(template_dirs)).hexdigest()]) if key not in self.template_cache: template, origin = self.find_template(template_name, template_dirs) if not hasattr(template, 'render'): try: template = get_template_from_string(template, origin, template_name) except TemplateDoesNotExist: # If compiling the template we found raises TemplateDoesNotExist, # back off to returning the source and display name for the template # we were asked to load. This allows for correct identification (later) # of the actual template that does not exist. return template, origin self.template_cache[key] = template return self.template_cache[key], None def reset(self): "Empty the template cache." self.template_cache.clear()
[ [ 8, 0, 0.0424, 0.0678, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1017, 0.0169, 0, 0.66, 0.1667, 160, 0, 1, 0, 0, 160, 0, 0 ], [ 1, 0, 0.1186, 0.0169, 0, 0.66...
[ "\"\"\"\nWrapper class that takes a list of template loaders as an argument and attempts\nto load templates from them in order, caching the result.\n\"\"\"", "from django.core.exceptions import ImproperlyConfigured", "from django.template import TemplateDoesNotExist", "from django.template.loader import BaseL...
# Wrapper for loading templates from eggs via pkg_resources.resource_string. try: from pkg_resources import resource_string except ImportError: resource_string = None from django.template import TemplateDoesNotExist from django.template.loader import BaseLoader from django.conf import settings class Loader(BaseLoader): is_usable = resource_string is not None def load_template_source(self, template_name, template_dirs=None): """ Loads templates from Python eggs via pkg_resource.resource_string. For every installed app, it tries to get the resource (app, template_name). """ if resource_string is not None: pkg_name = 'templates/' + template_name for app in settings.INSTALLED_APPS: try: return (resource_string(app, pkg_name).decode(settings.FILE_CHARSET), 'egg:%s:%s' % (app, pkg_name)) except: pass raise TemplateDoesNotExist(template_name) _loader = Loader() def load_template_source(template_name, template_dirs=None): import warnings warnings.warn( "'django.template.loaders.eggs.load_template_source' is deprecated; use 'django.template.loaders.eggs.Loader' instead.", DeprecationWarning ) return _loader.load_template_source(template_name, template_dirs) load_template_source.is_usable = resource_string is not None
[ [ 7, 0, 0.1154, 0.1026, 0, 0.66, 0, 0, 0, 1, 0, 0, 0, 0, 0 ], [ 1, 1, 0.1026, 0.0256, 1, 0.76, 0, 947, 0, 1, 0, 0, 947, 0, 0 ], [ 14, 1, 0.1538, 0.0256, 1, 0.76, ...
[ "try:\n from pkg_resources import resource_string\nexcept ImportError:\n resource_string = None", " from pkg_resources import resource_string", " resource_string = None", "from django.template import TemplateDoesNotExist", "from django.template.loader import BaseLoader", "from django.conf impo...
""" Wrapper for loading templates from "templates" directories in INSTALLED_APPS packages. """ import os import sys from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.template import TemplateDoesNotExist from django.template.loader import BaseLoader from django.utils._os import safe_join from django.utils.importlib import import_module # At compile time, cache the directories to search. fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() app_template_dirs = [] for app in settings.INSTALLED_APPS: try: mod = import_module(app) except ImportError, e: raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0])) template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates') if os.path.isdir(template_dir): app_template_dirs.append(template_dir.decode(fs_encoding)) # It won't change, so convert it to a tuple to save memory. app_template_dirs = tuple(app_template_dirs) class Loader(BaseLoader): is_usable = True def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. """ if not template_dirs: template_dirs = app_template_dirs for template_dir in template_dirs: try: yield safe_join(template_dir, template_name) except UnicodeDecodeError: # The template dir name was a bytestring that wasn't valid UTF-8. raise except ValueError: # The joined path was located outside of template_dir. pass def load_template_source(self, template_name, template_dirs=None): for filepath in self.get_template_sources(template_name, template_dirs): try: file = open(filepath) try: return (file.read().decode(settings.FILE_CHARSET), filepath) finally: file.close() except IOError: pass raise TemplateDoesNotExist(template_name) _loader = Loader() def load_template_source(template_name, template_dirs=None): # For backwards compatibility import warnings warnings.warn( "'django.template.loaders.app_directories.load_template_source' is deprecated; use 'django.template.loaders.app_directories.Loader' instead.", DeprecationWarning ) return _loader.load_template_source(template_name, template_dirs) load_template_source.is_usable = True
[ [ 1, 0, 0.0196, 0.0196, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0392, 0.0196, 0, 0.66, 0.1111, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0784, 0.0196, 0, ...
[ "import os", "import sys", "from django.conf import settings", "from django.core.exceptions import ImproperlyConfigured", "from django.template import TemplateDoesNotExist", "from django.template.loader import BaseLoader", "from django.utils._os import safe_join", "from django.utils.importlib import i...
""" Wrapper for loading templates from the filesystem. """ from django.conf import settings from django.template import TemplateDoesNotExist from django.template.loader import BaseLoader from django.utils._os import safe_join class Loader(BaseLoader): is_usable = True def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. """ if not template_dirs: template_dirs = settings.TEMPLATE_DIRS for template_dir in template_dirs: try: yield safe_join(template_dir, template_name) except UnicodeDecodeError: # The template dir name was a bytestring that wasn't valid UTF-8. raise except ValueError: # The joined path was located outside of this particular # template_dir (it might be inside another one, so this isn't # fatal). pass def load_template_source(self, template_name, template_dirs=None): tried = [] for filepath in self.get_template_sources(template_name, template_dirs): try: file = open(filepath) try: return (file.read().decode(settings.FILE_CHARSET), filepath) finally: file.close() except IOError: tried.append(filepath) if tried: error_msg = "Tried %s" % tried else: error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory." raise TemplateDoesNotExist(error_msg) load_template_source.is_usable = True _loader = Loader() def load_template_source(template_name, template_dirs=None): # For backwards compatibility import warnings warnings.warn( "'django.template.loaders.filesystem.load_template_source' is deprecated; use 'django.template.loaders.filesystem.Loader' instead.", DeprecationWarning ) return _loader.load_template_source(template_name, template_dirs) load_template_source.is_usable = True
[ [ 8, 0, 0.0328, 0.0492, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.082, 0.0164, 0, 0.66, 0.125, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0984, 0.0164, 0, 0.66, ...
[ "\"\"\"\nWrapper for loading templates from the filesystem.\n\"\"\"", "from django.conf import settings", "from django.template import TemplateDoesNotExist", "from django.template.loader import BaseLoader", "from django.utils._os import safe_join", "class Loader(BaseLoader):\n is_usable = True\n\n d...
from django.template import TemplateSyntaxError, TemplateDoesNotExist, Variable from django.template import Library, Node, TextNode from django.template.loader import get_template from django.conf import settings from django.utils.safestring import mark_safe register = Library() BLOCK_CONTEXT_KEY = 'block_context' class ExtendsError(Exception): pass class BlockContext(object): def __init__(self): # Dictionary of FIFO queues. self.blocks = {} def add_blocks(self, blocks): for name, block in blocks.iteritems(): if name in self.blocks: self.blocks[name].insert(0, block) else: self.blocks[name] = [block] def pop(self, name): try: return self.blocks[name].pop() except (IndexError, KeyError): return None def push(self, name, block): self.blocks[name].append(block) def get_block(self, name): try: return self.blocks[name][-1] except (IndexError, KeyError): return None class BlockNode(Node): def __init__(self, name, nodelist, parent=None): self.name, self.nodelist, self.parent = name, nodelist, parent def __repr__(self): return "<Block Node: %s. Contents: %r>" % (self.name, self.nodelist) def render(self, context): block_context = context.render_context.get(BLOCK_CONTEXT_KEY) context.push() if block_context is None: context['block'] = self result = self.nodelist.render(context) else: push = block = block_context.pop(self.name) if block is None: block = self # Create new block so we can store context without thread-safety issues. block = BlockNode(block.name, block.nodelist) block.context = context context['block'] = block result = block.nodelist.render(context) if push is not None: block_context.push(self.name, push) context.pop() return result def super(self): render_context = self.context.render_context if (BLOCK_CONTEXT_KEY in render_context and render_context[BLOCK_CONTEXT_KEY].get_block(self.name) is not None): return mark_safe(self.render(self.context)) return '' class ExtendsNode(Node): must_be_first = True def __init__(self, nodelist, parent_name, parent_name_expr, template_dirs=None): self.nodelist = nodelist self.parent_name, self.parent_name_expr = parent_name, parent_name_expr self.template_dirs = template_dirs self.blocks = dict([(n.name, n) for n in nodelist.get_nodes_by_type(BlockNode)]) def __repr__(self): if self.parent_name_expr: return "<ExtendsNode: extends %s>" % self.parent_name_expr.token return '<ExtendsNode: extends "%s">' % self.parent_name def get_parent(self, context): if self.parent_name_expr: self.parent_name = self.parent_name_expr.resolve(context) parent = self.parent_name if not parent: error_msg = "Invalid template name in 'extends' tag: %r." % parent if self.parent_name_expr: error_msg += " Got this from the '%s' variable." % self.parent_name_expr.token raise TemplateSyntaxError(error_msg) if hasattr(parent, 'render'): return parent # parent is a Template object return get_template(parent) def render(self, context): compiled_parent = self.get_parent(context) if BLOCK_CONTEXT_KEY not in context.render_context: context.render_context[BLOCK_CONTEXT_KEY] = BlockContext() block_context = context.render_context[BLOCK_CONTEXT_KEY] # Add the block nodes from this node to the block context block_context.add_blocks(self.blocks) # If this block's parent doesn't have an extends node it is the root, # and its block nodes also need to be added to the block context. for node in compiled_parent.nodelist: # The ExtendsNode has to be the first non-text node. if not isinstance(node, TextNode): if not isinstance(node, ExtendsNode): blocks = dict([(n.name, n) for n in compiled_parent.nodelist.get_nodes_by_type(BlockNode)]) block_context.add_blocks(blocks) break # Call Template._render explicitly so the parser context stays # the same. return compiled_parent._render(context) class ConstantIncludeNode(Node): def __init__(self, template_path): try: t = get_template(template_path) self.template = t except: if settings.TEMPLATE_DEBUG: raise self.template = None def render(self, context): if self.template: return self.template.render(context) else: return '' class IncludeNode(Node): def __init__(self, template_name): self.template_name = Variable(template_name) def render(self, context): try: template_name = self.template_name.resolve(context) t = get_template(template_name) return t.render(context) except TemplateSyntaxError, e: if settings.TEMPLATE_DEBUG: raise return '' except: return '' # Fail silently for invalid included templates. def do_block(parser, token): """ Define a block that can be overridden by child templates. """ bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'%s' tag takes only one argument" % bits[0]) block_name = bits[1] # Keep track of the names of BlockNodes found in this template, so we can # check for duplication. try: if block_name in parser.__loaded_blocks: raise TemplateSyntaxError("'%s' tag with name '%s' appears more than once" % (bits[0], block_name)) parser.__loaded_blocks.append(block_name) except AttributeError: # parser.__loaded_blocks isn't a list yet parser.__loaded_blocks = [block_name] nodelist = parser.parse(('endblock', 'endblock %s' % block_name)) parser.delete_first_token() return BlockNode(block_name, nodelist) def do_extends(parser, token): """ Signal that this template extends a parent template. This tag may be used in two ways: ``{% extends "base" %}`` (with quotes) uses the literal value "base" as the name of the parent template to extend, or ``{% extends variable %}`` uses the value of ``variable`` as either the name of the parent template to extend (if it evaluates to a string) or as the parent tempate itelf (if it evaluates to a Template object). """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'%s' takes one argument" % bits[0]) parent_name, parent_name_expr = None, None if bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]: parent_name = bits[1][1:-1] else: parent_name_expr = parser.compile_filter(bits[1]) nodelist = parser.parse() if nodelist.get_nodes_by_type(ExtendsNode): raise TemplateSyntaxError("'%s' cannot appear more than once in the same template" % bits[0]) return ExtendsNode(nodelist, parent_name, parent_name_expr) def do_include(parser, token): """ Loads a template and renders it with the current context. Example:: {% include "foo/some_include" %} """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("%r tag takes one argument: the name of the template to be included" % bits[0]) path = bits[1] if path[0] in ('"', "'") and path[-1] == path[0]: return ConstantIncludeNode(path[1:-1]) return IncludeNode(bits[1]) register.tag('block', do_block) register.tag('extends', do_extends) register.tag('include', do_include)
[ [ 1, 0, 0.0046, 0.0046, 0, 0.66, 0, 213, 0, 3, 0, 0, 213, 0, 0 ], [ 1, 0, 0.0091, 0.0046, 0, 0.66, 0.0556, 213, 0, 3, 0, 0, 213, 0, 0 ], [ 1, 0, 0.0137, 0.0046, 0, ...
[ "from django.template import TemplateSyntaxError, TemplateDoesNotExist, Variable", "from django.template import Library, Node, TextNode", "from django.template.loader import get_template", "from django.conf import settings", "from django.utils.safestring import mark_safe", "register = Library()", "BLOCK...
""" Extra HTML Widget classes """ import time import datetime import re from django.forms.widgets import Widget, Select from django.utils import datetime_safe from django.utils.dates import MONTHS from django.utils.safestring import mark_safe from django.utils.formats import get_format from django.conf import settings __all__ = ('SelectDateWidget',) RE_DATE = re.compile(r'(\d{4})-(\d\d?)-(\d\d?)$') class SelectDateWidget(Widget): """ A Widget that splits date input into three <select> boxes. This also serves as an example of a Widget that has more than one HTML element and hence implements value_from_datadict. """ none_value = (0, '---') month_field = '%s_month' day_field = '%s_day' year_field = '%s_year' def __init__(self, attrs=None, years=None, required=True): # years is an optional list/tuple of years to use in the "year" select box. self.attrs = attrs or {} self.required = required if years: self.years = years else: this_year = datetime.date.today().year self.years = range(this_year, this_year+10) def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): if settings.USE_L10N: try: input_format = get_format('DATE_INPUT_FORMATS')[0] # Python 2.4 compatibility: # v = datetime.datetime.strptime(value, input_format) # would be clearer, but datetime.strptime was added in # Python 2.5 v = datetime.datetime(*(time.strptime(value, input_format)[0:6])) year_val, month_val, day_val = v.year, v.month, v.day except ValueError: pass else: match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] choices = [(i, i) for i in self.years] year_html = self.create_select(name, self.year_field, value, year_val, choices) choices = MONTHS.items() month_html = self.create_select(name, self.month_field, value, month_val, choices) choices = [(i, i) for i in range(1, 32)] day_html = self.create_select(name, self.day_field, value, day_val, choices) format = get_format('DATE_FORMAT') escaped = False output = [] for char in format: if escaped: escaped = False elif char == '\\': escaped = True elif char in 'Yy': output.append(year_html) elif char in 'bFMmNn': output.append(month_html) elif char in 'dj': output.append(day_html) return mark_safe(u'\n'.join(output)) def id_for_label(self, id_): return '%s_month' % id_ id_for_label = classmethod(id_for_label) def value_from_datadict(self, data, files, name): y = data.get(self.year_field % name) m = data.get(self.month_field % name) d = data.get(self.day_field % name) if y == m == d == "0": return None if y and m and d: if settings.USE_L10N: input_format = get_format('DATE_INPUT_FORMATS')[0] try: date_value = datetime.date(int(y), int(m), int(d)) except ValueError: pass else: date_value = datetime_safe.new_date(date_value) return date_value.strftime(input_format) else: return '%s-%s-%s' % (y, m, d) return data.get(name, None) def create_select(self, name, field, value, val, choices): if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name if not (self.required and val): choices.insert(0, self.none_value) local_attrs = self.build_attrs(id=field % id_) s = Select(choices=choices) select_html = s.render(field % name, val, local_attrs) return select_html
[ [ 8, 0, 0.0165, 0.0248, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0413, 0.0083, 0, 0.66, 0.0833, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 1, 0, 0.0496, 0.0083, 0, 0.66...
[ "\"\"\"\nExtra HTML Widget classes\n\"\"\"", "import time", "import datetime", "import re", "from django.forms.widgets import Widget, Select", "from django.utils import datetime_safe", "from django.utils.dates import MONTHS", "from django.utils.safestring import mark_safe", "from django.utils.format...
from widgets import *
[ [ 1, 0, 1, 1, 0, 0.66, 0, 178, 0, 1, 0, 0, 178, 0, 0 ] ]
[ "from widgets import *" ]
from django.utils.html import conditional_escape from django.utils.encoding import StrAndUnicode, force_unicode from django.utils.safestring import mark_safe # Import ValidationError so that it can be imported from this # module to maintain backwards compatibility. from django.core.exceptions import ValidationError def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. """ return u''.join([u' %s="%s"' % (k, conditional_escape(v)) for k, v in attrs.items()]) class ErrorDict(dict, StrAndUnicode): """ A collection of errors that knows how to display itself in various formats. The dictionary keys are the field names, and the values are the errors. """ def __unicode__(self): return self.as_ul() def as_ul(self): if not self: return u'' return mark_safe(u'<ul class="errorlist">%s</ul>' % ''.join([u'<li>%s%s</li>' % (k, force_unicode(v)) for k, v in self.items()])) def as_text(self): return u'\n'.join([u'* %s\n%s' % (k, u'\n'.join([u' * %s' % force_unicode(i) for i in v])) for k, v in self.items()]) class ErrorList(list, StrAndUnicode): """ A collection of errors that knows how to display itself in various formats. """ def __unicode__(self): return self.as_ul() def as_ul(self): if not self: return u'' return mark_safe(u'<ul class="errorlist">%s</ul>' % ''.join([u'<li>%s</li>' % conditional_escape(force_unicode(e)) for e in self])) def as_text(self): if not self: return u'' return u'\n'.join([u'* %s' % force_unicode(e) for e in self]) def __repr__(self): return repr([force_unicode(e) for e in self])
[ [ 1, 0, 0.0185, 0.0185, 0, 0.66, 0, 535, 0, 1, 0, 0, 535, 0, 0 ], [ 1, 0, 0.037, 0.0185, 0, 0.66, 0.1667, 96, 0, 2, 0, 0, 96, 0, 0 ], [ 1, 0, 0.0556, 0.0185, 0, 0.6...
[ "from django.utils.html import conditional_escape", "from django.utils.encoding import StrAndUnicode, force_unicode", "from django.utils.safestring import mark_safe", "from django.core.exceptions import ValidationError", "def flatatt(attrs):\n \"\"\"\n Convert a dictionary of attributes to a single st...
""" HTML Widget classes """ import django.utils.copycompat as copy from itertools import chain from django.conf import settings from django.utils.datastructures import MultiValueDict, MergeDict from django.utils.html import escape, conditional_escape from django.utils.translation import ugettext, ugettext_lazy from django.utils.encoding import StrAndUnicode, force_unicode from django.utils.safestring import mark_safe from django.utils import datetime_safe, formats import time import datetime from util import flatatt from urlparse import urljoin __all__ = ( 'Media', 'MediaDefiningClass', 'Widget', 'TextInput', 'PasswordInput', 'HiddenInput', 'MultipleHiddenInput', 'ClearableFileInput', 'FileInput', 'DateInput', 'DateTimeInput', 'TimeInput', 'Textarea', 'CheckboxInput', 'Select', 'NullBooleanSelect', 'SelectMultiple', 'RadioSelect', 'CheckboxSelectMultiple', 'MultiWidget', 'SplitDateTimeWidget', ) MEDIA_TYPES = ('css','js') class Media(StrAndUnicode): def __init__(self, media=None, **kwargs): if media: media_attrs = media.__dict__ else: media_attrs = kwargs self._css = {} self._js = [] for name in MEDIA_TYPES: getattr(self, 'add_' + name)(media_attrs.get(name, None)) # Any leftover attributes must be invalid. # if media_attrs != {}: # raise TypeError("'class Media' has invalid attribute(s): %s" % ','.join(media_attrs.keys())) def __unicode__(self): return self.render() def render(self): return mark_safe(u'\n'.join(chain(*[getattr(self, 'render_' + name)() for name in MEDIA_TYPES]))) def render_js(self): return [u'<script type="text/javascript" src="%s"></script>' % self.absolute_path(path) for path in self._js] def render_css(self): # To keep rendering order consistent, we can't just iterate over items(). # We need to sort the keys, and iterate over the sorted list. media = self._css.keys() media.sort() return chain(*[ [u'<link href="%s" type="text/css" media="%s" rel="stylesheet" />' % (self.absolute_path(path), medium) for path in self._css[medium]] for medium in media]) def absolute_path(self, path): if path.startswith(u'http://') or path.startswith(u'https://') or path.startswith(u'/'): return path return urljoin(settings.MEDIA_URL,path) def __getitem__(self, name): "Returns a Media object that only contains media of the given type" if name in MEDIA_TYPES: return Media(**{str(name): getattr(self, '_' + name)}) raise KeyError('Unknown media type "%s"' % name) def add_js(self, data): if data: for path in data: if path not in self._js: self._js.append(path) def add_css(self, data): if data: for medium, paths in data.items(): for path in paths: if not self._css.get(medium) or path not in self._css[medium]: self._css.setdefault(medium, []).append(path) def __add__(self, other): combined = Media() for name in MEDIA_TYPES: getattr(combined, 'add_' + name)(getattr(self, '_' + name, None)) getattr(combined, 'add_' + name)(getattr(other, '_' + name, None)) return combined def media_property(cls): def _media(self): # Get the media property of the superclass, if it exists if hasattr(super(cls, self), 'media'): base = super(cls, self).media else: base = Media() # Get the media definition for this class definition = getattr(cls, 'Media', None) if definition: extend = getattr(definition, 'extend', True) if extend: if extend == True: m = base else: m = Media() for medium in extend: m = m + base[medium] return m + Media(definition) else: return Media(definition) else: return base return property(_media) class MediaDefiningClass(type): "Metaclass for classes that can have media definitions" def __new__(cls, name, bases, attrs): new_class = super(MediaDefiningClass, cls).__new__(cls, name, bases, attrs) if 'media' not in attrs: new_class.media = media_property(new_class) return new_class class Widget(object): __metaclass__ = MediaDefiningClass is_hidden = False # Determines whether this corresponds to an <input type="hidden">. needs_multipart_form = False # Determines does this widget need multipart-encrypted form is_localized = False is_required = False def __init__(self, attrs=None): if attrs is not None: self.attrs = attrs.copy() else: self.attrs = {} def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() memo[id(self)] = obj return obj def render(self, name, value, attrs=None): """ Returns this Widget rendered as HTML, as a Unicode string. The 'value' given is not guaranteed to be valid input, so subclass implementations should program defensively. """ raise NotImplementedError def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." attrs = dict(self.attrs, **kwargs) if extra_attrs: attrs.update(extra_attrs) return attrs def value_from_datadict(self, data, files, name): """ Given a dictionary of data and this widget's name, returns the value of this widget. Returns None if it's not provided. """ return data.get(name, None) def _has_changed(self, initial, data): """ Return True if data differs from initial. """ # For purposes of seeing whether something has changed, None is # the same as an empty string, if the data or inital value we get # is None, replace it w/ u''. if data is None: data_value = u'' else: data_value = data if initial is None: initial_value = u'' else: initial_value = initial if force_unicode(initial_value) != force_unicode(data_value): return True return False def id_for_label(self, id_): """ Returns the HTML ID attribute of this Widget for use by a <label>, given the ID of the field. Returns None if no ID is available. This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget's tags. """ return id_ id_for_label = classmethod(id_for_label) class Input(Widget): """ Base class for all <input> widgets (except type='checkbox' and type='radio', which are special). """ input_type = None # Subclasses must define this. def _format_value(self, value): if self.is_localized: return formats.localize_input(value) return value def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_unicode(self._format_value(value)) return mark_safe(u'<input%s />' % flatatt(final_attrs)) class TextInput(Input): input_type = 'text' class PasswordInput(Input): input_type = 'password' def __init__(self, attrs=None, render_value=False): super(PasswordInput, self).__init__(attrs) self.render_value = render_value def render(self, name, value, attrs=None): if not self.render_value: value=None return super(PasswordInput, self).render(name, value, attrs) class HiddenInput(Input): input_type = 'hidden' is_hidden = True class MultipleHiddenInput(HiddenInput): """ A widget that handles <input type="hidden"> for fields that have a list of values. """ def __init__(self, attrs=None, choices=()): super(MultipleHiddenInput, self).__init__(attrs) # choices can be any iterable self.choices = choices def render(self, name, value, attrs=None, choices=()): if value is None: value = [] final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) id_ = final_attrs.get('id', None) inputs = [] for i, v in enumerate(value): input_attrs = dict(value=force_unicode(v), **final_attrs) if id_: # An ID attribute was given. Add a numeric index as a suffix # so that the inputs don't all have the same ID attribute. input_attrs['id'] = '%s_%s' % (id_, i) inputs.append(u'<input%s />' % flatatt(input_attrs)) return mark_safe(u'\n'.join(inputs)) def value_from_datadict(self, data, files, name): if isinstance(data, (MultiValueDict, MergeDict)): return data.getlist(name) return data.get(name, None) class FileInput(Input): input_type = 'file' needs_multipart_form = True def render(self, name, value, attrs=None): return super(FileInput, self).render(name, None, attrs=attrs) def value_from_datadict(self, data, files, name): "File widgets take data from FILES, not POST" return files.get(name, None) def _has_changed(self, initial, data): if data is None: return False return True FILE_INPUT_CONTRADICTION = object() class ClearableFileInput(FileInput): initial_text = ugettext_lazy('Currently') input_text = ugettext_lazy('Change') clear_checkbox_label = ugettext_lazy('Clear') template_with_initial = u'%(initial_text)s: %(initial)s %(clear_template)s<br />%(input_text)s: %(input)s' template_with_clear = u'%(clear)s <label for="%(clear_checkbox_id)s">%(clear_checkbox_label)s</label>' def clear_checkbox_name(self, name): """ Given the name of the file input, return the name of the clear checkbox input. """ return name + '-clear' def clear_checkbox_id(self, name): """ Given the name of the clear checkbox input, return the HTML id for it. """ return name + '_id' def render(self, name, value, attrs=None): substitutions = { 'initial_text': self.initial_text, 'input_text': self.input_text, 'clear_template': '', 'clear_checkbox_label': self.clear_checkbox_label, } template = u'%(input)s' substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs) if value and hasattr(value, "url"): template = self.template_with_initial substitutions['initial'] = (u'<a target="_blank" href="%s">%s</a>' % (value.url, value)) if not self.is_required: checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) substitutions['clear_checkbox_name'] = checkbox_name substitutions['clear_checkbox_id'] = checkbox_id substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id}) substitutions['clear_template'] = self.template_with_clear % substitutions return mark_safe(template % substitutions) def value_from_datadict(self, data, files, name): upload = super(ClearableFileInput, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class Textarea(Widget): def __init__(self, attrs=None): # The 'rows' and 'cols' attributes are required for HTML correctness. default_attrs = {'cols': '40', 'rows': '10'} if attrs: default_attrs.update(attrs) super(Textarea, self).__init__(default_attrs) def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) return mark_safe(u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), conditional_escape(force_unicode(value)))) class DateInput(Input): input_type = 'text' format = '%Y-%m-%d' # '2006-10-25' def __init__(self, attrs=None, format=None): super(DateInput, self).__init__(attrs) if format: self.format = format self.manual_format = True else: self.format = formats.get_format('DATE_INPUT_FORMATS')[0] self.manual_format = False def _format_value(self, value): if self.is_localized and not self.manual_format: return formats.localize_input(value) elif hasattr(value, 'strftime'): value = datetime_safe.new_date(value) return value.strftime(self.format) return value def _has_changed(self, initial, data): # If our field has show_hidden_initial=True, initial will be a string # formatted by HiddenInput using formats.localize_input, which is not # necessarily the format used for this widget. Attempt to convert it. try: input_format = formats.get_format('DATE_INPUT_FORMATS')[0] initial = datetime.date(*time.strptime(initial, input_format)[:3]) except (TypeError, ValueError): pass return super(DateInput, self)._has_changed(self._format_value(initial), data) class DateTimeInput(Input): input_type = 'text' format = '%Y-%m-%d %H:%M:%S' # '2006-10-25 14:30:59' def __init__(self, attrs=None, format=None): super(DateTimeInput, self).__init__(attrs) if format: self.format = format self.manual_format = True else: self.format = formats.get_format('DATETIME_INPUT_FORMATS')[0] self.manual_format = False def _format_value(self, value): if self.is_localized and not self.manual_format: return formats.localize_input(value) elif hasattr(value, 'strftime'): value = datetime_safe.new_datetime(value) return value.strftime(self.format) return value def _has_changed(self, initial, data): # If our field has show_hidden_initial=True, initial will be a string # formatted by HiddenInput using formats.localize_input, which is not # necessarily the format used for this widget. Attempt to convert it. try: input_format = formats.get_format('DATETIME_INPUT_FORMATS')[0] initial = datetime.datetime(*time.strptime(initial, input_format)[:6]) except (TypeError, ValueError): pass return super(DateTimeInput, self)._has_changed(self._format_value(initial), data) class TimeInput(Input): input_type = 'text' format = '%H:%M:%S' # '14:30:59' def __init__(self, attrs=None, format=None): super(TimeInput, self).__init__(attrs) if format: self.format = format self.manual_format = True else: self.format = formats.get_format('TIME_INPUT_FORMATS')[0] self.manual_format = False def _format_value(self, value): if self.is_localized and not self.manual_format: return formats.localize_input(value) elif hasattr(value, 'strftime'): return value.strftime(self.format) return value def _has_changed(self, initial, data): # If our field has show_hidden_initial=True, initial will be a string # formatted by HiddenInput using formats.localize_input, which is not # necessarily the format used for this widget. Attempt to convert it. try: input_format = formats.get_format('TIME_INPUT_FORMATS')[0] initial = datetime.time(*time.strptime(initial, input_format)[3:6]) except (TypeError, ValueError): pass return super(TimeInput, self)._has_changed(self._format_value(initial), data) class CheckboxInput(Widget): def __init__(self, attrs=None, check_test=bool): super(CheckboxInput, self).__init__(attrs) # check_test is a callable that takes a value and returns True # if the checkbox should be checked for that value. self.check_test = check_test def render(self, name, value, attrs=None): final_attrs = self.build_attrs(attrs, type='checkbox', name=name) try: result = self.check_test(value) except: # Silently catch exceptions result = False if result: final_attrs['checked'] = 'checked' if value not in ('', True, False, None): # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_unicode(value) return mark_safe(u'<input%s />' % flatatt(final_attrs)) def value_from_datadict(self, data, files, name): if name not in data: # A missing value means False because HTML form submission does not # send results for unselected checkboxes. return False value = data.get(name) # Translate true and false strings to boolean values. values = {'true': True, 'false': False} if isinstance(value, basestring): value = values.get(value.lower(), value) return value def _has_changed(self, initial, data): # Sometimes data or initial could be None or u'' which should be the # same thing as False. return bool(initial) != bool(data) class Select(Widget): def __init__(self, attrs=None, choices=()): super(Select, self).__init__(attrs) # choices can be any iterable, but we may need to render this widget # multiple times. Thus, collapse it into a list so it can be consumed # more than once. self.choices = list(choices) def render(self, name, value, attrs=None, choices=()): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) output = [u'<select%s>' % flatatt(final_attrs)] options = self.render_options(choices, [value]) if options: output.append(options) output.append(u'</select>') return mark_safe(u'\n'.join(output)) def render_option(self, selected_choices, option_value, option_label): option_value = force_unicode(option_value) selected_html = (option_value in selected_choices) and u' selected="selected"' or '' return u'<option value="%s"%s>%s</option>' % ( escape(option_value), selected_html, conditional_escape(force_unicode(option_label))) def render_options(self, choices, selected_choices): # Normalize to strings. selected_choices = set([force_unicode(v) for v in selected_choices]) output = [] for option_value, option_label in chain(self.choices, choices): if isinstance(option_label, (list, tuple)): output.append(u'<optgroup label="%s">' % escape(force_unicode(option_value))) for option in option_label: output.append(self.render_option(selected_choices, *option)) output.append(u'</optgroup>') else: output.append(self.render_option(selected_choices, option_value, option_label)) return u'\n'.join(output) class NullBooleanSelect(Select): """ A Select Widget intended to be used with NullBooleanField. """ def __init__(self, attrs=None): choices = ((u'1', ugettext('Unknown')), (u'2', ugettext('Yes')), (u'3', ugettext('No'))) super(NullBooleanSelect, self).__init__(attrs, choices) def render(self, name, value, attrs=None, choices=()): try: value = {True: u'2', False: u'3', u'2': u'2', u'3': u'3'}[value] except KeyError: value = u'1' return super(NullBooleanSelect, self).render(name, value, attrs, choices) def value_from_datadict(self, data, files, name): value = data.get(name, None) return {u'2': True, True: True, 'True': True, u'3': False, 'False': False, False: False}.get(value, None) def _has_changed(self, initial, data): # For a NullBooleanSelect, None (unknown) and False (No) # are not the same if initial is not None: initial = bool(initial) if data is not None: data = bool(data) return initial != data class SelectMultiple(Select): def render(self, name, value, attrs=None, choices=()): if value is None: value = [] final_attrs = self.build_attrs(attrs, name=name) output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)] options = self.render_options(choices, value) if options: output.append(options) output.append('</select>') return mark_safe(u'\n'.join(output)) def value_from_datadict(self, data, files, name): if isinstance(data, (MultiValueDict, MergeDict)): return data.getlist(name) return data.get(name, None) def _has_changed(self, initial, data): if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True for value1, value2 in zip(initial, data): if force_unicode(value1) != force_unicode(value2): return True return False class RadioInput(StrAndUnicode): """ An object used by RadioFieldRenderer that represents a single <input type='radio'>. """ def __init__(self, name, value, attrs, choice, index): self.name, self.value = name, value self.attrs = attrs self.choice_value = force_unicode(choice[0]) self.choice_label = force_unicode(choice[1]) self.index = index def __unicode__(self): if 'id' in self.attrs: label_for = ' for="%s_%s"' % (self.attrs['id'], self.index) else: label_for = '' choice_label = conditional_escape(force_unicode(self.choice_label)) return mark_safe(u'<label%s>%s %s</label>' % (label_for, self.tag(), choice_label)) def is_checked(self): return self.value == self.choice_value def tag(self): if 'id' in self.attrs: self.attrs['id'] = '%s_%s' % (self.attrs['id'], self.index) final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value) if self.is_checked(): final_attrs['checked'] = 'checked' return mark_safe(u'<input%s />' % flatatt(final_attrs)) class RadioFieldRenderer(StrAndUnicode): """ An object used by RadioSelect to enable customization of radio widgets. """ def __init__(self, name, value, attrs, choices): self.name, self.value, self.attrs = name, value, attrs self.choices = choices def __iter__(self): for i, choice in enumerate(self.choices): yield RadioInput(self.name, self.value, self.attrs.copy(), choice, i) def __getitem__(self, idx): choice = self.choices[idx] # Let the IndexError propogate return RadioInput(self.name, self.value, self.attrs.copy(), choice, idx) def __unicode__(self): return self.render() def render(self): """Outputs a <ul> for this set of radio fields.""" return mark_safe(u'<ul>\n%s\n</ul>' % u'\n'.join([u'<li>%s</li>' % force_unicode(w) for w in self])) class RadioSelect(Select): renderer = RadioFieldRenderer def __init__(self, *args, **kwargs): # Override the default renderer if we were passed one. renderer = kwargs.pop('renderer', None) if renderer: self.renderer = renderer super(RadioSelect, self).__init__(*args, **kwargs) def get_renderer(self, name, value, attrs=None, choices=()): """Returns an instance of the renderer.""" if value is None: value = '' str_value = force_unicode(value) # Normalize to string. final_attrs = self.build_attrs(attrs) choices = list(chain(self.choices, choices)) return self.renderer(name, str_value, final_attrs, choices) def render(self, name, value, attrs=None, choices=()): return self.get_renderer(name, value, attrs, choices).render() def id_for_label(self, id_): # RadioSelect is represented by multiple <input type="radio"> fields, # each of which has a distinct ID. The IDs are made distinct by a "_X" # suffix, where X is the zero-based index of the radio field. Thus, # the label for a RadioSelect should reference the first one ('_0'). if id_: id_ += '_0' return id_ id_for_label = classmethod(id_for_label) class CheckboxSelectMultiple(SelectMultiple): def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) output = [u'<ul>'] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) output.append(u'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label)) output.append(u'</ul>') return mark_safe(u'\n'.join(output)) def id_for_label(self, id_): # See the comment for RadioSelect.id_for_label() if id_: id_ += '_0' return id_ id_for_label = classmethod(id_for_label) class MultiWidget(Widget): """ A widget that is composed of multiple widgets. Its render() method is different than other widgets', because it has to figure out how to split a single value for display in multiple widgets. The ``value`` argument can be one of two things: * A list. * A normal value (e.g., a string) that has been "compressed" from a list of values. In the second case -- i.e., if the value is NOT a list -- render() will first "decompress" the value into a list before rendering it. It does so by calling the decompress() method, which MultiWidget subclasses must implement. This method takes a single "compressed" value and returns a list. When render() does its HTML rendering, each value in the list is rendered with the corresponding widget -- the first value is rendered in the first widget, the second value is rendered in the second widget, etc. Subclasses may implement format_output(), which takes the list of rendered widgets and returns a string of HTML that formats them any way you'd like. You'll probably want to use this class with MultiValueField. """ def __init__(self, widgets, attrs=None): self.widgets = [isinstance(w, type) and w() or w for w in widgets] super(MultiWidget, self).__init__(attrs) def render(self, name, value, attrs=None): if self.is_localized: for widget in self.widgets: widget.is_localized = self.is_localized # value is a list of values, each corresponding to a widget # in self.widgets. if not isinstance(value, list): value = self.decompress(value) output = [] final_attrs = self.build_attrs(attrs) id_ = final_attrs.get('id', None) for i, widget in enumerate(self.widgets): try: widget_value = value[i] except IndexError: widget_value = None if id_: final_attrs = dict(final_attrs, id='%s_%s' % (id_, i)) output.append(widget.render(name + '_%s' % i, widget_value, final_attrs)) return mark_safe(self.format_output(output)) def id_for_label(self, id_): # See the comment for RadioSelect.id_for_label() if id_: id_ += '_0' return id_ id_for_label = classmethod(id_for_label) def value_from_datadict(self, data, files, name): return [widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)] def _has_changed(self, initial, data): if initial is None: initial = [u'' for x in range(0, len(data))] else: if not isinstance(initial, list): initial = self.decompress(initial) for widget, initial, data in zip(self.widgets, initial, data): if widget._has_changed(initial, data): return True return False def format_output(self, rendered_widgets): """ Given a list of rendered widgets (as strings), returns a Unicode string representing the HTML for the whole lot. This hook allows you to format the HTML design of the widgets, if needed. """ return u''.join(rendered_widgets) def decompress(self, value): """ Returns a list of decompressed values for the given compressed value. The given value can be assumed to be valid, but not necessarily non-empty. """ raise NotImplementedError('Subclasses must implement this method.') def _get_media(self): "Media for a multiwidget is the combination of all media of the subwidgets" media = Media() for w in self.widgets: media = media + w.media return media media = property(_get_media) def __deepcopy__(self, memo): obj = super(MultiWidget, self).__deepcopy__(memo) obj.widgets = copy.deepcopy(self.widgets) return obj class SplitDateTimeWidget(MultiWidget): """ A Widget that splits datetime input into two <input type="text"> boxes. """ date_format = DateInput.format time_format = TimeInput.format def __init__(self, attrs=None, date_format=None, time_format=None): widgets = (DateInput(attrs=attrs, format=date_format), TimeInput(attrs=attrs, format=time_format)) super(SplitDateTimeWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return [value.date(), value.time().replace(microsecond=0)] return [None, None] class SplitHiddenDateTimeWidget(SplitDateTimeWidget): """ A Widget that splits datetime input into two <input type="hidden"> inputs. """ is_hidden = True def __init__(self, attrs=None, date_format=None, time_format=None): super(SplitHiddenDateTimeWidget, self).__init__(attrs, date_format, time_format) for widget in self.widgets: widget.input_type = 'hidden' widget.is_hidden = True
[ [ 8, 0, 0.0024, 0.0035, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0059, 0.0012, 0, 0.66, 0.0238, 125, 0, 1, 0, 0, 125, 0, 0 ], [ 1, 0, 0.0071, 0.0012, 0, 0.66...
[ "\"\"\"\nHTML Widget classes\n\"\"\"", "import django.utils.copycompat as copy", "from itertools import chain", "from django.conf import settings", "from django.utils.datastructures import MultiValueDict, MergeDict", "from django.utils.html import escape, conditional_escape", "from django.utils.translat...
""" Django validation and HTML form handling. TODO: Default value for field Field labels Nestable Forms FatalValidationError -- short-circuits all other validators on a form ValidationWarning "This form field requires foo.js" and form.js_includes() """ from django.core.exceptions import ValidationError from widgets import * from fields import * from forms import * from models import *
[ [ 8, 0, 0.3529, 0.6471, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.7647, 0.0588, 0, 0.66, 0.2, 160, 0, 1, 0, 0, 160, 0, 0 ], [ 1, 0, 0.8235, 0.0588, 0, 0.66, ...
[ "\"\"\"\nDjango validation and HTML form handling.\n\nTODO:\n Default value for field\n Field labels\n Nestable Forms\n FatalValidationError -- short-circuits all other validators on a form", "from django.core.exceptions import ValidationError", "from widgets import *", "from fields import *", "...
VERSION = (1, 3, 0, 'alpha', 1) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) from django.utils.version import get_svn_revision svn_rev = get_svn_revision() if svn_rev != u'SVN-unknown': version = "%s %s" % (version, svn_rev) return version
[ [ 14, 0, 0.0625, 0.0625, 0, 0.66, 0, 557, 0, 0, 0, 0, 0, 8, 0 ], [ 2, 0, 0.5938, 0.875, 0, 0.66, 1, 75, 0, 0, 1, 0, 0, 0, 1 ], [ 14, 1, 0.25, 0.0625, 1, 0.8, 0,...
[ "VERSION = (1, 3, 0, 'alpha', 1)", "def get_version():\n version = '%s.%s' % (VERSION[0], VERSION[1])\n if VERSION[2]:\n version = '%s.%s' % (version, VERSION[2])\n if VERSION[3:] == ('alpha', 0):\n version = '%s pre-alpha' % version\n else:\n if VERSION[3] != 'final':", " ve...
from django.dispatch import Signal class_prepared = Signal(providing_args=["class"]) pre_init = Signal(providing_args=["instance", "args", "kwargs"]) post_init = Signal(providing_args=["instance"]) pre_save = Signal(providing_args=["instance", "raw", "using"]) post_save = Signal(providing_args=["instance", "raw", "created", "using"]) pre_delete = Signal(providing_args=["instance", "using"]) post_delete = Signal(providing_args=["instance", "using"]) post_syncdb = Signal(providing_args=["class", "app", "created_models", "verbosity", "interactive"]) m2m_changed = Signal(providing_args=["action", "instance", "reverse", "model", "pk_set", "using"])
[ [ 1, 0, 0.0625, 0.0625, 0, 0.66, 0, 548, 0, 1, 0, 0, 548, 0, 0 ], [ 14, 0, 0.1875, 0.0625, 0, 0.66, 0.1111, 564, 3, 1, 0, 0, 592, 10, 1 ], [ 14, 0, 0.3125, 0.0625, 0, ...
[ "from django.dispatch import Signal", "class_prepared = Signal(providing_args=[\"class\"])", "pre_init = Signal(providing_args=[\"instance\", \"args\", \"kwargs\"])", "post_init = Signal(providing_args=[\"instance\"])", "pre_save = Signal(providing_args=[\"instance\", \"raw\", \"using\"])", "post_save = S...
from operator import attrgetter from django.db import connections, transaction, IntegrityError from django.db.models import signals, sql from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE from django.utils.datastructures import SortedDict from django.utils.functional import wraps def CASCADE(collector, field, sub_objs, using): collector.collect(sub_objs, source=field.rel.to, source_attr=field.name, nullable=field.null) if field.null and not connections[using].features.can_defer_constraint_checks: collector.add_field_update(field, None, sub_objs) def PROTECT(collector, field, sub_objs, using): raise IntegrityError("Cannot delete some instances of model '%s' because " "they are referenced through a protected foreign key: '%s.%s'" % ( field.rel.to.__name__, sub_objs[0].__class__.__name__, field.name )) def SET(value): if callable(value): def set_on_delete(collector, field, sub_objs, using): collector.add_field_update(field, value(), sub_objs) else: def set_on_delete(collector, field, sub_objs, using): collector.add_field_update(field, value, sub_objs) return set_on_delete SET_NULL = SET(None) def SET_DEFAULT(collector, field, sub_objs, using): collector.add_field_update(field, field.get_default(), sub_objs) def DO_NOTHING(collector, field, sub_objs, using): pass def force_managed(func): @wraps(func) def decorated(self, *args, **kwargs): if not transaction.is_managed(using=self.using): transaction.enter_transaction_management(using=self.using) forced_managed = True else: forced_managed = False try: func(self, *args, **kwargs) if forced_managed: transaction.commit(using=self.using) else: transaction.commit_unless_managed(using=self.using) finally: if forced_managed: transaction.leave_transaction_management(using=self.using) return decorated class Collector(object): def __init__(self, using): self.using = using self.data = {} # {model: [instances]} self.batches = {} # {model: {field: set([instances])}} self.field_updates = {} # {model: {(field, value): set([instances])}} self.dependencies = {} # {model: set([models])} def add(self, objs, source=None, nullable=False): """ Adds 'objs' to the collection of objects to be deleted. If the call is the result of a cascade, 'source' should be the model that caused it and 'nullable' should be set to True, if the relation can be null. Returns a list of all objects that were not already collected. """ if not objs: return [] new_objs = [] model = objs[0].__class__ instances = self.data.setdefault(model, []) for obj in objs: if obj not in instances: new_objs.append(obj) instances.extend(new_objs) # Nullable relationships can be ignored -- they are nulled out before # deleting, and therefore do not affect the order in which objects have # to be deleted. if new_objs and source is not None and not nullable: self.dependencies.setdefault(source, set()).add(model) return new_objs def add_batch(self, model, field, objs): """ Schedules a batch delete. Every instance of 'model' that is related to an instance of 'obj' through 'field' will be deleted. """ self.batches.setdefault(model, {}).setdefault(field, set()).update(objs) def add_field_update(self, field, value, objs): """ Schedules a field update. 'objs' must be a homogenous iterable collection of model instances (e.g. a QuerySet). """ if not objs: return model = objs[0].__class__ self.field_updates.setdefault( model, {}).setdefault( (field, value), set()).update(objs) def collect(self, objs, source=None, nullable=False, collect_related=True, source_attr=None): """ Adds 'objs' to the collection of objects to be deleted as well as all parent instances. 'objs' must be a homogenous iterable collection of model instances (e.g. a QuerySet). If 'collect_related' is True, related objects will be handled by their respective on_delete handler. If the call is the result of a cascade, 'source' should be the model that caused it and 'nullable' should be set to True, if the relation can be null. """ if not connections[self.using].features.supports_deleting_related_objects: collect_related = False new_objs = self.add(objs, source, nullable) if not new_objs: return model = new_objs[0].__class__ # Recursively collect parent models, but not their related objects. # These will be found by meta.get_all_related_objects() for parent_model, ptr in model._meta.parents.iteritems(): if ptr: parent_objs = [getattr(obj, ptr.name) for obj in new_objs] self.collect(parent_objs, source=model, source_attr=ptr.rel.related_name, collect_related=False) if collect_related: for related in model._meta.get_all_related_objects(include_hidden=True): field = related.field if related.model._meta.auto_created: self.add_batch(related.model, field, new_objs) else: sub_objs = self.related_objects(related, new_objs) if not sub_objs: continue field.rel.on_delete(self, field, sub_objs, self.using) # TODO This entire block is only needed as a special case to # support cascade-deletes for GenericRelation. It should be # removed/fixed when the ORM gains a proper abstraction for virtual # or composite fields, and GFKs are reworked to fit into that. for relation in model._meta.many_to_many: if not relation.rel.through: sub_objs = relation.bulk_related_objects(new_objs, self.using) self.collect(sub_objs, source=model, source_attr=relation.rel.related_name, nullable=True) def related_objects(self, related, objs): """ Gets a QuerySet of objects related to ``objs`` via the relation ``related``. """ return related.model._base_manager.using(self.using).filter( **{"%s__in" % related.field.name: objs} ) def instances_with_model(self): for model, instances in self.data.iteritems(): for obj in instances: yield model, obj def sort(self): sorted_models = [] models = self.data.keys() while len(sorted_models) < len(models): found = False for model in models: if model in sorted_models: continue dependencies = self.dependencies.get(model) if not (dependencies and dependencies.difference(sorted_models)): sorted_models.append(model) found = True if not found: return self.data = SortedDict([(model, self.data[model]) for model in sorted_models]) @force_managed def delete(self): # sort instance collections for instances in self.data.itervalues(): instances.sort(key=attrgetter("pk")) # if possible, bring the models in an order suitable for databases that # don't support transactions or cannot defer contraint checks until the # end of a transaction. self.sort() # send pre_delete signals for model, obj in self.instances_with_model(): if not model._meta.auto_created: signals.pre_delete.send( sender=model, instance=obj, using=self.using ) # update fields for model, instances_for_fieldvalues in self.field_updates.iteritems(): query = sql.UpdateQuery(model) for (field, value), instances in instances_for_fieldvalues.iteritems(): query.update_batch([obj.pk for obj in instances], {field.name: value}, self.using) # reverse instance collections for instances in self.data.itervalues(): instances.reverse() # delete batches for model, batches in self.batches.iteritems(): query = sql.DeleteQuery(model) for field, instances in batches.iteritems(): query.delete_batch([obj.pk for obj in instances], self.using, field) # delete instances for model, instances in self.data.iteritems(): query = sql.DeleteQuery(model) pk_list = [obj.pk for obj in instances] query.delete_batch(pk_list, self.using) # send post_delete signals for model, obj in self.instances_with_model(): if not model._meta.auto_created: signals.post_delete.send( sender=model, instance=obj, using=self.using ) # update collected instances for model, instances_for_fieldvalues in self.field_updates.iteritems(): for (field, value), instances in instances_for_fieldvalues.iteritems(): for obj in instances: setattr(obj, field.attname, value) for model, instances in self.data.iteritems(): for instance in instances: setattr(instance, model._meta.pk.attname, None)
[ [ 1, 0, 0.004, 0.004, 0, 0.66, 0, 616, 0, 1, 0, 0, 616, 0, 0 ], [ 1, 0, 0.0121, 0.004, 0, 0.66, 0.0769, 40, 0, 3, 0, 0, 40, 0, 0 ], [ 1, 0, 0.0161, 0.004, 0, 0.66, ...
[ "from operator import attrgetter", "from django.db import connections, transaction, IntegrityError", "from django.db.models import signals, sql", "from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE", "from django.utils.datastructures import SortedDict", "from django.utils.functional import...
from datetime import datetime from django.utils import tree from django.utils.copycompat import deepcopy class ExpressionNode(tree.Node): """ Base class for all query expressions. """ # Arithmetic connectors ADD = '+' SUB = '-' MUL = '*' DIV = '/' MOD = '%%' # This is a quoted % operator - it is quoted # because it can be used in strings that also # have parameter substitution. # Bitwise operators AND = '&' OR = '|' def __init__(self, children=None, connector=None, negated=False): if children is not None and len(children) > 1 and connector is None: raise TypeError('You have to specify a connector.') super(ExpressionNode, self).__init__(children, connector, negated) def _combine(self, other, connector, reversed, node=None): if reversed: obj = ExpressionNode([other], connector) obj.add(node or self, connector) else: obj = node or ExpressionNode([self], connector) obj.add(other, connector) return obj ################### # VISITOR METHODS # ################### def prepare(self, evaluator, query, allow_joins): return evaluator.prepare_node(self, query, allow_joins) def evaluate(self, evaluator, qn, connection): return evaluator.evaluate_node(self, qn, connection) ############# # OPERATORS # ############# def __add__(self, other): return self._combine(other, self.ADD, False) def __sub__(self, other): return self._combine(other, self.SUB, False) def __mul__(self, other): return self._combine(other, self.MUL, False) def __div__(self, other): return self._combine(other, self.DIV, False) def __mod__(self, other): return self._combine(other, self.MOD, False) def __and__(self, other): return self._combine(other, self.AND, False) def __or__(self, other): return self._combine(other, self.OR, False) def __radd__(self, other): return self._combine(other, self.ADD, True) def __rsub__(self, other): return self._combine(other, self.SUB, True) def __rmul__(self, other): return self._combine(other, self.MUL, True) def __rdiv__(self, other): return self._combine(other, self.DIV, True) def __rmod__(self, other): return self._combine(other, self.MOD, True) def __rand__(self, other): return self._combine(other, self.AND, True) def __ror__(self, other): return self._combine(other, self.OR, True) def prepare_database_save(self, unused): return self class F(ExpressionNode): """ An expression representing the value of the given field. """ def __init__(self, name): super(F, self).__init__(None, None, False) self.name = name def __deepcopy__(self, memodict): obj = super(F, self).__deepcopy__(memodict) obj.name = self.name return obj def prepare(self, evaluator, query, allow_joins): return evaluator.prepare_leaf(self, query, allow_joins) def evaluate(self, evaluator, qn, connection): return evaluator.evaluate_leaf(self, qn, connection)
[ [ 1, 0, 0.0088, 0.0088, 0, 0.66, 0, 426, 0, 1, 0, 0, 426, 0, 0 ], [ 1, 0, 0.0265, 0.0088, 0, 0.66, 0.25, 944, 0, 1, 0, 0, 944, 0, 0 ], [ 1, 0, 0.0354, 0.0088, 0, 0....
[ "from datetime import datetime", "from django.utils import tree", "from django.utils.copycompat import deepcopy", "class ExpressionNode(tree.Node):\n \"\"\"\n Base class for all query expressions.\n \"\"\"\n # Arithmetic connectors\n ADD = '+'\n SUB = '-'\n MUL = '*'", " \"\"\"\n ...
from django.core.exceptions import FieldError from django.db import connections from django.db.backends.util import truncate_name from django.db.models.sql.constants import * from django.db.models.sql.datastructures import EmptyResultSet from django.db.models.sql.expressions import SQLEvaluator from django.db.models.sql.query import get_proxied_model, get_order_dir, \ select_related_descend, Query class SQLCompiler(object): def __init__(self, query, connection, using): self.query = query self.connection = connection self.using = using self.quote_cache = {} def pre_sql_setup(self): """ Does any necessary class setup immediately prior to producing SQL. This is for things that can't necessarily be done in __init__ because we might not have all the pieces in place at that time. """ if not self.query.tables: self.query.join((None, self.query.model._meta.db_table, None, None)) if (not self.query.select and self.query.default_cols and not self.query.included_inherited_models): self.query.setup_inherited_models() if self.query.select_related and not self.query.related_select_cols: self.fill_related_selections() def quote_name_unless_alias(self, name): """ A wrapper around connection.ops.quote_name that doesn't quote aliases for table names. This avoids problems with some SQL dialects that treat quoted strings specially (e.g. PostgreSQL). """ if name in self.quote_cache: return self.quote_cache[name] if ((name in self.query.alias_map and name not in self.query.table_map) or name in self.query.extra_select): self.quote_cache[name] = name return name r = self.connection.ops.quote_name(name) self.quote_cache[name] = r return r def as_sql(self, with_limits=True, with_col_aliases=False): """ Creates the SQL for this query. Returns the SQL string and list of parameters. If 'with_limits' is False, any limit/offset information is not included in the query. """ if with_limits and self.query.low_mark == self.query.high_mark: return '', () self.pre_sql_setup() out_cols = self.get_columns(with_col_aliases) ordering, ordering_group_by = self.get_ordering() # This must come after 'select' and 'ordering' -- see docstring of # get_from_clause() for details. from_, f_params = self.get_from_clause() qn = self.quote_name_unless_alias where, w_params = self.query.where.as_sql(qn=qn, connection=self.connection) having, h_params = self.query.having.as_sql(qn=qn, connection=self.connection) params = [] for val in self.query.extra_select.itervalues(): params.extend(val[1]) result = ['SELECT'] if self.query.distinct: result.append('DISTINCT') result.append(', '.join(out_cols + self.query.ordering_aliases)) result.append('FROM') result.extend(from_) params.extend(f_params) if where: result.append('WHERE %s' % where) params.extend(w_params) grouping, gb_params = self.get_grouping() if grouping: if ordering: # If the backend can't group by PK (i.e., any database # other than MySQL), then any fields mentioned in the # ordering clause needs to be in the group by clause. if not self.connection.features.allows_group_by_pk: for col, col_params in ordering_group_by: if col not in grouping: grouping.append(str(col)) gb_params.extend(col_params) else: ordering = self.connection.ops.force_no_ordering() result.append('GROUP BY %s' % ', '.join(grouping)) params.extend(gb_params) if having: result.append('HAVING %s' % having) params.extend(h_params) if ordering: result.append('ORDER BY %s' % ', '.join(ordering)) if with_limits: if self.query.high_mark is not None: result.append('LIMIT %d' % (self.query.high_mark - self.query.low_mark)) if self.query.low_mark: if self.query.high_mark is None: val = self.connection.ops.no_limit_value() if val: result.append('LIMIT %d' % val) result.append('OFFSET %d' % self.query.low_mark) return ' '.join(result), tuple(params) def as_nested_sql(self): """ Perform the same functionality as the as_sql() method, returning an SQL string and parameters. However, the alias prefixes are bumped beforehand (in a copy -- the current query isn't changed), and any ordering is removed if the query is unsliced. Used when nesting this query inside another. """ obj = self.query.clone() if obj.low_mark == 0 and obj.high_mark is None: # If there is no slicing in use, then we can safely drop all ordering obj.clear_ordering(True) obj.bump_prefix() return obj.get_compiler(connection=self.connection).as_sql() def get_columns(self, with_aliases=False): """ Returns the list of columns to use in the select statement. If no columns have been specified, returns all columns relating to fields in the model. If 'with_aliases' is true, any column names that are duplicated (without the table names) are given unique aliases. This is needed in some cases to avoid ambiguity with nested queries. """ qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name result = ['(%s) AS %s' % (col[0], qn2(alias)) for alias, col in self.query.extra_select.iteritems()] aliases = set(self.query.extra_select.keys()) if with_aliases: col_aliases = aliases.copy() else: col_aliases = set() if self.query.select: only_load = self.deferred_to_columns() for col in self.query.select: if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and col not in only_load[table]: continue r = '%s.%s' % (qn(alias), qn(column)) if with_aliases: if col[1] in col_aliases: c_alias = 'Col%d' % len(col_aliases) result.append('%s AS %s' % (r, c_alias)) aliases.add(c_alias) col_aliases.add(c_alias) else: result.append('%s AS %s' % (r, qn2(col[1]))) aliases.add(r) col_aliases.add(col[1]) else: result.append(r) aliases.add(r) col_aliases.add(col[1]) else: result.append(col.as_sql(qn, self.connection)) if hasattr(col, 'alias'): aliases.add(col.alias) col_aliases.add(col.alias) elif self.query.default_cols: cols, new_aliases = self.get_default_columns(with_aliases, col_aliases) result.extend(cols) aliases.update(new_aliases) max_name_length = self.connection.ops.max_name_length() result.extend([ '%s%s' % ( aggregate.as_sql(qn, self.connection), alias is not None and ' AS %s' % qn(truncate_name(alias, max_name_length)) or '' ) for alias, aggregate in self.query.aggregate_select.items() ]) for table, col in self.query.related_select_cols: r = '%s.%s' % (qn(table), qn(col)) if with_aliases and col in col_aliases: c_alias = 'Col%d' % len(col_aliases) result.append('%s AS %s' % (r, c_alias)) aliases.add(c_alias) col_aliases.add(c_alias) else: result.append(r) aliases.add(r) col_aliases.add(col) self._select_aliases = aliases return result def get_default_columns(self, with_aliases=False, col_aliases=None, start_alias=None, opts=None, as_pairs=False, local_only=False): """ Computes the default columns for selecting every field in the base model. Will sometimes be called to pull in related models (e.g. via select_related), in which case "opts" and "start_alias" will be given to provide a starting point for the traversal. Returns a list of strings, quoted appropriately for use in SQL directly, as well as a set of aliases used in the select statement (if 'as_pairs' is True, returns a list of (alias, col_name) pairs instead of strings as the first component and None as the second component). """ result = [] if opts is None: opts = self.query.model._meta qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name aliases = set() only_load = self.deferred_to_columns() # Skip all proxy to the root proxied model proxied_model = get_proxied_model(opts) if start_alias: seen = {None: start_alias} for field, model in opts.get_fields_with_model(): if local_only and model is not None: continue if start_alias: try: alias = seen[model] except KeyError: if model is proxied_model: alias = start_alias else: link_field = opts.get_ancestor_link(model) alias = self.query.join((start_alias, model._meta.db_table, link_field.column, model._meta.pk.column)) seen[model] = alias else: # If we're starting from the base model of the queryset, the # aliases will have already been set up in pre_sql_setup(), so # we can save time here. alias = self.query.included_inherited_models[model] table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and field.column not in only_load[table]: continue if as_pairs: result.append((alias, field.column)) aliases.add(alias) continue if with_aliases and field.column in col_aliases: c_alias = 'Col%d' % len(col_aliases) result.append('%s.%s AS %s' % (qn(alias), qn2(field.column), c_alias)) col_aliases.add(c_alias) aliases.add(c_alias) else: r = '%s.%s' % (qn(alias), qn2(field.column)) result.append(r) aliases.add(r) if with_aliases: col_aliases.add(field.column) return result, aliases def get_ordering(self): """ Returns a tuple containing a list representing the SQL elements in the "order by" clause, and the list of SQL elements that need to be added to the GROUP BY clause as a result of the ordering. Also sets the ordering_aliases attribute on this instance to a list of extra aliases needed in the select. Determining the ordering SQL can change the tables we need to include, so this should be run *before* get_from_clause(). """ if self.query.extra_order_by: ordering = self.query.extra_order_by elif not self.query.default_ordering: ordering = self.query.order_by else: ordering = self.query.order_by or self.query.model._meta.ordering qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name distinct = self.query.distinct select_aliases = self._select_aliases result = [] group_by = [] ordering_aliases = [] if self.query.standard_ordering: asc, desc = ORDER_DIR['ASC'] else: asc, desc = ORDER_DIR['DESC'] # It's possible, due to model inheritance, that normal usage might try # to include the same field more than once in the ordering. We track # the table/column pairs we use and discard any after the first use. processed_pairs = set() for field in ordering: if field == '?': result.append(self.connection.ops.random_function_sql()) continue if isinstance(field, int): if field < 0: order = desc field = -field else: order = asc result.append('%s %s' % (field, order)) group_by.append((field, [])) continue col, order = get_order_dir(field, asc) if col in self.query.aggregate_select: result.append('%s %s' % (col, order)) continue if '.' in field: # This came in through an extra(order_by=...) addition. Pass it # on verbatim. table, col = col.split('.', 1) if (table, col) not in processed_pairs: elt = '%s.%s' % (qn(table), col) processed_pairs.add((table, col)) if not distinct or elt in select_aliases: result.append('%s %s' % (elt, order)) group_by.append((elt, [])) elif get_order_dir(field)[0] not in self.query.extra_select: # 'col' is of the form 'field' or 'field1__field2' or # '-field1__field2__field', etc. for table, col, order in self.find_ordering_name(field, self.query.model._meta, default_order=asc): if (table, col) not in processed_pairs: elt = '%s.%s' % (qn(table), qn2(col)) processed_pairs.add((table, col)) if distinct and elt not in select_aliases: ordering_aliases.append(elt) result.append('%s %s' % (elt, order)) group_by.append((elt, [])) else: elt = qn2(col) if distinct and col not in select_aliases: ordering_aliases.append(elt) result.append('%s %s' % (elt, order)) group_by.append(self.query.extra_select[col]) self.query.ordering_aliases = ordering_aliases return result, group_by def find_ordering_name(self, name, opts, alias=None, default_order='ASC', already_seen=None): """ Returns the table alias (the name might be ambiguous, the alias will not be) and column name for ordering by the given 'name' parameter. The 'name' is of the form 'field1__field2__...__fieldN'. """ name, order = get_order_dir(name, default_order) pieces = name.split(LOOKUP_SEP) if not alias: alias = self.query.get_initial_alias() field, target, opts, joins, last, extra = self.query.setup_joins(pieces, opts, alias, False) alias = joins[-1] col = target.column if not field.rel: # To avoid inadvertent trimming of a necessary alias, use the # refcount to show that we are referencing a non-relation field on # the model. self.query.ref_alias(alias) # Must use left outer joins for nullable fields and their relations. self.query.promote_alias_chain(joins, self.query.alias_map[joins[0]][JOIN_TYPE] == self.query.LOUTER) # If we get to this point and the field is a relation to another model, # append the default ordering for that model. if field.rel and len(joins) > 1 and opts.ordering: # Firstly, avoid infinite loops. if not already_seen: already_seen = set() join_tuple = tuple([self.query.alias_map[j][TABLE_NAME] for j in joins]) if join_tuple in already_seen: raise FieldError('Infinite loop caused by ordering.') already_seen.add(join_tuple) results = [] for item in opts.ordering: results.extend(self.find_ordering_name(item, opts, alias, order, already_seen)) return results if alias: # We have to do the same "final join" optimisation as in # add_filter, since the final column might not otherwise be part of # the select set (so we can't order on it). while 1: join = self.query.alias_map[alias] if col != join[RHS_JOIN_COL]: break self.query.unref_alias(alias) alias = join[LHS_ALIAS] col = join[LHS_JOIN_COL] return [(alias, col, order)] def get_from_clause(self): """ Returns a list of strings that are joined together to go after the "FROM" part of the query, as well as a list any extra parameters that need to be included. Sub-classes, can override this to create a from-clause via a "select". This should only be called after any SQL construction methods that might change the tables we need. This means the select columns and ordering must be done first. """ result = [] qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name first = True for alias in self.query.tables: if not self.query.alias_refcount[alias]: continue try: name, alias, join_type, lhs, lhs_col, col, nullable = self.query.alias_map[alias] except KeyError: # Extra tables can end up in self.tables, but not in the # alias_map if they aren't in a join. That's OK. We skip them. continue alias_str = (alias != name and ' %s' % alias or '') if join_type and not first: result.append('%s %s%s ON (%s.%s = %s.%s)' % (join_type, qn(name), alias_str, qn(lhs), qn2(lhs_col), qn(alias), qn2(col))) else: connector = not first and ', ' or '' result.append('%s%s%s' % (connector, qn(name), alias_str)) first = False for t in self.query.extra_tables: alias, unused = self.query.table_alias(t) # Only add the alias if it's not already present (the table_alias() # calls increments the refcount, so an alias refcount of one means # this is the only reference. if alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1: connector = not first and ', ' or '' result.append('%s%s' % (connector, qn(alias))) first = False return result, [] def get_grouping(self): """ Returns a tuple representing the SQL elements in the "group by" clause. """ qn = self.quote_name_unless_alias result, params = [], [] if self.query.group_by is not None: if len(self.query.model._meta.fields) == len(self.query.select) and \ self.connection.features.allows_group_by_pk: self.query.group_by = [(self.query.model._meta.db_table, self.query.model._meta.pk.column)] group_by = self.query.group_by or [] extra_selects = [] for extra_select, extra_params in self.query.extra_select.itervalues(): extra_selects.append(extra_select) params.extend(extra_params) for col in group_by + self.query.related_select_cols + extra_selects: if isinstance(col, (list, tuple)): result.append('%s.%s' % (qn(col[0]), qn(col[1]))) elif hasattr(col, 'as_sql'): result.append(col.as_sql(qn)) else: result.append('(%s)' % str(col)) return result, params def fill_related_selections(self, opts=None, root_alias=None, cur_depth=1, used=None, requested=None, restricted=None, nullable=None, dupe_set=None, avoid_set=None): """ Fill in the information needed for a select_related query. The current depth is measured as the number of connections away from the root model (for example, cur_depth=1 means we are looking at models with direct connections to the root model). """ if not restricted and self.query.max_depth and cur_depth > self.query.max_depth: # We've recursed far enough; bail out. return if not opts: opts = self.query.get_meta() root_alias = self.query.get_initial_alias() self.query.related_select_cols = [] self.query.related_select_fields = [] if not used: used = set() if dupe_set is None: dupe_set = set() if avoid_set is None: avoid_set = set() orig_dupe_set = dupe_set # Setup for the case when only particular related fields should be # included in the related selection. if requested is None: if isinstance(self.query.select_related, dict): requested = self.query.select_related restricted = True else: restricted = False for f, model in opts.get_fields_with_model(): if not select_related_descend(f, restricted, requested): continue # The "avoid" set is aliases we want to avoid just for this # particular branch of the recursion. They aren't permanently # forbidden from reuse in the related selection tables (which is # what "used" specifies). avoid = avoid_set.copy() dupe_set = orig_dupe_set.copy() table = f.rel.to._meta.db_table promote = nullable or f.null if model: int_opts = opts alias = root_alias alias_chain = [] for int_model in opts.get_base_chain(model): # Proxy model have elements in base chain # with no parents, assign the new options # object and skip to the next base in that # case if not int_opts.parents[int_model]: int_opts = int_model._meta continue lhs_col = int_opts.parents[int_model].column dedupe = lhs_col in opts.duplicate_targets if dedupe: avoid.update(self.query.dupe_avoidance.get((id(opts), lhs_col), ())) dupe_set.add((opts, lhs_col)) int_opts = int_model._meta alias = self.query.join((alias, int_opts.db_table, lhs_col, int_opts.pk.column), exclusions=used, promote=promote) alias_chain.append(alias) for (dupe_opts, dupe_col) in dupe_set: self.query.update_dupe_avoidance(dupe_opts, dupe_col, alias) if self.query.alias_map[root_alias][JOIN_TYPE] == self.query.LOUTER: self.query.promote_alias_chain(alias_chain, True) else: alias = root_alias dedupe = f.column in opts.duplicate_targets if dupe_set or dedupe: avoid.update(self.query.dupe_avoidance.get((id(opts), f.column), ())) if dedupe: dupe_set.add((opts, f.column)) alias = self.query.join((alias, table, f.column, f.rel.get_related_field().column), exclusions=used.union(avoid), promote=promote) used.add(alias) columns, aliases = self.get_default_columns(start_alias=alias, opts=f.rel.to._meta, as_pairs=True) self.query.related_select_cols.extend(columns) if self.query.alias_map[alias][JOIN_TYPE] == self.query.LOUTER: self.query.promote_alias_chain(aliases, True) self.query.related_select_fields.extend(f.rel.to._meta.fields) if restricted: next = requested.get(f.name, {}) else: next = False new_nullable = f.null or promote for dupe_opts, dupe_col in dupe_set: self.query.update_dupe_avoidance(dupe_opts, dupe_col, alias) self.fill_related_selections(f.rel.to._meta, alias, cur_depth + 1, used, next, restricted, new_nullable, dupe_set, avoid) if restricted: related_fields = [ (o.field, o.model) for o in opts.get_all_related_objects() if o.field.unique ] for f, model in related_fields: if not select_related_descend(f, restricted, requested, reverse=True): continue # The "avoid" set is aliases we want to avoid just for this # particular branch of the recursion. They aren't permanently # forbidden from reuse in the related selection tables (which is # what "used" specifies). avoid = avoid_set.copy() dupe_set = orig_dupe_set.copy() table = model._meta.db_table int_opts = opts alias = root_alias alias_chain = [] chain = opts.get_base_chain(f.rel.to) if chain is not None: for int_model in chain: # Proxy model have elements in base chain # with no parents, assign the new options # object and skip to the next base in that # case if not int_opts.parents[int_model]: int_opts = int_model._meta continue lhs_col = int_opts.parents[int_model].column dedupe = lhs_col in opts.duplicate_targets if dedupe: avoid.update((self.query.dupe_avoidance.get(id(opts), lhs_col), ())) dupe_set.add((opts, lhs_col)) int_opts = int_model._meta alias = self.query.join( (alias, int_opts.db_table, lhs_col, int_opts.pk.column), exclusions=used, promote=True, reuse=used ) alias_chain.append(alias) for dupe_opts, dupe_col in dupe_set: self.query.update_dupe_avoidance(dupe_opts, dupe_col, alias) dedupe = f.column in opts.duplicate_targets if dupe_set or dedupe: avoid.update(self.query.dupe_avoidance.get((id(opts), f.column), ())) if dedupe: dupe_set.add((opts, f.column)) alias = self.query.join( (alias, table, f.rel.get_related_field().column, f.column), exclusions=used.union(avoid), promote=True ) used.add(alias) columns, aliases = self.get_default_columns(start_alias=alias, opts=model._meta, as_pairs=True, local_only=True) self.query.related_select_cols.extend(columns) self.query.related_select_fields.extend(model._meta.fields) next = requested.get(f.related_query_name(), {}) new_nullable = f.null or None self.fill_related_selections(model._meta, table, cur_depth+1, used, next, restricted, new_nullable) def deferred_to_columns(self): """ Converts the self.deferred_loading data structure to mapping of table names to sets of column names which are to be loaded. Returns the dictionary. """ columns = {} self.query.deferred_to_data(columns, self.query.deferred_to_columns_cb) return columns def results_iter(self): """ Returns an iterator over the results from executing this query. """ resolve_columns = hasattr(self, 'resolve_columns') fields = None for rows in self.execute_sql(MULTI): for row in rows: if resolve_columns: if fields is None: # We only set this up here because # related_select_fields isn't populated until # execute_sql() has been called. if self.query.select_fields: fields = self.query.select_fields + self.query.related_select_fields else: fields = self.query.model._meta.fields # If the field was deferred, exclude it from being passed # into `resolve_columns` because it wasn't selected. only_load = self.deferred_to_columns() if only_load: db_table = self.query.model._meta.db_table fields = [f for f in fields if db_table in only_load and f.column in only_load[db_table]] row = self.resolve_columns(row, fields) if self.query.aggregate_select: aggregate_start = len(self.query.extra_select.keys()) + len(self.query.select) aggregate_end = aggregate_start + len(self.query.aggregate_select) row = tuple(row[:aggregate_start]) + tuple([ self.query.resolve_aggregate(value, aggregate, self.connection) for (alias, aggregate), value in zip(self.query.aggregate_select.items(), row[aggregate_start:aggregate_end]) ]) + tuple(row[aggregate_end:]) yield row def has_results(self): # This is always executed on a query clone, so we can modify self.query self.query.add_extra({'a': 1}, None, None, None, None, None) self.query.set_extra_mask(('a',)) return bool(self.execute_sql(SINGLE)) def execute_sql(self, result_type=MULTI): """ Run the query against the database and returns the result(s). The return value is a single data item if result_type is SINGLE, or an iterator over the results if the result_type is MULTI. result_type is either MULTI (use fetchmany() to retrieve all rows), SINGLE (only retrieve a single row), or None. In this last case, the cursor is returned if any query is executed, since it's used by subclasses such as InsertQuery). It's possible, however, that no query is needed, as the filters describe an empty set. In that case, None is returned, to avoid any unnecessary database interaction. """ try: sql, params = self.as_sql() if not sql: raise EmptyResultSet except EmptyResultSet: if result_type == MULTI: return empty_iter() else: return cursor = self.connection.cursor() cursor.execute(sql, params) if not result_type: return cursor if result_type == SINGLE: if self.query.ordering_aliases: return cursor.fetchone()[:-len(self.query.ordering_aliases)] return cursor.fetchone() # The MULTI case. if self.query.ordering_aliases: result = order_modified_iter(cursor, len(self.query.ordering_aliases), self.connection.features.empty_fetchmany_value) else: result = iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)), self.connection.features.empty_fetchmany_value) if not self.connection.features.can_use_chunked_reads: # If we are using non-chunked reads, we return the same data # structure as normally, but ensure it is all read into memory # before going any further. return list(result) return result class SQLInsertCompiler(SQLCompiler): def placeholder(self, field, val): if field is None: # A field value of None means the value is raw. return val elif hasattr(field, 'get_placeholder'): # Some fields (e.g. geo fields) need special munging before # they can be inserted. return field.get_placeholder(val, self.connection) else: # Return the common case for the placeholder return '%s' def as_sql(self): # We don't need quote_name_unless_alias() here, since these are all # going to be column names (so we can avoid the extra overhead). qn = self.connection.ops.quote_name opts = self.query.model._meta result = ['INSERT INTO %s' % qn(opts.db_table)] result.append('(%s)' % ', '.join([qn(c) for c in self.query.columns])) values = [self.placeholder(*v) for v in self.query.values] result.append('VALUES (%s)' % ', '.join(values)) params = self.query.params if self.return_id and self.connection.features.can_return_id_from_insert: col = "%s.%s" % (qn(opts.db_table), qn(opts.pk.column)) r_fmt, r_params = self.connection.ops.return_insert_id() result.append(r_fmt % col) params = params + r_params return ' '.join(result), params def execute_sql(self, return_id=False): self.return_id = return_id cursor = super(SQLInsertCompiler, self).execute_sql(None) if not (return_id and cursor): return if self.connection.features.can_return_id_from_insert: return self.connection.ops.fetch_returned_insert_id(cursor) return self.connection.ops.last_insert_id(cursor, self.query.model._meta.db_table, self.query.model._meta.pk.column) class SQLDeleteCompiler(SQLCompiler): def as_sql(self): """ Creates the SQL for this query. Returns the SQL string and list of parameters. """ assert len(self.query.tables) == 1, \ "Can only delete from one table at a time." qn = self.quote_name_unless_alias result = ['DELETE FROM %s' % qn(self.query.tables[0])] where, params = self.query.where.as_sql(qn=qn, connection=self.connection) result.append('WHERE %s' % where) return ' '.join(result), tuple(params) class SQLUpdateCompiler(SQLCompiler): def as_sql(self): """ Creates the SQL for this query. Returns the SQL string and list of parameters. """ from django.db.models.base import Model self.pre_sql_setup() if not self.query.values: return '', () table = self.query.tables[0] qn = self.quote_name_unless_alias result = ['UPDATE %s' % qn(table)] result.append('SET') values, update_params = [], [] for field, model, val in self.query.values: if hasattr(val, 'prepare_database_save'): val = val.prepare_database_save(field) else: val = field.get_db_prep_save(val, connection=self.connection) # Getting the placeholder for the field. if hasattr(field, 'get_placeholder'): placeholder = field.get_placeholder(val, self.connection) else: placeholder = '%s' if hasattr(val, 'evaluate'): val = SQLEvaluator(val, self.query, allow_joins=False) name = field.column if hasattr(val, 'as_sql'): sql, params = val.as_sql(qn, self.connection) values.append('%s = %s' % (qn(name), sql)) update_params.extend(params) elif val is not None: values.append('%s = %s' % (qn(name), placeholder)) update_params.append(val) else: values.append('%s = NULL' % qn(name)) if not values: return '', () result.append(', '.join(values)) where, params = self.query.where.as_sql(qn=qn, connection=self.connection) if where: result.append('WHERE %s' % where) return ' '.join(result), tuple(update_params + params) def execute_sql(self, result_type): """ Execute the specified update. Returns the number of rows affected by the primary update query. The "primary update query" is the first non-empty query that is executed. Row counts for any subsequent, related queries are not available. """ cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) rows = cursor and cursor.rowcount or 0 is_empty = cursor is None del cursor for query in self.query.get_related_updates(): aux_rows = query.get_compiler(self.using).execute_sql(result_type) if is_empty: rows = aux_rows is_empty = False return rows def pre_sql_setup(self): """ If the update depends on results from other tables, we need to do some munging of the "where" conditions to match the format required for (portable) SQL updates. That is done here. Further, if we are going to be running multiple updates, we pull out the id values to update at this point so that they don't change as a result of the progressive updates. """ self.query.select_related = False self.query.clear_ordering(True) super(SQLUpdateCompiler, self).pre_sql_setup() count = self.query.count_active_tables() if not self.query.related_updates and count == 1: return # We need to use a sub-select in the where clause to filter on things # from other tables. query = self.query.clone(klass=Query) query.bump_prefix() query.extra = {} query.select = [] query.add_fields([query.model._meta.pk.name]) must_pre_select = count > 1 and not self.connection.features.update_can_self_select # Now we adjust the current query: reset the where clause and get rid # of all the tables we don't need (since they're in the sub-select). self.query.where = self.query.where_class() if self.query.related_updates or must_pre_select: # Either we're using the idents in multiple update queries (so # don't want them to change), or the db backend doesn't support # selecting from the updating table (e.g. MySQL). idents = [] for rows in query.get_compiler(self.using).execute_sql(MULTI): idents.extend([r[0] for r in rows]) self.query.add_filter(('pk__in', idents)) self.query.related_ids = idents else: # The fast path. Filters and updates in one query. self.query.add_filter(('pk__in', query)) for alias in self.query.tables[1:]: self.query.alias_refcount[alias] = 0 class SQLAggregateCompiler(SQLCompiler): def as_sql(self, qn=None): """ Creates the SQL for this query. Returns the SQL string and list of parameters. """ if qn is None: qn = self.quote_name_unless_alias sql = ('SELECT %s FROM (%s) subquery' % ( ', '.join([ aggregate.as_sql(qn, self.connection) for aggregate in self.query.aggregate_select.values() ]), self.query.subquery) ) params = self.query.sub_params return (sql, params) class SQLDateCompiler(SQLCompiler): def results_iter(self): """ Returns an iterator over the results from executing this query. """ resolve_columns = hasattr(self, 'resolve_columns') if resolve_columns: from django.db.models.fields import DateTimeField fields = [DateTimeField()] else: from django.db.backends.util import typecast_timestamp needs_string_cast = self.connection.features.needs_datetime_string_cast offset = len(self.query.extra_select) for rows in self.execute_sql(MULTI): for row in rows: date = row[offset] if resolve_columns: date = self.resolve_columns(row, fields)[offset] elif needs_string_cast: date = typecast_timestamp(str(date)) yield date def empty_iter(): """ Returns an iterator containing no results. """ yield iter([]).next() def order_modified_iter(cursor, trim, sentinel): """ Yields blocks of rows from a cursor. We use this iterator in the special case when extra output columns have been added to support ordering requirements. We must trim those extra columns before anything else can use the results, since they're only needed to make the SQL valid. """ for rows in iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)), sentinel): yield [r[:-trim] for r in rows]
[ [ 1, 0, 0.001, 0.001, 0, 0.66, 0, 160, 0, 1, 0, 0, 160, 0, 0 ], [ 1, 0, 0.002, 0.001, 0, 0.66, 0.0714, 40, 0, 1, 0, 0, 40, 0, 0 ], [ 1, 0, 0.0031, 0.001, 0, 0.66, ...
[ "from django.core.exceptions import FieldError", "from django.db import connections", "from django.db.backends.util import truncate_name", "from django.db.models.sql.constants import *", "from django.db.models.sql.datastructures import EmptyResultSet", "from django.db.models.sql.expressions import SQLEval...
""" Query subclasses which provide extra functionality beyond simple data retrieval. """ from django.core.exceptions import FieldError from django.db import connections from django.db.models.fields import DateField, FieldDoesNotExist from django.db.models.sql.constants import * from django.db.models.sql.datastructures import Date from django.db.models.sql.expressions import SQLEvaluator from django.db.models.sql.query import Query from django.db.models.sql.where import AND, Constraint __all__ = ['DeleteQuery', 'UpdateQuery', 'InsertQuery', 'DateQuery', 'AggregateQuery'] class DeleteQuery(Query): """ Delete queries are done through this class, since they are more constrained than general queries. """ compiler = 'SQLDeleteCompiler' def do_query(self, table, where, using): self.tables = [table] self.where = where self.get_compiler(using).execute_sql(None) def delete_batch(self, pk_list, using, field=None): """ Set up and execute delete queries for all the objects in pk_list. More than one physical query may be executed if there are a lot of values in pk_list. """ if not field: field = self.model._meta.pk for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE): where = self.where_class() where.add((Constraint(None, field.column, field), 'in', pk_list[offset : offset + GET_ITERATOR_CHUNK_SIZE]), AND) self.do_query(self.model._meta.db_table, where, using=using) class UpdateQuery(Query): """ Represents an "update" SQL query. """ compiler = 'SQLUpdateCompiler' def __init__(self, *args, **kwargs): super(UpdateQuery, self).__init__(*args, **kwargs) self._setup_query() def _setup_query(self): """ Runs on initialization and after cloning. Any attributes that would normally be set in __init__ should go in here, instead, so that they are also set up after a clone() call. """ self.values = [] self.related_ids = None if not hasattr(self, 'related_updates'): self.related_updates = {} def clone(self, klass=None, **kwargs): return super(UpdateQuery, self).clone(klass, related_updates=self.related_updates.copy(), **kwargs) def update_batch(self, pk_list, values, using): pk_field = self.model._meta.pk self.add_update_values(values) for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE): self.where = self.where_class() self.where.add((Constraint(None, pk_field.column, pk_field), 'in', pk_list[offset : offset + GET_ITERATOR_CHUNK_SIZE]), AND) self.get_compiler(using).execute_sql(None) def add_update_values(self, values): """ Convert a dictionary of field name to value mappings into an update query. This is the entry point for the public update() method on querysets. """ values_seq = [] for name, val in values.iteritems(): field, model, direct, m2m = self.model._meta.get_field_by_name(name) if not direct or m2m: raise FieldError('Cannot update model field %r (only non-relations and foreign keys permitted).' % field) if model: self.add_related_update(model, field, val) continue values_seq.append((field, model, val)) return self.add_update_fields(values_seq) def add_update_fields(self, values_seq): """ Turn a sequence of (field, model, value) triples into an update query. Used by add_update_values() as well as the "fast" update path when saving models. """ self.values.extend(values_seq) def add_related_update(self, model, field, value): """ Adds (name, value) to an update query for an ancestor model. Updates are coalesced so that we only run one update query per ancestor. """ try: self.related_updates[model].append((field, None, value)) except KeyError: self.related_updates[model] = [(field, None, value)] def get_related_updates(self): """ Returns a list of query objects: one for each update required to an ancestor model. Each query will have the same filtering conditions as the current query but will only update a single table. """ if not self.related_updates: return [] result = [] for model, values in self.related_updates.iteritems(): query = UpdateQuery(model) query.values = values if self.related_ids is not None: query.add_filter(('pk__in', self.related_ids)) result.append(query) return result class InsertQuery(Query): compiler = 'SQLInsertCompiler' def __init__(self, *args, **kwargs): super(InsertQuery, self).__init__(*args, **kwargs) self.columns = [] self.values = [] self.params = () def clone(self, klass=None, **kwargs): extras = { 'columns': self.columns[:], 'values': self.values[:], 'params': self.params } extras.update(kwargs) return super(InsertQuery, self).clone(klass, **extras) def insert_values(self, insert_values, raw_values=False): """ Set up the insert query from the 'insert_values' dictionary. The dictionary gives the model field names and their target values. If 'raw_values' is True, the values in the 'insert_values' dictionary are inserted directly into the query, rather than passed as SQL parameters. This provides a way to insert NULL and DEFAULT keywords into the query, for example. """ placeholders, values = [], [] for field, val in insert_values: placeholders.append((field, val)) self.columns.append(field.column) values.append(val) if raw_values: self.values.extend([(None, v) for v in values]) else: self.params += tuple(values) self.values.extend(placeholders) class DateQuery(Query): """ A DateQuery is a normal query, except that it specifically selects a single date field. This requires some special handling when converting the results back to Python objects, so we put it in a separate class. """ compiler = 'SQLDateCompiler' def add_date_select(self, field_name, lookup_type, order='ASC'): """ Converts the query into a date extraction query. """ try: result = self.setup_joins( field_name.split(LOOKUP_SEP), self.get_meta(), self.get_initial_alias(), False ) except FieldError: raise FieldDoesNotExist("%s has no field named '%s'" % ( self.model._meta.object_name, field_name )) field = result[0] assert isinstance(field, DateField), "%r isn't a DateField." \ % field.name alias = result[3][-1] select = Date((alias, field.column), lookup_type) self.select = [select] self.select_fields = [None] self.select_related = False # See #7097. self.set_extra_mask([]) self.distinct = True self.order_by = order == 'ASC' and [1] or [-1] if field.null: self.add_filter(("%s__isnull" % field_name, False)) class AggregateQuery(Query): """ An AggregateQuery takes another query as a parameter to the FROM clause and only selects the elements in the provided list. """ compiler = 'SQLAggregateCompiler' def add_subquery(self, query, using): self.subquery, self.sub_params = query.get_compiler(using).as_sql(with_col_aliases=True)
[ [ 8, 0, 0.009, 0.0135, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0225, 0.0045, 0, 0.66, 0.0714, 160, 0, 1, 0, 0, 160, 0, 0 ], [ 1, 0, 0.027, 0.0045, 0, 0.66, ...
[ "\"\"\"\nQuery subclasses which provide extra functionality beyond simple data retrieval.\n\"\"\"", "from django.core.exceptions import FieldError", "from django.db import connections", "from django.db.models.fields import DateField, FieldDoesNotExist", "from django.db.models.sql.constants import *", "fro...
from django.core.exceptions import FieldError from django.db.models.fields import FieldDoesNotExist from django.db.models.sql.constants import LOOKUP_SEP class SQLEvaluator(object): def __init__(self, expression, query, allow_joins=True): self.expression = expression self.opts = query.get_meta() self.cols = {} self.contains_aggregate = False self.expression.prepare(self, query, allow_joins) def prepare(self): return self def as_sql(self, qn, connection): return self.expression.evaluate(self, qn, connection) def relabel_aliases(self, change_map): for node, col in self.cols.items(): self.cols[node] = (change_map.get(col[0], col[0]), col[1]) ##################################################### # Vistor methods for initial expression preparation # ##################################################### def prepare_node(self, node, query, allow_joins): for child in node.children: if hasattr(child, 'prepare'): child.prepare(self, query, allow_joins) def prepare_leaf(self, node, query, allow_joins): if not allow_joins and LOOKUP_SEP in node.name: raise FieldError("Joined field references are not permitted in this query") field_list = node.name.split(LOOKUP_SEP) if (len(field_list) == 1 and node.name in query.aggregate_select.keys()): self.contains_aggregate = True self.cols[node] = query.aggregate_select[node.name] else: try: field, source, opts, join_list, last, _ = query.setup_joins( field_list, query.get_meta(), query.get_initial_alias(), False) col, _, join_list = query.trim_joins(source, join_list, last, False) self.cols[node] = (join_list[-1], col) except FieldDoesNotExist: raise FieldError("Cannot resolve keyword %r into field. " "Choices are: %s" % (self.name, [f.name for f in self.opts.fields])) ################################################## # Vistor methods for final expression evaluation # ################################################## def evaluate_node(self, node, qn, connection): expressions = [] expression_params = [] for child in node.children: if hasattr(child, 'evaluate'): sql, params = child.evaluate(self, qn, connection) else: sql, params = '%s', (child,) if len(getattr(child, 'children', [])) > 1: format = '(%s)' else: format = '%s' if sql: expressions.append(format % sql) expression_params.extend(params) return connection.ops.combine_expression(node.connector, expressions), expression_params def evaluate_leaf(self, node, qn, connection): col = self.cols[node] if hasattr(col, 'as_sql'): return col.as_sql(qn, connection), () else: return '%s.%s' % (qn(col[0]), qn(col[1])), ()
[ [ 1, 0, 0.0119, 0.0119, 0, 0.66, 0, 160, 0, 1, 0, 0, 160, 0, 0 ], [ 1, 0, 0.0238, 0.0119, 0, 0.66, 0.3333, 5, 0, 1, 0, 0, 5, 0, 0 ], [ 1, 0, 0.0357, 0.0119, 0, 0.66...
[ "from django.core.exceptions import FieldError", "from django.db.models.fields import FieldDoesNotExist", "from django.db.models.sql.constants import LOOKUP_SEP", "class SQLEvaluator(object):\n def __init__(self, expression, query, allow_joins=True):\n self.expression = expression\n self.opts...
import re # Valid query types (a dictionary is used for speedy lookups). QUERY_TERMS = dict([(x, None) for x in ( 'exact', 'iexact', 'contains', 'icontains', 'gt', 'gte', 'lt', 'lte', 'in', 'startswith', 'istartswith', 'endswith', 'iendswith', 'range', 'year', 'month', 'day', 'week_day', 'isnull', 'search', 'regex', 'iregex', )]) # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space. GET_ITERATOR_CHUNK_SIZE = 100 # Separator used to split filter strings apart. LOOKUP_SEP = '__' # Constants to make looking up tuple values clearer. # Join lists (indexes into the tuples that are values in the alias_map # dictionary in the Query class). TABLE_NAME = 0 RHS_ALIAS = 1 JOIN_TYPE = 2 LHS_ALIAS = 3 LHS_JOIN_COL = 4 RHS_JOIN_COL = 5 NULLABLE = 6 # How many results to expect from a cursor.execute call MULTI = 'multi' SINGLE = 'single' ORDER_PATTERN = re.compile(r'\?|[-+]?[.\w]+$') ORDER_DIR = { 'ASC': ('ASC', 'DESC'), 'DESC': ('DESC', 'ASC')}
[ [ 1, 0, 0.027, 0.027, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 14, 0, 0.1622, 0.1351, 0, 0.66, 0.0714, 857, 3, 1, 0, 0, 827, 10, 1 ], [ 14, 0, 0.3243, 0.027, 0, ...
[ "import re", "QUERY_TERMS = dict([(x, None) for x in (\n 'exact', 'iexact', 'contains', 'icontains', 'gt', 'gte', 'lt', 'lte', 'in',\n 'startswith', 'istartswith', 'endswith', 'iendswith', 'range', 'year',\n 'month', 'day', 'week_day', 'isnull', 'search', 'regex', 'iregex',\n )])", "GET_ITERATOR_CHU...
""" Classes to represent the default SQL aggregate functions """ class AggregateField(object): """An internal field mockup used to identify aggregates in the data-conversion parts of the database backend. """ def __init__(self, internal_type): self.internal_type = internal_type def get_internal_type(self): return self.internal_type ordinal_aggregate_field = AggregateField('IntegerField') computed_aggregate_field = AggregateField('FloatField') class Aggregate(object): """ Default SQL Aggregate. """ is_ordinal = False is_computed = False sql_template = '%(function)s(%(field)s)' def __init__(self, col, source=None, is_summary=False, **extra): """Instantiate an SQL aggregate * col is a column reference describing the subject field of the aggregate. It can be an alias, or a tuple describing a table and column name. * source is the underlying field or aggregate definition for the column reference. If the aggregate is not an ordinal or computed type, this reference is used to determine the coerced output type of the aggregate. * extra is a dictionary of additional data to provide for the aggregate definition Also utilizes the class variables: * sql_function, the name of the SQL function that implements the aggregate. * sql_template, a template string that is used to render the aggregate into SQL. * is_ordinal, a boolean indicating if the output of this aggregate is an integer (e.g., a count) * is_computed, a boolean indicating if this output of this aggregate is a computed float (e.g., an average), regardless of the input type. """ self.col = col self.source = source self.is_summary = is_summary self.extra = extra # Follow the chain of aggregate sources back until you find an # actual field, or an aggregate that forces a particular output # type. This type of this field will be used to coerce values # retrieved from the database. tmp = self while tmp and isinstance(tmp, Aggregate): if getattr(tmp, 'is_ordinal', False): tmp = ordinal_aggregate_field elif getattr(tmp, 'is_computed', False): tmp = computed_aggregate_field else: tmp = tmp.source self.field = tmp def relabel_aliases(self, change_map): if isinstance(self.col, (list, tuple)): self.col = (change_map.get(self.col[0], self.col[0]), self.col[1]) def as_sql(self, qn, connection): "Return the aggregate, rendered as SQL." if hasattr(self.col, 'as_sql'): field_name = self.col.as_sql(qn, connection) elif isinstance(self.col, (list, tuple)): field_name = '.'.join([qn(c) for c in self.col]) else: field_name = self.col params = { 'function': self.sql_function, 'field': field_name } params.update(self.extra) return self.sql_template % params class Avg(Aggregate): is_computed = True sql_function = 'AVG' class Count(Aggregate): is_ordinal = True sql_function = 'COUNT' sql_template = '%(function)s(%(distinct)s%(field)s)' def __init__(self, col, distinct=False, **extra): super(Count, self).__init__(col, distinct=distinct and 'DISTINCT ' or '', **extra) class Max(Aggregate): sql_function = 'MAX' class Min(Aggregate): sql_function = 'MIN' class StdDev(Aggregate): is_computed = True def __init__(self, col, sample=False, **extra): super(StdDev, self).__init__(col, **extra) self.sql_function = sample and 'STDDEV_SAMP' or 'STDDEV_POP' class Sum(Aggregate): sql_function = 'SUM' class Variance(Aggregate): is_computed = True def __init__(self, col, sample=False, **extra): super(Variance, self).__init__(col, **extra) self.sql_function = sample and 'VAR_SAMP' or 'VAR_POP'
[ [ 8, 0, 0.0157, 0.0236, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 3, 0, 0.0669, 0.063, 0, 0.66, 0.0909, 733, 0, 2, 0, 0, 186, 0, 0 ], [ 8, 1, 0.0551, 0.0236, 1, 0.07,...
[ "\"\"\"\nClasses to represent the default SQL aggregate functions\n\"\"\"", "class AggregateField(object):\n \"\"\"An internal field mockup used to identify aggregates in the\n data-conversion parts of the database backend.\n \"\"\"\n def __init__(self, internal_type):\n self.internal_type = in...
""" Code to manage the creation and SQL rendering of 'where' constraints. """ import datetime from itertools import repeat from django.utils import tree from django.db.models.fields import Field from django.db.models.query_utils import QueryWrapper from datastructures import EmptyResultSet, FullResultSet # Connection types AND = 'AND' OR = 'OR' class EmptyShortCircuit(Exception): """ Internal exception used to indicate that a "matches nothing" node should be added to the where-clause. """ pass class WhereNode(tree.Node): """ Used to represent the SQL where-clause. The class is tied to the Query class that created it (in order to create the correct SQL). The children in this tree are usually either Q-like objects or lists of [table_alias, field_name, db_type, lookup_type, value_annotation, params]. However, a child could also be any class with as_sql() and relabel_aliases() methods. """ default = AND def add(self, data, connector): """ Add a node to the where-tree. If the data is a list or tuple, it is expected to be of the form (obj, lookup_type, value), where obj is a Constraint object, and is then slightly munged before being stored (to avoid storing any reference to field objects). Otherwise, the 'data' is stored unchanged and can be any class with an 'as_sql()' method. """ if not isinstance(data, (list, tuple)): super(WhereNode, self).add(data, connector) return obj, lookup_type, value = data if hasattr(value, '__iter__') and hasattr(value, 'next'): # Consume any generators immediately, so that we can determine # emptiness and transform any non-empty values correctly. value = list(value) # The "annotation" parameter is used to pass auxilliary information # about the value(s) to the query construction. Specifically, datetime # and empty values need special handling. Other types could be used # here in the future (using Python types is suggested for consistency). if isinstance(value, datetime.datetime): annotation = datetime.datetime elif hasattr(value, 'value_annotation'): annotation = value.value_annotation else: annotation = bool(value) if hasattr(obj, "prepare"): value = obj.prepare(lookup_type, value) super(WhereNode, self).add((obj, lookup_type, annotation, value), connector) return super(WhereNode, self).add((obj, lookup_type, annotation, value), connector) def as_sql(self, qn, connection): """ Returns the SQL version of the where clause and the value to be substituted in. Returns None, None if this node is empty. If 'node' is provided, that is the root of the SQL generation (generally not needed except by the internal implementation for recursion). """ if not self.children: return None, [] result = [] result_params = [] empty = True for child in self.children: try: if hasattr(child, 'as_sql'): sql, params = child.as_sql(qn=qn, connection=connection) else: # A leaf node in the tree. sql, params = self.make_atom(child, qn, connection) except EmptyResultSet: if self.connector == AND and not self.negated: # We can bail out early in this particular case (only). raise elif self.negated: empty = False continue except FullResultSet: if self.connector == OR: if self.negated: empty = True break # We match everything. No need for any constraints. return '', [] if self.negated: empty = True continue empty = False if sql: result.append(sql) result_params.extend(params) if empty: raise EmptyResultSet conn = ' %s ' % self.connector sql_string = conn.join(result) if sql_string: if self.negated: sql_string = 'NOT (%s)' % sql_string elif len(self.children) != 1: sql_string = '(%s)' % sql_string return sql_string, result_params def make_atom(self, child, qn, connection): """ Turn a tuple (table_alias, column_name, db_type, lookup_type, value_annot, params) into valid SQL. Returns the string for the SQL fragment and the parameters to use for it. """ lvalue, lookup_type, value_annot, params_or_value = child if hasattr(lvalue, 'process'): try: lvalue, params = lvalue.process(lookup_type, params_or_value, connection) except EmptyShortCircuit: raise EmptyResultSet else: params = Field().get_db_prep_lookup(lookup_type, params_or_value, connection=connection, prepared=True) if isinstance(lvalue, tuple): # A direct database column lookup. field_sql = self.sql_for_columns(lvalue, qn, connection) else: # A smart object with an as_sql() method. field_sql = lvalue.as_sql(qn, connection) if value_annot is datetime.datetime: cast_sql = connection.ops.datetime_cast_sql() else: cast_sql = '%s' if hasattr(params, 'as_sql'): extra, params = params.as_sql(qn, connection) cast_sql = '' else: extra = '' if (len(params) == 1 and params[0] == '' and lookup_type == 'exact' and connection.features.interprets_empty_strings_as_nulls): lookup_type = 'isnull' value_annot = True if lookup_type in connection.operators: format = "%s %%s %%s" % (connection.ops.lookup_cast(lookup_type),) return (format % (field_sql, connection.operators[lookup_type] % cast_sql, extra), params) if lookup_type == 'in': if not value_annot: raise EmptyResultSet if extra: return ('%s IN %s' % (field_sql, extra), params) max_in_list_size = connection.ops.max_in_list_size() if max_in_list_size and len(params) > max_in_list_size: # Break up the params list into an OR of manageable chunks. in_clause_elements = ['('] for offset in xrange(0, len(params), max_in_list_size): if offset > 0: in_clause_elements.append(' OR ') in_clause_elements.append('%s IN (' % field_sql) group_size = min(len(params) - offset, max_in_list_size) param_group = ', '.join(repeat('%s', group_size)) in_clause_elements.append(param_group) in_clause_elements.append(')') in_clause_elements.append(')') return ''.join(in_clause_elements), params else: return ('%s IN (%s)' % (field_sql, ', '.join(repeat('%s', len(params)))), params) elif lookup_type in ('range', 'year'): return ('%s BETWEEN %%s and %%s' % field_sql, params) elif lookup_type in ('month', 'day', 'week_day'): return ('%s = %%s' % connection.ops.date_extract_sql(lookup_type, field_sql), params) elif lookup_type == 'isnull': return ('%s IS %sNULL' % (field_sql, (not value_annot and 'NOT ' or '')), ()) elif lookup_type == 'search': return (connection.ops.fulltext_search_sql(field_sql), params) elif lookup_type in ('regex', 'iregex'): return connection.ops.regex_lookup(lookup_type) % (field_sql, cast_sql), params raise TypeError('Invalid lookup_type: %r' % lookup_type) def sql_for_columns(self, data, qn, connection): """ Returns the SQL fragment used for the left-hand side of a column constraint (for example, the "T1.foo" portion in the clause "WHERE ... T1.foo = 6"). """ table_alias, name, db_type = data if table_alias: lhs = '%s.%s' % (qn(table_alias), qn(name)) else: lhs = qn(name) return connection.ops.field_cast_sql(db_type) % lhs def relabel_aliases(self, change_map, node=None): """ Relabels the alias values of any children. 'change_map' is a dictionary mapping old (current) alias values to the new values. """ if not node: node = self for pos, child in enumerate(node.children): if hasattr(child, 'relabel_aliases'): child.relabel_aliases(change_map) elif isinstance(child, tree.Node): self.relabel_aliases(change_map, child) elif isinstance(child, (list, tuple)): if isinstance(child[0], (list, tuple)): elt = list(child[0]) if elt[0] in change_map: elt[0] = change_map[elt[0]] node.children[pos] = (tuple(elt),) + child[1:] else: child[0].relabel_aliases(change_map) # Check if the query value also requires relabelling if hasattr(child[3], 'relabel_aliases'): child[3].relabel_aliases(change_map) class EverythingNode(object): """ A node that matches everything. """ def as_sql(self, qn=None, connection=None): raise FullResultSet def relabel_aliases(self, change_map, node=None): return class NothingNode(object): """ A node that matches nothing. """ def as_sql(self, qn=None, connection=None): raise EmptyResultSet def relabel_aliases(self, change_map, node=None): return class ExtraWhere(object): def __init__(self, sqls, params): self.sqls = sqls self.params = params def as_sql(self, qn=None, connection=None): return " AND ".join(self.sqls), tuple(self.params or ()) class Constraint(object): """ An object that can be passed to WhereNode.add() and knows how to pre-process itself prior to including in the WhereNode. """ def __init__(self, alias, col, field): self.alias, self.col, self.field = alias, col, field def __getstate__(self): """Save the state of the Constraint for pickling. Fields aren't necessarily pickleable, because they can have callable default values. So, instead of pickling the field store a reference so we can restore it manually """ obj_dict = self.__dict__.copy() if self.field: obj_dict['model'] = self.field.model obj_dict['field_name'] = self.field.name del obj_dict['field'] return obj_dict def __setstate__(self, data): """Restore the constraint """ model = data.pop('model', None) field_name = data.pop('field_name', None) self.__dict__.update(data) if model is not None: self.field = model._meta.get_field(field_name) else: self.field = None def prepare(self, lookup_type, value): if self.field: return self.field.get_prep_lookup(lookup_type, value) return value def process(self, lookup_type, value, connection): """ Returns a tuple of data suitable for inclusion in a WhereNode instance. """ # Because of circular imports, we need to import this here. from django.db.models.base import ObjectDoesNotExist try: if self.field: params = self.field.get_db_prep_lookup(lookup_type, value, connection=connection, prepared=True) db_type = self.field.db_type(connection=connection) else: # This branch is used at times when we add a comparison to NULL # (we don't really want to waste time looking up the associated # field object at the calling location). params = Field().get_db_prep_lookup(lookup_type, value, connection=connection, prepared=True) db_type = None except ObjectDoesNotExist: raise EmptyShortCircuit return (self.alias, self.col, db_type), params def relabel_aliases(self, change_map): if self.alias in change_map: self.alias = change_map[self.alias]
[ [ 8, 0, 0.0058, 0.0087, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0116, 0.0029, 0, 0.66, 0.0714, 426, 0, 1, 0, 0, 426, 0, 0 ], [ 1, 0, 0.0145, 0.0029, 0, 0.66...
[ "\"\"\"\nCode to manage the creation and SQL rendering of 'where' constraints.\n\"\"\"", "import datetime", "from itertools import repeat", "from django.utils import tree", "from django.db.models.fields import Field", "from django.db.models.query_utils import QueryWrapper", "from datastructures import E...
from query import * from subqueries import * from where import AND, OR from datastructures import EmptyResultSet __all__ = ['Query', 'AND', 'OR', 'EmptyResultSet']
[ [ 1, 0, 0.1429, 0.1429, 0, 0.66, 0, 546, 0, 1, 0, 0, 546, 0, 0 ], [ 1, 0, 0.2857, 0.1429, 0, 0.66, 0.25, 401, 0, 1, 0, 0, 401, 0, 0 ], [ 1, 0, 0.4286, 0.1429, 0, 0....
[ "from query import *", "from subqueries import *", "from where import AND, OR", "from datastructures import EmptyResultSet", "__all__ = ['Query', 'AND', 'OR', 'EmptyResultSet']" ]
""" Useful auxilliary data structures for query construction. Not useful outside the SQL domain. """ class EmptyResultSet(Exception): pass class FullResultSet(Exception): pass class MultiJoin(Exception): """ Used by join construction code to indicate the point at which a multi-valued join was attempted (if the caller wants to treat that exceptionally). """ def __init__(self, level): self.level = level class Empty(object): pass class RawValue(object): def __init__(self, value): self.value = value class Date(object): """ Add a date selection column. """ def __init__(self, col, lookup_type): self.col = col self.lookup_type = lookup_type def relabel_aliases(self, change_map): c = self.col if isinstance(c, (list, tuple)): self.col = (change_map.get(c[0], c[0]), c[1]) def as_sql(self, qn, connection): if isinstance(self.col, (list, tuple)): col = '%s.%s' % tuple([qn(c) for c in self.col]) else: col = self.col return connection.ops.date_trunc_sql(self.lookup_type, col)
[ [ 8, 0, 0.0543, 0.087, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 3, 0, 0.1413, 0.0435, 0, 0.66, 0.1667, 855, 0, 0, 0, 0, 645, 0, 0 ], [ 3, 0, 0.2065, 0.0435, 0, 0.66,...
[ "\"\"\"\nUseful auxilliary data structures for query construction. Not useful outside\nthe SQL domain.\n\"\"\"", "class EmptyResultSet(Exception):\n pass", "class FullResultSet(Exception):\n pass", "class MultiJoin(Exception):\n \"\"\"\n Used by join construction code to indicate the point at whic...
import datetime import os import django.utils.copycompat as copy from django.conf import settings from django.db.models.fields import Field from django.core.files.base import File, ContentFile from django.core.files.storage import default_storage from django.core.files.images import ImageFile, get_image_dimensions from django.core.files.uploadedfile import UploadedFile from django.utils.functional import curry from django.db.models import signals from django.utils.encoding import force_unicode, smart_str from django.utils.translation import ugettext_lazy, ugettext as _ from django import forms from django.db.models.loading import cache class FieldFile(File): def __init__(self, instance, field, name): super(FieldFile, self).__init__(None, name) self.instance = instance self.field = field self.storage = field.storage self._committed = True def __eq__(self, other): # Older code may be expecting FileField values to be simple strings. # By overriding the == operator, it can remain backwards compatibility. if hasattr(other, 'name'): return self.name == other.name return self.name == other def __ne__(self, other): return not self.__eq__(other) def __hash__(self): # Required because we defined a custom __eq__. return hash(self.name) # The standard File contains most of the necessary properties, but # FieldFiles can be instantiated without a name, so that needs to # be checked for here. def _require_file(self): if not self: raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) def _get_file(self): self._require_file() if not hasattr(self, '_file') or self._file is None: self._file = self.storage.open(self.name, 'rb') return self._file def _set_file(self, file): self._file = file def _del_file(self): del self._file file = property(_get_file, _set_file, _del_file) def _get_path(self): self._require_file() return self.storage.path(self.name) path = property(_get_path) def _get_url(self): self._require_file() return self.storage.url(self.name) url = property(_get_url) def _get_size(self): self._require_file() if not self._committed: return len(self.file) return self.storage.size(self.name) size = property(_get_size) def open(self, mode='rb'): self._require_file() self.file.open(mode) # open() doesn't alter the file's contents, but it does reset the pointer open.alters_data = True # In addition to the standard File API, FieldFiles have extra methods # to further manipulate the underlying file, as well as update the # associated model instance. def save(self, name, content, save=True): name = self.field.generate_filename(self.instance, name) self.name = self.storage.save(name, content) setattr(self.instance, self.field.name, self.name) # Update the filesize cache self._size = len(content) self._committed = True # Save the object because it has changed, unless save is False if save: self.instance.save() save.alters_data = True def delete(self, save=True): # Only close the file if it's already open, which we know by the # presence of self._file if hasattr(self, '_file'): self.close() del self.file self.storage.delete(self.name) self.name = None setattr(self.instance, self.field.name, self.name) # Delete the filesize cache if hasattr(self, '_size'): del self._size self._committed = False if save: self.instance.save() delete.alters_data = True def _get_closed(self): file = getattr(self, '_file', None) return file is None or file.closed closed = property(_get_closed) def close(self): file = getattr(self, '_file', None) if file is not None: file.close() def __getstate__(self): # FieldFile needs access to its associated model field and an instance # it's attached to in order to work properly, but the only necessary # data to be pickled is the file's name itself. Everything else will # be restored later, by FileDescriptor below. return {'name': self.name, 'closed': False, '_committed': True, '_file': None} class FileDescriptor(object): """ The descriptor for the file attribute on the model instance. Returns a FieldFile when accessed so you can do stuff like:: >>> instance.file.size Assigns a file object on assignment so you can do:: >>> instance.file = File(...) """ def __init__(self, field): self.field = field def __get__(self, instance=None, owner=None): if instance is None: raise AttributeError( "The '%s' attribute can only be accessed from %s instances." % (self.field.name, owner.__name__)) # This is slightly complicated, so worth an explanation. # instance.file`needs to ultimately return some instance of `File`, # probably a subclass. Additionally, this returned object needs to have # the FieldFile API so that users can easily do things like # instance.file.path and have that delegated to the file storage engine. # Easy enough if we're strict about assignment in __set__, but if you # peek below you can see that we're not. So depending on the current # value of the field we have to dynamically construct some sort of # "thing" to return. # The instance dict contains whatever was originally assigned # in __set__. file = instance.__dict__[self.field.name] # If this value is a string (instance.file = "path/to/file") or None # then we simply wrap it with the appropriate attribute class according # to the file field. [This is FieldFile for FileFields and # ImageFieldFile for ImageFields; it's also conceivable that user # subclasses might also want to subclass the attribute class]. This # object understands how to convert a path to a file, and also how to # handle None. if isinstance(file, basestring) or file is None: attr = self.field.attr_class(instance, self.field, file) instance.__dict__[self.field.name] = attr # Other types of files may be assigned as well, but they need to have # the FieldFile interface added to the. Thus, we wrap any other type of # File inside a FieldFile (well, the field's attr_class, which is # usually FieldFile). elif isinstance(file, File) and not isinstance(file, FieldFile): file_copy = self.field.attr_class(instance, self.field, file.name) file_copy.file = file file_copy._committed = False instance.__dict__[self.field.name] = file_copy # Finally, because of the (some would say boneheaded) way pickle works, # the underlying FieldFile might not actually itself have an associated # file. So we need to reset the details of the FieldFile in those cases. elif isinstance(file, FieldFile) and not hasattr(file, 'field'): file.instance = instance file.field = self.field file.storage = self.field.storage # That was fun, wasn't it? return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value class FileField(Field): # The class to wrap instance attributes in. Accessing the file object off # the instance will always return an instance of attr_class. attr_class = FieldFile # The descriptor to use for accessing the attribute off of the class. descriptor_class = FileDescriptor description = ugettext_lazy("File path") def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs): for arg in ('primary_key', 'unique'): if arg in kwargs: raise TypeError("'%s' is not a valid argument for %s." % (arg, self.__class__)) self.storage = storage or default_storage self.upload_to = upload_to if callable(upload_to): self.generate_filename = upload_to kwargs['max_length'] = kwargs.get('max_length', 100) super(FileField, self).__init__(verbose_name, name, **kwargs) def get_internal_type(self): return "FileField" def get_prep_lookup(self, lookup_type, value): if hasattr(value, 'name'): value = value.name return super(FileField, self).get_prep_lookup(lookup_type, value) def get_prep_value(self, value): "Returns field's value prepared for saving into a database." # Need to convert File objects provided via a form to unicode for database insertion if value is None: return None return unicode(value) def pre_save(self, model_instance, add): "Returns field's value just before saving." file = super(FileField, self).pre_save(model_instance, add) if file and not file._committed: # Commit the file to storage prior to saving the model file.save(file.name, file, save=False) return file def contribute_to_class(self, cls, name): super(FileField, self).contribute_to_class(cls, name) setattr(cls, self.name, self.descriptor_class(self)) signals.post_delete.connect(self.delete_file, sender=cls) def delete_file(self, instance, sender, **kwargs): file = getattr(instance, self.attname) # If no other object of this type references the file, # and it's not the default value for future objects, # delete it from the backend. if file and file.name != self.default and \ not sender._default_manager.filter(**{self.name: file.name}): file.delete(save=False) elif file: # Otherwise, just close the file, so it doesn't tie up resources. file.close() def get_directory_name(self): return os.path.normpath(force_unicode(datetime.datetime.now().strftime(smart_str(self.upload_to)))) def get_filename(self, filename): return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename))) def generate_filename(self, instance, filename): return os.path.join(self.get_directory_name(), self.get_filename(filename)) def save_form_data(self, instance, data): # Important: None means "no change", other false value means "clear" # This subtle distinction (rather than a more explicit marker) is # needed because we need to consume values that are also sane for a # regular (non Model-) Form to find in its cleaned_data dictionary. if data is not None: # This value will be converted to unicode and stored in the # database, so leaving False as-is is not acceptable. if not data: data = '' setattr(instance, self.name, data) def formfield(self, **kwargs): defaults = {'form_class': forms.FileField, 'max_length': self.max_length} # If a file has been provided previously, then the form doesn't require # that a new file is provided this time. # The code to mark the form field as not required is used by # form_for_instance, but can probably be removed once form_for_instance # is gone. ModelForm uses a different method to check for an existing file. if 'initial' in kwargs: defaults['required'] = False defaults.update(kwargs) return super(FileField, self).formfield(**defaults) class ImageFileDescriptor(FileDescriptor): """ Just like the FileDescriptor, but for ImageFields. The only difference is assigning the width/height to the width_field/height_field, if appropriate. """ def __set__(self, instance, value): previous_file = instance.__dict__.get(self.field.name) super(ImageFileDescriptor, self).__set__(instance, value) # To prevent recalculating image dimensions when we are instantiating # an object from the database (bug #11084), only update dimensions if # the field had a value before this assignment. Since the default # value for FileField subclasses is an instance of field.attr_class, # previous_file will only be None when we are called from # Model.__init__(). The ImageField.update_dimension_fields method # hooked up to the post_init signal handles the Model.__init__() cases. # Assignment happening outside of Model.__init__() will trigger the # update right here. if previous_file is not None: self.field.update_dimension_fields(instance, force=True) class ImageFieldFile(ImageFile, FieldFile): def delete(self, save=True): # Clear the image dimensions cache if hasattr(self, '_dimensions_cache'): del self._dimensions_cache super(ImageFieldFile, self).delete(save) class ImageField(FileField): attr_class = ImageFieldFile descriptor_class = ImageFileDescriptor description = ugettext_lazy("File path") def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs): self.width_field, self.height_field = width_field, height_field FileField.__init__(self, verbose_name, name, **kwargs) def contribute_to_class(self, cls, name): super(ImageField, self).contribute_to_class(cls, name) # Attach update_dimension_fields so that dimension fields declared # after their corresponding image field don't stay cleared by # Model.__init__, see bug #11196. signals.post_init.connect(self.update_dimension_fields, sender=cls) def update_dimension_fields(self, instance, force=False, *args, **kwargs): """ Updates field's width and height fields, if defined. This method is hooked up to model's post_init signal to update dimensions after instantiating a model instance. However, dimensions won't be updated if the dimensions fields are already populated. This avoids unnecessary recalculation when loading an object from the database. Dimensions can be forced to update with force=True, which is how ImageFileDescriptor.__set__ calls this method. """ # Nothing to update if the field doesn't have have dimension fields. has_dimension_fields = self.width_field or self.height_field if not has_dimension_fields: return # getattr will call the ImageFileDescriptor's __get__ method, which # coerces the assigned value into an instance of self.attr_class # (ImageFieldFile in this case). file = getattr(instance, self.attname) # Nothing to update if we have no file and not being forced to update. if not file and not force: return dimension_fields_filled = not( (self.width_field and not getattr(instance, self.width_field)) or (self.height_field and not getattr(instance, self.height_field)) ) # When both dimension fields have values, we are most likely loading # data from the database or updating an image field that already had # an image stored. In the first case, we don't want to update the # dimension fields because we are already getting their values from the # database. In the second case, we do want to update the dimensions # fields and will skip this return because force will be True since we # were called from ImageFileDescriptor.__set__. if dimension_fields_filled and not force: return # file should be an instance of ImageFieldFile or should be None. if file: width = file.width height = file.height else: # No file, so clear dimensions fields. width = None height = None # Update the width and height fields. if self.width_field: setattr(instance, self.width_field, width) if self.height_field: setattr(instance, self.height_field, height) def formfield(self, **kwargs): defaults = {'form_class': forms.ImageField} defaults.update(kwargs) return super(ImageField, self).formfield(**defaults)
[ [ 1, 0, 0.0024, 0.0024, 0, 0.66, 0, 426, 0, 1, 0, 0, 426, 0, 0 ], [ 1, 0, 0.0049, 0.0024, 0, 0.66, 0.05, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0097, 0.0024, 0, 0....
[ "import datetime", "import os", "import django.utils.copycompat as copy", "from django.conf import settings", "from django.db.models.fields import Field", "from django.core.files.base import File, ContentFile", "from django.core.files.storage import default_storage", "from django.core.files.images imp...
""" Field-like classes that aren't really fields. It's easier to use objects that have the same attributes as fields sometimes (avoids a lot of special casing). """ from django.db.models import fields class OrderWrt(fields.IntegerField): """ A proxy for the _order database field that is used when Meta.order_with_respect_to is specified. """ def __init__(self, *args, **kwargs): kwargs['name'] = '_order' kwargs['editable'] = False super(OrderWrt, self).__init__(*args, **kwargs)
[ [ 8, 0, 0.1471, 0.2353, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.3529, 0.0588, 0, 0.66, 0.5, 680, 0, 1, 0, 0, 680, 0, 0 ], [ 3, 0, 0.7353, 0.5882, 0, 0.66, ...
[ "\"\"\"\nField-like classes that aren't really fields. It's easier to use objects that\nhave the same attributes as fields sometimes (avoids a lot of special casing).\n\"\"\"", "from django.db.models import fields", "class OrderWrt(fields.IntegerField):\n \"\"\"\n A proxy for the _order database field tha...
from django.conf import settings from django.db import connection, router, transaction, connections from django.db.backends import util from django.db.models import signals, get_model from django.db.models.fields import (AutoField, Field, IntegerField, PositiveIntegerField, PositiveSmallIntegerField, FieldDoesNotExist) from django.db.models.related import RelatedObject from django.db.models.query import QuerySet from django.db.models.query_utils import QueryWrapper from django.db.models.deletion import CASCADE from django.utils.encoding import smart_unicode from django.utils.translation import (ugettext_lazy as _, string_concat, ungettext, ugettext) from django.utils.functional import curry from django.core import exceptions from django import forms RECURSIVE_RELATIONSHIP_CONSTANT = 'self' pending_lookups = {} def add_lazy_relation(cls, field, relation, operation): """ Adds a lookup on ``cls`` when a related field is defined using a string, i.e.:: class MyModel(Model): fk = ForeignKey("AnotherModel") This string can be: * RECURSIVE_RELATIONSHIP_CONSTANT (i.e. "self") to indicate a recursive relation. * The name of a model (i.e "AnotherModel") to indicate another model in the same app. * An app-label and model name (i.e. "someapp.AnotherModel") to indicate another model in a different app. If the other model hasn't yet been loaded -- almost a given if you're using lazy relationships -- then the relation won't be set up until the class_prepared signal fires at the end of model initialization. operation is the work that must be performed once the relation can be resolved. """ # Check for recursive relations if relation == RECURSIVE_RELATIONSHIP_CONSTANT: app_label = cls._meta.app_label model_name = cls.__name__ else: # Look for an "app.Model" relation try: app_label, model_name = relation.split(".") except ValueError: # If we can't split, assume a model in current app app_label = cls._meta.app_label model_name = relation except AttributeError: # If it doesn't have a split it's actually a model class app_label = relation._meta.app_label model_name = relation._meta.object_name # Try to look up the related model, and if it's already loaded resolve the # string right away. If get_model returns None, it means that the related # model isn't loaded yet, so we need to pend the relation until the class # is prepared. model = get_model(app_label, model_name, False) if model: operation(field, model, cls) else: key = (app_label, model_name) value = (cls, field, operation) pending_lookups.setdefault(key, []).append(value) def do_pending_lookups(sender, **kwargs): """ Handle any pending relations to the sending model. Sent from class_prepared. """ key = (sender._meta.app_label, sender.__name__) for cls, field, operation in pending_lookups.pop(key, []): operation(field, sender, cls) signals.class_prepared.connect(do_pending_lookups) #HACK class RelatedField(object): def contribute_to_class(self, cls, name): sup = super(RelatedField, self) # Store the opts for related_query_name() self.opts = cls._meta if hasattr(sup, 'contribute_to_class'): sup.contribute_to_class(cls, name) if not cls._meta.abstract and self.rel.related_name: self.rel.related_name = self.rel.related_name % { 'class': cls.__name__.lower(), 'app_label': cls._meta.app_label.lower(), } other = self.rel.to if isinstance(other, basestring) or other._meta.pk is None: def resolve_related_class(field, model, cls): field.rel.to = model field.do_related_class(model, cls) add_lazy_relation(cls, self, other, resolve_related_class) else: self.do_related_class(other, cls) def set_attributes_from_rel(self): self.name = self.name or (self.rel.to._meta.object_name.lower() + '_' + self.rel.to._meta.pk.name) if self.verbose_name is None: self.verbose_name = self.rel.to._meta.verbose_name self.rel.field_name = self.rel.field_name or self.rel.to._meta.pk.name def do_related_class(self, other, cls): self.set_attributes_from_rel() self.related = RelatedObject(other, cls, self) if not cls._meta.abstract: self.contribute_to_related_class(other, self.related) def get_prep_lookup(self, lookup_type, value): if hasattr(value, 'prepare'): return value.prepare() if hasattr(value, '_prepare'): return value._prepare() # FIXME: lt and gt are explicitly allowed to make # get_(next/prev)_by_date work; other lookups are not allowed since that # gets messy pretty quick. This is a good candidate for some refactoring # in the future. if lookup_type in ['exact', 'gt', 'lt', 'gte', 'lte']: return self._pk_trace(value, 'get_prep_lookup', lookup_type) if lookup_type in ('range', 'in'): return [self._pk_trace(v, 'get_prep_lookup', lookup_type) for v in value] elif lookup_type == 'isnull': return [] raise TypeError("Related Field has invalid lookup: %s" % lookup_type) def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): if not prepared: value = self.get_prep_lookup(lookup_type, value) if hasattr(value, 'get_compiler'): value = value.get_compiler(connection=connection) if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'): # If the value has a relabel_aliases method, it will need to # be invoked before the final SQL is evaluated if hasattr(value, 'relabel_aliases'): return value if hasattr(value, 'as_sql'): sql, params = value.as_sql() else: sql, params = value._as_sql(connection=connection) return QueryWrapper(('(%s)' % sql), params) # FIXME: lt and gt are explicitly allowed to make # get_(next/prev)_by_date work; other lookups are not allowed since that # gets messy pretty quick. This is a good candidate for some refactoring # in the future. if lookup_type in ['exact', 'gt', 'lt', 'gte', 'lte']: return [self._pk_trace(value, 'get_db_prep_lookup', lookup_type, connection=connection, prepared=prepared)] if lookup_type in ('range', 'in'): return [self._pk_trace(v, 'get_db_prep_lookup', lookup_type, connection=connection, prepared=prepared) for v in value] elif lookup_type == 'isnull': return [] raise TypeError("Related Field has invalid lookup: %s" % lookup_type) def _pk_trace(self, value, prep_func, lookup_type, **kwargs): # Value may be a primary key, or an object held in a relation. # If it is an object, then we need to get the primary key value for # that object. In certain conditions (especially one-to-one relations), # the primary key may itself be an object - so we need to keep drilling # down until we hit a value that can be used for a comparison. v = value try: while True: v = getattr(v, v._meta.pk.name) except AttributeError: pass except exceptions.ObjectDoesNotExist: v = None field = self while field.rel: if hasattr(field.rel, 'field_name'): field = field.rel.to._meta.get_field(field.rel.field_name) else: field = field.rel.to._meta.pk if lookup_type in ('range', 'in'): v = [v] v = getattr(field, prep_func)(lookup_type, v, **kwargs) if isinstance(v, list): v = v[0] return v def related_query_name(self): # This method defines the name that can be used to identify this # related object in a table-spanning query. It uses the lower-cased # object_name by default, but this can be overridden with the # "related_name" option. return self.rel.related_name or self.opts.object_name.lower() class SingleRelatedObjectDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # a single "remote" value, on the class pointed to by a related field. # In the example "place.restaurant", the restaurant attribute is a # SingleRelatedObjectDescriptor instance. def __init__(self, related): self.related = related self.cache_name = related.get_cache_name() def __get__(self, instance, instance_type=None): if instance is None: return self try: return getattr(instance, self.cache_name) except AttributeError: params = {'%s__pk' % self.related.field.name: instance._get_pk_val()} db = router.db_for_read(self.related.model, instance=instance) rel_obj = self.related.model._base_manager.using(db).get(**params) setattr(instance, self.cache_name, rel_obj) return rel_obj def __set__(self, instance, value): if instance is None: raise AttributeError("%s must be accessed via instance" % self.related.opts.object_name) # The similarity of the code below to the code in # ReverseSingleRelatedObjectDescriptor is annoying, but there's a bunch # of small differences that would make a common base class convoluted. # If null=True, we can assign null here, but otherwise the value needs # to be an instance of the related class. if value is None and self.related.field.null == False: raise ValueError('Cannot assign None: "%s.%s" does not allow null values.' % (instance._meta.object_name, self.related.get_accessor_name())) elif value is not None and not isinstance(value, self.related.model): raise ValueError('Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (value, instance._meta.object_name, self.related.get_accessor_name(), self.related.opts.object_name)) elif value is not None: if instance._state.db is None: instance._state.db = router.db_for_write(instance.__class__, instance=value) elif value._state.db is None: value._state.db = router.db_for_write(value.__class__, instance=instance) elif value._state.db is not None and instance._state.db is not None: if not router.allow_relation(value, instance): raise ValueError('Cannot assign "%r": instance is on database "%s", value is on database "%s"' % (value, instance._state.db, value._state.db)) # Set the value of the related field to the value of the related object's related field setattr(value, self.related.field.attname, getattr(instance, self.related.field.rel.get_related_field().attname)) # Since we already know what the related object is, seed the related # object caches now, too. This avoids another db hit if you get the # object you just set. setattr(instance, self.cache_name, value) setattr(value, self.related.field.get_cache_name(), instance) class ReverseSingleRelatedObjectDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # a single "remote" value, on the class that defines the related field. # In the example "choice.poll", the poll attribute is a # ReverseSingleRelatedObjectDescriptor instance. def __init__(self, field_with_rel): self.field = field_with_rel def __get__(self, instance, instance_type=None): if instance is None: return self cache_name = self.field.get_cache_name() try: return getattr(instance, cache_name) except AttributeError: val = getattr(instance, self.field.attname) if val is None: # If NULL is an allowed value, return it. if self.field.null: return None raise self.field.rel.to.DoesNotExist other_field = self.field.rel.get_related_field() if other_field.rel: params = {'%s__pk' % self.field.rel.field_name: val} else: params = {'%s__exact' % self.field.rel.field_name: val} # If the related manager indicates that it should be used for # related fields, respect that. rel_mgr = self.field.rel.to._default_manager db = router.db_for_read(self.field.rel.to, instance=instance) if getattr(rel_mgr, 'use_for_related_fields', False): rel_obj = rel_mgr.using(db).get(**params) else: rel_obj = QuerySet(self.field.rel.to).using(db).get(**params) setattr(instance, cache_name, rel_obj) return rel_obj def __set__(self, instance, value): if instance is None: raise AttributeError("%s must be accessed via instance" % self._field.name) # If null=True, we can assign null here, but otherwise the value needs # to be an instance of the related class. if value is None and self.field.null == False: raise ValueError('Cannot assign None: "%s.%s" does not allow null values.' % (instance._meta.object_name, self.field.name)) elif value is not None and not isinstance(value, self.field.rel.to): raise ValueError('Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (value, instance._meta.object_name, self.field.name, self.field.rel.to._meta.object_name)) elif value is not None: if instance._state.db is None: instance._state.db = router.db_for_write(instance.__class__, instance=value) elif value._state.db is None: value._state.db = router.db_for_write(value.__class__, instance=instance) elif value._state.db is not None and instance._state.db is not None: if not router.allow_relation(value, instance): raise ValueError('Cannot assign "%r": instance is on database "%s", value is on database "%s"' % (value, instance._state.db, value._state.db)) # If we're setting the value of a OneToOneField to None, we need to clear # out the cache on any old related object. Otherwise, deleting the # previously-related object will also cause this object to be deleted, # which is wrong. if value is None: # Look up the previously-related object, which may still be available # since we've not yet cleared out the related field. # Use the cache directly, instead of the accessor; if we haven't # populated the cache, then we don't care - we're only accessing # the object to invalidate the accessor cache, so there's no # need to populate the cache just to expire it again. related = getattr(instance, self.field.get_cache_name(), None) # If we've got an old related object, we need to clear out its # cache. This cache also might not exist if the related object # hasn't been accessed yet. if related: cache_name = self.field.related.get_cache_name() try: delattr(related, cache_name) except AttributeError: pass # Set the value of the related field try: val = getattr(value, self.field.rel.get_related_field().attname) except AttributeError: val = None setattr(instance, self.field.attname, val) # Since we already know what the related object is, seed the related # object cache now, too. This avoids another db hit if you get the # object you just set. setattr(instance, self.field.get_cache_name(), value) class ForeignRelatedObjectsDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # multiple "remote" values and have a ForeignKey pointed at them by # some other model. In the example "poll.choice_set", the choice_set # attribute is a ForeignRelatedObjectsDescriptor instance. def __init__(self, related): self.related = related # RelatedObject instance def __get__(self, instance, instance_type=None): if instance is None: return self return self.create_manager(instance, self.related.model._default_manager.__class__) def __set__(self, instance, value): if instance is None: raise AttributeError("Manager must be accessed via instance") manager = self.__get__(instance) # If the foreign key can support nulls, then completely clear the related set. # Otherwise, just move the named objects into the set. if self.related.field.null: manager.clear() manager.add(*value) def delete_manager(self, instance): """ Returns a queryset based on the related model's base manager (rather than the default manager, as returned by __get__). Used by Model.delete(). """ return self.create_manager(instance, self.related.model._base_manager.__class__) def create_manager(self, instance, superclass): """ Creates the managers used by other methods (__get__() and delete()). """ rel_field = self.related.field rel_model = self.related.model class RelatedManager(superclass): def get_query_set(self): db = self._db or router.db_for_read(rel_model, instance=instance) return superclass.get_query_set(self).using(db).filter(**(self.core_filters)) def add(self, *objs): for obj in objs: if not isinstance(obj, self.model): raise TypeError("'%s' instance expected" % self.model._meta.object_name) setattr(obj, rel_field.name, instance) obj.save() add.alters_data = True def create(self, **kwargs): kwargs.update({rel_field.name: instance}) db = router.db_for_write(rel_model, instance=instance) return super(RelatedManager, self.db_manager(db)).create(**kwargs) create.alters_data = True def get_or_create(self, **kwargs): # Update kwargs with the related object that this # ForeignRelatedObjectsDescriptor knows about. kwargs.update({rel_field.name: instance}) db = router.db_for_write(rel_model, instance=instance) return super(RelatedManager, self.db_manager(db)).get_or_create(**kwargs) get_or_create.alters_data = True # remove() and clear() are only provided if the ForeignKey can have a value of null. if rel_field.null: def remove(self, *objs): val = getattr(instance, rel_field.rel.get_related_field().attname) for obj in objs: # Is obj actually part of this descriptor set? if getattr(obj, rel_field.attname) == val: setattr(obj, rel_field.name, None) obj.save() else: raise rel_field.rel.to.DoesNotExist("%r is not related to %r." % (obj, instance)) remove.alters_data = True def clear(self): for obj in self.all(): setattr(obj, rel_field.name, None) obj.save() clear.alters_data = True manager = RelatedManager() attname = rel_field.rel.get_related_field().name manager.core_filters = {'%s__%s' % (rel_field.name, attname): getattr(instance, attname)} manager.model = self.related.model return manager def create_many_related_manager(superclass, rel=False): """Creates a manager that subclasses 'superclass' (which is a Manager) and adds behavior for many-to-many related objects.""" through = rel.through class ManyRelatedManager(superclass): def __init__(self, model=None, core_filters=None, instance=None, symmetrical=None, join_table=None, source_field_name=None, target_field_name=None, reverse=False): super(ManyRelatedManager, self).__init__() self.core_filters = core_filters self.model = model self.symmetrical = symmetrical self.instance = instance self.source_field_name = source_field_name self.target_field_name = target_field_name self.through = through self._pk_val = self.instance.pk self.reverse = reverse if self._pk_val is None: raise ValueError("%r instance needs to have a primary key value before a many-to-many relationship can be used." % instance.__class__.__name__) def get_query_set(self): db = self._db or router.db_for_read(self.instance.__class__, instance=self.instance) return superclass.get_query_set(self).using(db)._next_is_sticky().filter(**(self.core_filters)) # If the ManyToMany relation has an intermediary model, # the add and remove methods do not exist. if rel.through._meta.auto_created: def add(self, *objs): self._add_items(self.source_field_name, self.target_field_name, *objs) # If this is a symmetrical m2m relation to self, add the mirror entry in the m2m table if self.symmetrical: self._add_items(self.target_field_name, self.source_field_name, *objs) add.alters_data = True def remove(self, *objs): self._remove_items(self.source_field_name, self.target_field_name, *objs) # If this is a symmetrical m2m relation to self, remove the mirror entry in the m2m table if self.symmetrical: self._remove_items(self.target_field_name, self.source_field_name, *objs) remove.alters_data = True def clear(self): self._clear_items(self.source_field_name) # If this is a symmetrical m2m relation to self, clear the mirror entry in the m2m table if self.symmetrical: self._clear_items(self.target_field_name) clear.alters_data = True def create(self, **kwargs): # This check needs to be done here, since we can't later remove this # from the method lookup table, as we do with add and remove. if not rel.through._meta.auto_created: opts = through._meta raise AttributeError("Cannot use create() on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)) db = router.db_for_write(self.instance.__class__, instance=self.instance) new_obj = super(ManyRelatedManager, self.db_manager(db)).create(**kwargs) self.add(new_obj) return new_obj create.alters_data = True def get_or_create(self, **kwargs): db = router.db_for_write(self.instance.__class__, instance=self.instance) obj, created = \ super(ManyRelatedManager, self.db_manager(db)).get_or_create(**kwargs) # We only need to add() if created because if we got an object back # from get() then the relationship already exists. if created: self.add(obj) return obj, created get_or_create.alters_data = True def _add_items(self, source_field_name, target_field_name, *objs): # join_table: name of the m2m link table # source_field_name: the PK fieldname in join_table for the source object # target_field_name: the PK fieldname in join_table for the target object # *objs - objects to add. Either object instances, or primary keys of object instances. # If there aren't any objects, there is nothing to do. from django.db.models import Model if objs: new_ids = set() for obj in objs: if isinstance(obj, self.model): if not router.allow_relation(obj, self.instance): raise ValueError('Cannot add "%r": instance is on database "%s", value is on database "%s"' % (obj, self.instance._state.db, obj._state.db)) new_ids.add(obj.pk) elif isinstance(obj, Model): raise TypeError("'%s' instance expected" % self.model._meta.object_name) else: new_ids.add(obj) db = router.db_for_write(self.through.__class__, instance=self.instance) vals = self.through._default_manager.using(db).values_list(target_field_name, flat=True) vals = vals.filter(**{ source_field_name: self._pk_val, '%s__in' % target_field_name: new_ids, }) new_ids = new_ids - set(vals) if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are inserting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action='pre_add', instance=self.instance, reverse=self.reverse, model=self.model, pk_set=new_ids, using=db) # Add the ones that aren't there already for obj_id in new_ids: self.through._default_manager.using(db).create(**{ '%s_id' % source_field_name: self._pk_val, '%s_id' % target_field_name: obj_id, }) if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are inserting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action='post_add', instance=self.instance, reverse=self.reverse, model=self.model, pk_set=new_ids, using=db) def _remove_items(self, source_field_name, target_field_name, *objs): # source_col_name: the PK colname in join_table for the source object # target_col_name: the PK colname in join_table for the target object # *objs - objects to remove # If there aren't any objects, there is nothing to do. if objs: # Check that all the objects are of the right type old_ids = set() for obj in objs: if isinstance(obj, self.model): old_ids.add(obj.pk) else: old_ids.add(obj) # Work out what DB we're operating on db = router.db_for_write(self.through.__class__, instance=self.instance) # Send a signal to the other end if need be. if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are deleting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action="pre_remove", instance=self.instance, reverse=self.reverse, model=self.model, pk_set=old_ids, using=db) # Remove the specified objects from the join table self.through._default_manager.using(db).filter(**{ source_field_name: self._pk_val, '%s__in' % target_field_name: old_ids }).delete() if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are deleting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action="post_remove", instance=self.instance, reverse=self.reverse, model=self.model, pk_set=old_ids, using=db) def _clear_items(self, source_field_name): db = router.db_for_write(self.through.__class__, instance=self.instance) # source_col_name: the PK colname in join_table for the source object if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are clearing the # duplicate data rows for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action="pre_clear", instance=self.instance, reverse=self.reverse, model=self.model, pk_set=None, using=db) self.through._default_manager.using(db).filter(**{ source_field_name: self._pk_val }).delete() if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are clearing the # duplicate data rows for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action="post_clear", instance=self.instance, reverse=self.reverse, model=self.model, pk_set=None, using=db) return ManyRelatedManager class ManyRelatedObjectsDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # multiple "remote" values and have a ManyToManyField pointed at them by # some other model (rather than having a ManyToManyField themselves). # In the example "publication.article_set", the article_set attribute is a # ManyRelatedObjectsDescriptor instance. def __init__(self, related): self.related = related # RelatedObject instance def __get__(self, instance, instance_type=None): if instance is None: return self # Dynamically create a class that subclasses the related # model's default manager. rel_model = self.related.model superclass = rel_model._default_manager.__class__ RelatedManager = create_many_related_manager(superclass, self.related.field.rel) manager = RelatedManager( model=rel_model, core_filters={'%s__pk' % self.related.field.name: instance._get_pk_val()}, instance=instance, symmetrical=False, source_field_name=self.related.field.m2m_reverse_field_name(), target_field_name=self.related.field.m2m_field_name(), reverse=True ) return manager def __set__(self, instance, value): if instance is None: raise AttributeError("Manager must be accessed via instance") if not self.related.field.rel.through._meta.auto_created: opts = self.related.field.rel.through._meta raise AttributeError("Cannot set values on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)) manager = self.__get__(instance) manager.clear() manager.add(*value) class ReverseManyRelatedObjectsDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # multiple "remote" values and have a ManyToManyField defined in their # model (rather than having another model pointed *at* them). # In the example "article.publications", the publications attribute is a # ReverseManyRelatedObjectsDescriptor instance. def __init__(self, m2m_field): self.field = m2m_field def _through(self): # through is provided so that you have easy access to the through # model (Book.authors.through) for inlines, etc. This is done as # a property to ensure that the fully resolved value is returned. return self.field.rel.through through = property(_through) def __get__(self, instance, instance_type=None): if instance is None: return self # Dynamically create a class that subclasses the related # model's default manager. rel_model=self.field.rel.to superclass = rel_model._default_manager.__class__ RelatedManager = create_many_related_manager(superclass, self.field.rel) manager = RelatedManager( model=rel_model, core_filters={'%s__pk' % self.field.related_query_name(): instance._get_pk_val()}, instance=instance, symmetrical=self.field.rel.symmetrical, source_field_name=self.field.m2m_field_name(), target_field_name=self.field.m2m_reverse_field_name(), reverse=False ) return manager def __set__(self, instance, value): if instance is None: raise AttributeError("Manager must be accessed via instance") if not self.field.rel.through._meta.auto_created: opts = self.field.rel.through._meta raise AttributeError("Cannot set values on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)) manager = self.__get__(instance) manager.clear() manager.add(*value) class ManyToOneRel(object): def __init__(self, to, field_name, related_name=None, limit_choices_to=None, parent_link=False, on_delete=None): try: to._meta except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "'to' must be either a model, a model name or the string %r" % RECURSIVE_RELATIONSHIP_CONSTANT self.to, self.field_name = to, field_name self.related_name = related_name if limit_choices_to is None: limit_choices_to = {} self.limit_choices_to = limit_choices_to self.multiple = True self.parent_link = parent_link self.on_delete = on_delete def is_hidden(self): "Should the related object be hidden?" return self.related_name and self.related_name[-1] == '+' def get_related_field(self): """ Returns the Field in the 'to' object to which this relationship is tied. """ data = self.to._meta.get_field_by_name(self.field_name) if not data[2]: raise FieldDoesNotExist("No related field named '%s'" % self.field_name) return data[0] class OneToOneRel(ManyToOneRel): def __init__(self, to, field_name, related_name=None, limit_choices_to=None, parent_link=False, on_delete=None): super(OneToOneRel, self).__init__(to, field_name, related_name=related_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete ) self.multiple = False class ManyToManyRel(object): def __init__(self, to, related_name=None, limit_choices_to=None, symmetrical=True, through=None): self.to = to self.related_name = related_name if limit_choices_to is None: limit_choices_to = {} self.limit_choices_to = limit_choices_to self.symmetrical = symmetrical self.multiple = True self.through = through def is_hidden(self): "Should the related object be hidden?" return self.related_name and self.related_name[-1] == '+' def get_related_field(self): """ Returns the field in the to' object to which this relationship is tied (this is always the primary key on the target model). Provided for symmetry with ManyToOneRel. """ return self.to._meta.pk class ForeignKey(RelatedField, Field): empty_strings_allowed = False default_error_messages = { 'invalid': _('Model %(model)s with pk %(pk)r does not exist.') } description = _("Foreign Key (type determined by related field)") def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs): try: to_name = to._meta.object_name.lower() except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) else: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) # For backwards compatibility purposes, we need to *try* and set # the to_field during FK construction. It won't be guaranteed to # be correct until contribute_to_class is called. Refs #12190. to_field = to_field or (to._meta.pk and to._meta.pk.name) kwargs['verbose_name'] = kwargs.get('verbose_name', None) if 'db_index' not in kwargs: kwargs['db_index'] = True kwargs['rel'] = rel_class(to, to_field, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), parent_link=kwargs.pop('parent_link', False), on_delete=kwargs.pop('on_delete', CASCADE), ) Field.__init__(self, **kwargs) def validate(self, value, model_instance): if self.rel.parent_link: return super(ForeignKey, self).validate(value, model_instance) if value is None: return qs = self.rel.to._default_manager.filter(**{self.rel.field_name:value}) qs = qs.complex_filter(self.rel.limit_choices_to) if not qs.exists(): raise exceptions.ValidationError(self.error_messages['invalid'] % { 'model': self.rel.to._meta.verbose_name, 'pk': value}) def get_attname(self): return '%s_id' % self.name def get_validator_unique_lookup_type(self): return '%s__%s__exact' % (self.name, self.rel.get_related_field().name) def get_default(self): "Here we check if the default value is an object and return the to_field if so." field_default = super(ForeignKey, self).get_default() if isinstance(field_default, self.rel.to): return getattr(field_default, self.rel.get_related_field().attname) return field_default def get_db_prep_save(self, value, connection): if value == '' or value == None: return None else: return self.rel.get_related_field().get_db_prep_save(value, connection=connections[router.db_for_read(self.rel.to)]) def value_to_string(self, obj): if not obj: # In required many-to-one fields with only one available choice, # select that one available choice. Note: For SelectFields # we have to check that the length of choices is *2*, not 1, # because SelectFields always have an initial "blank" value. if not self.blank and self.choices: choice_list = self.get_choices_default() if len(choice_list) == 2: return smart_unicode(choice_list[1][0]) return Field.value_to_string(self, obj) def contribute_to_class(self, cls, name): super(ForeignKey, self).contribute_to_class(cls, name) setattr(cls, self.name, ReverseSingleRelatedObjectDescriptor(self)) if isinstance(self.rel.to, basestring): target = self.rel.to else: target = self.rel.to._meta.db_table cls._meta.duplicate_targets[self.column] = (target, "o2m") def contribute_to_related_class(self, cls, related): # Internal FK's - i.e., those with a related name ending with '+' - # don't get a related descriptor. if not self.rel.is_hidden(): setattr(cls, related.get_accessor_name(), ForeignRelatedObjectsDescriptor(related)) if self.rel.field_name is None: self.rel.field_name = cls._meta.pk.name def formfield(self, **kwargs): db = kwargs.pop('using', None) defaults = { 'form_class': forms.ModelChoiceField, 'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to), 'to_field_name': self.rel.field_name, } defaults.update(kwargs) return super(ForeignKey, self).formfield(**defaults) def db_type(self, connection): # The database column type of a ForeignKey is the column type # of the field to which it points. An exception is if the ForeignKey # points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField, # in which case the column type is simply that of an IntegerField. # If the database needs similar types for key fields however, the only # thing we can do is making AutoField an IntegerField. rel_field = self.rel.get_related_field() return rel_field.related_db_type(connection=connections[router.db_for_read(rel_field.model)]) class OneToOneField(ForeignKey): """ A OneToOneField is essentially the same as a ForeignKey, with the exception that always carries a "unique" constraint with it and the reverse relation always returns the object pointed to (since there will only ever be one), rather than returning a list. """ description = _("One-to-one relationship") def __init__(self, to, to_field=None, **kwargs): kwargs['unique'] = True super(OneToOneField, self).__init__(to, to_field, OneToOneRel, **kwargs) def contribute_to_related_class(self, cls, related): setattr(cls, related.get_accessor_name(), SingleRelatedObjectDescriptor(related)) def formfield(self, **kwargs): if self.rel.parent_link: return None return super(OneToOneField, self).formfield(**kwargs) def save_form_data(self, instance, data): if isinstance(data, self.rel.to): setattr(instance, self.name, data) else: setattr(instance, self.attname, data) def create_many_to_many_intermediary_model(field, klass): from django.db import models managed = True if isinstance(field.rel.to, basestring) and field.rel.to != RECURSIVE_RELATIONSHIP_CONSTANT: to_model = field.rel.to to = to_model.split('.')[-1] def set_managed(field, model, cls): field.rel.through._meta.managed = model._meta.managed or cls._meta.managed add_lazy_relation(klass, field, to_model, set_managed) elif isinstance(field.rel.to, basestring): to = klass._meta.object_name to_model = klass managed = klass._meta.managed else: to = field.rel.to._meta.object_name to_model = field.rel.to managed = klass._meta.managed or to_model._meta.managed name = '%s_%s' % (klass._meta.object_name, field.name) if field.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to == klass._meta.object_name: from_ = 'from_%s' % to.lower() to = 'to_%s' % to.lower() else: from_ = klass._meta.object_name.lower() to = to.lower() meta = type('Meta', (object,), { 'db_table': field._get_m2m_db_table(klass._meta), 'managed': managed, 'auto_created': klass, 'app_label': klass._meta.app_label, 'unique_together': (from_, to), 'verbose_name': '%(from)s-%(to)s relationship' % {'from': from_, 'to': to}, 'verbose_name_plural': '%(from)s-%(to)s relationships' % {'from': from_, 'to': to}, }) # Construct and return the new class. return type(name, (models.Model,), { 'Meta': meta, '__module__': klass.__module__, from_: models.ForeignKey(klass, related_name='%s+' % name), to: models.ForeignKey(to_model, related_name='%s+' % name) }) class ManyToManyField(RelatedField, Field): description = _("Many-to-many relationship") def __init__(self, to, **kwargs): try: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ManyToManyRel(to, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), symmetrical=kwargs.pop('symmetrical', to==RECURSIVE_RELATIONSHIP_CONSTANT), through=kwargs.pop('through', None)) self.db_table = kwargs.pop('db_table', None) if kwargs['rel'].through is not None: assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used." Field.__init__(self, **kwargs) msg = _('Hold down "Control", or "Command" on a Mac, to select more than one.') self.help_text = string_concat(self.help_text, ' ', msg) def get_choices_default(self): return Field.get_choices(self, include_blank=False) def _get_m2m_db_table(self, opts): "Function that can be curried to provide the m2m table name for this relation" if self.rel.through is not None: return self.rel.through._meta.db_table elif self.db_table: return self.db_table else: return util.truncate_name('%s_%s' % (opts.db_table, self.name), connection.ops.max_name_length()) def _get_m2m_attr(self, related, attr): "Function that can be curried to provide the source accessor or DB column name for the m2m table" cache_attr = '_m2m_%s_cache' % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) for f in self.rel.through._meta.fields: if hasattr(f,'rel') and f.rel and f.rel.to == related.model: setattr(self, cache_attr, getattr(f, attr)) return getattr(self, cache_attr) def _get_m2m_reverse_attr(self, related, attr): "Function that can be curried to provide the related accessor or DB column name for the m2m table" cache_attr = '_m2m_reverse_%s_cache' % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) found = False for f in self.rel.through._meta.fields: if hasattr(f,'rel') and f.rel and f.rel.to == related.parent_model: if related.model == related.parent_model: # If this is an m2m-intermediate to self, # the first foreign key you find will be # the source column. Keep searching for # the second foreign key. if found: setattr(self, cache_attr, getattr(f, attr)) break else: found = True else: setattr(self, cache_attr, getattr(f, attr)) break return getattr(self, cache_attr) def isValidIDList(self, field_data, all_data): "Validates that the value is a valid list of foreign keys" mod = self.rel.to try: pks = map(int, field_data.split(',')) except ValueError: # the CommaSeparatedIntegerField validator will catch this error return objects = mod._default_manager.in_bulk(pks) if len(objects) != len(pks): badkeys = [k for k in pks if k not in objects] raise exceptions.ValidationError( ungettext("Please enter valid %(self)s IDs. The value %(value)r is invalid.", "Please enter valid %(self)s IDs. The values %(value)r are invalid.", len(badkeys)) % { 'self': self.verbose_name, 'value': len(badkeys) == 1 and badkeys[0] or tuple(badkeys), }) def value_to_string(self, obj): data = '' if obj: qs = getattr(obj, self.name).all() data = [instance._get_pk_val() for instance in qs] else: # In required many-to-many fields with only one available choice, # select that one available choice. if not self.blank: choices_list = self.get_choices_default() if len(choices_list) == 1: data = [choices_list[0][0]] return smart_unicode(data) def contribute_to_class(self, cls, name): # To support multiple relations to self, it's useful to have a non-None # related name on symmetrical relations for internal reasons. The # concept doesn't make a lot of sense externally ("you want me to # specify *what* on my non-reversible relation?!"), so we set it up # automatically. The funky name reduces the chance of an accidental # clash. if self.rel.symmetrical and (self.rel.to == "self" or self.rel.to == cls._meta.object_name): self.rel.related_name = "%s_rel_+" % name super(ManyToManyField, self).contribute_to_class(cls, name) # The intermediate m2m model is not auto created if: # 1) There is a manually specified intermediate, or # 2) The class owning the m2m field is abstract. if not self.rel.through and not cls._meta.abstract: self.rel.through = create_many_to_many_intermediary_model(self, cls) # Add the descriptor for the m2m relation setattr(cls, self.name, ReverseManyRelatedObjectsDescriptor(self)) # Set up the accessor for the m2m table name for the relation self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta) # Populate some necessary rel arguments so that cross-app relations # work correctly. if isinstance(self.rel.through, basestring): def resolve_through_model(field, model, cls): field.rel.through = model add_lazy_relation(cls, self, self.rel.through, resolve_through_model) if isinstance(self.rel.to, basestring): target = self.rel.to else: target = self.rel.to._meta.db_table cls._meta.duplicate_targets[self.column] = (target, "m2m") def contribute_to_related_class(self, cls, related): # Internal M2Ms (i.e., those with a related name ending with '+') # don't get a related descriptor. if not self.rel.is_hidden(): setattr(cls, related.get_accessor_name(), ManyRelatedObjectsDescriptor(related)) # Set up the accessors for the column names on the m2m table self.m2m_column_name = curry(self._get_m2m_attr, related, 'column') self.m2m_reverse_name = curry(self._get_m2m_reverse_attr, related, 'column') self.m2m_field_name = curry(self._get_m2m_attr, related, 'name') self.m2m_reverse_field_name = curry(self._get_m2m_reverse_attr, related, 'name') def set_attributes_from_rel(self): pass def value_from_object(self, obj): "Returns the value of this field in the given model instance." return getattr(obj, self.attname).all() def save_form_data(self, instance, data): setattr(instance, self.attname, data) def formfield(self, **kwargs): db = kwargs.pop('using', None) defaults = { 'form_class': forms.ModelMultipleChoiceField, 'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to) } defaults.update(kwargs) # If initial is passed in, it's a list of related objects, but the # MultipleChoiceField takes a list of IDs. if defaults.get('initial') is not None: initial = defaults['initial'] if callable(initial): initial = initial() defaults['initial'] = [i._get_pk_val() for i in initial] return super(ManyToManyField, self).formfield(**defaults) def db_type(self, connection): # A ManyToManyField is not represented by a single column, # so return None. return None
[ [ 1, 0, 0.0009, 0.0009, 0, 0.66, 0, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0017, 0.0009, 0, 0.66, 0.0312, 40, 0, 4, 0, 0, 40, 0, 0 ], [ 1, 0, 0.0026, 0.0009, 0, 0....
[ "from django.conf import settings", "from django.db import connection, router, transaction, connections", "from django.db.backends import util", "from django.db.models import signals, get_model", "from django.db.models.fields import (AutoField, Field, IntegerField,\n PositiveIntegerField, PositiveSmallIn...
""" Convenience routines for creating non-trivial Field subclasses, as well as backwards compatibility utilities. Add SubfieldBase as the __metaclass__ for your Field subclass, implement to_python() and the other necessary methods and everything will work seamlessly. """ from inspect import getargspec from warnings import warn def call_with_connection(func): arg_names, varargs, varkwargs, defaults = getargspec(func) updated = ('connection' in arg_names or varkwargs) if not updated: warn("A Field class whose %s method hasn't been updated to take a " "`connection` argument." % func.__name__, DeprecationWarning, stacklevel=3) def inner(*args, **kwargs): if 'connection' not in kwargs: from django.db import connection kwargs['connection'] = connection warn("%s has been called without providing a connection argument. " % func.__name__, DeprecationWarning, stacklevel=2) if updated: return func(*args, **kwargs) if 'connection' in kwargs: del kwargs['connection'] return func(*args, **kwargs) return inner def call_with_connection_and_prepared(func): arg_names, varargs, varkwargs, defaults = getargspec(func) updated = ( ('connection' in arg_names or varkwargs) and ('prepared' in arg_names or varkwargs) ) if not updated: warn("A Field class whose %s method hasn't been updated to take " "`connection` and `prepared` arguments." % func.__name__, DeprecationWarning, stacklevel=3) def inner(*args, **kwargs): if 'connection' not in kwargs: from django.db import connection kwargs['connection'] = connection warn("%s has been called without providing a connection argument. " % func.__name__, DeprecationWarning, stacklevel=2) if updated: return func(*args, **kwargs) if 'connection' in kwargs: del kwargs['connection'] if 'prepared' in kwargs: del kwargs['prepared'] return func(*args, **kwargs) return inner class LegacyConnection(type): """ A metaclass to normalize arguments give to the get_db_prep_* and db_type methods on fields. """ def __new__(cls, names, bases, attrs): new_cls = super(LegacyConnection, cls).__new__(cls, names, bases, attrs) for attr in ('db_type', 'get_db_prep_save'): setattr(new_cls, attr, call_with_connection(getattr(new_cls, attr))) for attr in ('get_db_prep_lookup', 'get_db_prep_value'): setattr(new_cls, attr, call_with_connection_and_prepared(getattr(new_cls, attr))) return new_cls class SubfieldBase(LegacyConnection): """ A metaclass for custom Field subclasses. This ensures the model's attribute has the descriptor protocol attached to it. """ def __new__(cls, base, name, attrs): new_class = super(SubfieldBase, cls).__new__(cls, base, name, attrs) new_class.contribute_to_class = make_contrib( new_class, attrs.get('contribute_to_class') ) return new_class class Creator(object): """ A placeholder class that provides a way to set the attribute on the model. """ def __init__(self, field): self.field = field def __get__(self, obj, type=None): if obj is None: raise AttributeError('Can only be accessed via an instance.') return obj.__dict__[self.field.name] def __set__(self, obj, value): obj.__dict__[self.field.name] = self.field.to_python(value) def make_contrib(superclass, func=None): """ Returns a suitable contribute_to_class() method for the Field subclass. If 'func' is passed in, it is the existing contribute_to_class() method on the subclass and it is called before anything else. It is assumed in this case that the existing contribute_to_class() calls all the necessary superclass methods. """ def contribute_to_class(self, cls, name): if func: func(self, cls, name) else: super(superclass, self).contribute_to_class(cls, name) setattr(cls, self.name, Creator(self)) return contribute_to_class
[ [ 8, 0, 0.0342, 0.0598, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0769, 0.0085, 0, 0.66, 0.125, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.0855, 0.0085, 0, 0.66,...
[ "\"\"\"\nConvenience routines for creating non-trivial Field subclasses, as well as\nbackwards compatibility utilities.\n\nAdd SubfieldBase as the __metaclass__ for your Field subclass, implement\nto_python() and the other necessary methods and everything will work seamlessly.\n\"\"\"", "from inspect import getar...
"Utilities for loading models and the modules that contain them." from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule import imp import sys import os import threading __all__ = ('get_apps', 'get_app', 'get_models', 'get_model', 'register_models', 'load_app', 'app_cache_ready') class AppCache(object): """ A cache that stores installed applications and their models. Used to provide reverse-relations and for app introspection (e.g. admin). """ # Use the Borg pattern to share state between all instances. Details at # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531. __shared_state = dict( # Keys of app_store are the model modules for each application. app_store = SortedDict(), # Mapping of app_labels to a dictionary of model names to model code. app_models = SortedDict(), # Mapping of app_labels to errors raised when trying to import the app. app_errors = {}, # -- Everything below here is only used when populating the cache -- loaded = False, handled = {}, postponed = [], nesting_level = 0, write_lock = threading.RLock(), _get_models_cache = {}, ) def __init__(self): self.__dict__ = self.__shared_state def _populate(self): """ Fill in all the cache information. This method is threadsafe, in the sense that every caller will see the same state upon return, and if the cache is already initialised, it does no work. """ if self.loaded: return self.write_lock.acquire() try: if self.loaded: return for app_name in settings.INSTALLED_APPS: if app_name in self.handled: continue self.load_app(app_name, True) if not self.nesting_level: for app_name in self.postponed: self.load_app(app_name) self.loaded = True finally: self.write_lock.release() def load_app(self, app_name, can_postpone=False): """ Loads the app with the provided fully qualified name, and returns the model module. """ self.handled[app_name] = None self.nesting_level += 1 app_module = import_module(app_name) try: models = import_module('.models', app_name) except ImportError: self.nesting_level -= 1 # If the app doesn't have a models module, we can just ignore the # ImportError and return no models for it. if not module_has_submodule(app_module, 'models'): return None # But if the app does have a models module, we need to figure out # whether to suppress or propagate the error. If can_postpone is # True then it may be that the package is still being imported by # Python and the models module isn't available yet. So we add the # app to the postponed list and we'll try it again after all the # recursion has finished (in populate). If can_postpone is False # then it's time to raise the ImportError. else: if can_postpone: self.postponed.append(app_name) return None else: raise self.nesting_level -= 1 if models not in self.app_store: self.app_store[models] = len(self.app_store) return models def app_cache_ready(self): """ Returns true if the model cache is fully populated. Useful for code that wants to cache the results of get_models() for themselves once it is safe to do so. """ return self.loaded def get_apps(self): "Returns a list of all installed modules that contain models." self._populate() # Ensure the returned list is always in the same order (with new apps # added at the end). This avoids unstable ordering on the admin app # list page, for example. apps = [(v, k) for k, v in self.app_store.items()] apps.sort() return [elt[1] for elt in apps] def get_app(self, app_label, emptyOK=False): """ Returns the module containing the models for the given app_label. If the app has no models in it and 'emptyOK' is True, returns None. """ self._populate() self.write_lock.acquire() try: for app_name in settings.INSTALLED_APPS: if app_label == app_name.split('.')[-1]: mod = self.load_app(app_name, False) if mod is None: if emptyOK: return None else: return mod raise ImproperlyConfigured("App with label %s could not be found" % app_label) finally: self.write_lock.release() def get_app_errors(self): "Returns the map of known problems with the INSTALLED_APPS." self._populate() return self.app_errors def get_models(self, app_mod=None, include_auto_created=False, include_deferred=False): """ Given a module containing models, returns a list of the models. Otherwise returns a list of all installed models. By default, auto-created models (i.e., m2m models without an explicit intermediate table) are not included. However, if you specify include_auto_created=True, they will be. By default, models created to satisfy deferred attribute queries are *not* included in the list of models. However, if you specify include_deferred, they will be. """ cache_key = (app_mod, include_auto_created, include_deferred) try: return self._get_models_cache[cache_key] except KeyError: pass self._populate() if app_mod: app_list = [self.app_models.get(app_mod.__name__.split('.')[-2], SortedDict())] else: app_list = self.app_models.itervalues() model_list = [] for app in app_list: model_list.extend( model for model in app.values() if ((not model._deferred or include_deferred) and (not model._meta.auto_created or include_auto_created)) ) self._get_models_cache[cache_key] = model_list return model_list def get_model(self, app_label, model_name, seed_cache=True): """ Returns the model matching the given app_label and case-insensitive model_name. Returns None if no model is found. """ if seed_cache: self._populate() return self.app_models.get(app_label, SortedDict()).get(model_name.lower()) def register_models(self, app_label, *models): """ Register a set of models as belonging to an app. """ for model in models: # Store as 'name: model' pair in a dictionary # in the app_models dictionary model_name = model._meta.object_name.lower() model_dict = self.app_models.setdefault(app_label, SortedDict()) if model_name in model_dict: # The same model may be imported via different paths (e.g. # appname.models and project.appname.models). We use the source # filename as a means to detect identity. fname1 = os.path.abspath(sys.modules[model.__module__].__file__) fname2 = os.path.abspath(sys.modules[model_dict[model_name].__module__].__file__) # Since the filename extension could be .py the first time and # .pyc or .pyo the second time, ignore the extension when # comparing. if os.path.splitext(fname1)[0] == os.path.splitext(fname2)[0]: continue model_dict[model_name] = model self._get_models_cache.clear() cache = AppCache() # These methods were always module level, so are kept that way for backwards # compatibility. get_apps = cache.get_apps get_app = cache.get_app get_app_errors = cache.get_app_errors get_models = cache.get_models get_model = cache.get_model register_models = cache.register_models load_app = cache.load_app app_cache_ready = cache.app_cache_ready
[ [ 8, 0, 0.0044, 0.0044, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0132, 0.0044, 0, 0.66, 0.05, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0176, 0.0044, 0, 0.66, ...
[ "\"Utilities for loading models and the modules that contain them.\"", "from django.conf import settings", "from django.core.exceptions import ImproperlyConfigured", "from django.utils.datastructures import SortedDict", "from django.utils.importlib import import_module", "from django.utils.module_loading ...
""" Classes to represent the definitions of aggregate functions. """ class Aggregate(object): """ Default Aggregate definition. """ def __init__(self, lookup, **extra): """Instantiate a new aggregate. * lookup is the field on which the aggregate operates. * extra is a dictionary of additional data to provide for the aggregate definition Also utilizes the class variables: * name, the identifier for this aggregate function. """ self.lookup = lookup self.extra = extra def _default_alias(self): return '%s__%s' % (self.lookup, self.name.lower()) default_alias = property(_default_alias) def add_to_query(self, query, alias, col, source, is_summary): """Add the aggregate to the nominated query. This method is used to convert the generic Aggregate definition into a backend-specific definition. * query is the backend-specific query instance to which the aggregate is to be added. * col is a column reference describing the subject field of the aggregate. It can be an alias, or a tuple describing a table and column name. * source is the underlying field or aggregate definition for the column reference. If the aggregate is not an ordinal or computed type, this reference is used to determine the coerced output type of the aggregate. * is_summary is a boolean that is set True if the aggregate is a summary value rather than an annotation. """ klass = getattr(query.aggregates_module, self.name) aggregate = klass(col, source=source, is_summary=is_summary, **self.extra) query.aggregates[alias] = aggregate class Avg(Aggregate): name = 'Avg' class Count(Aggregate): name = 'Count' class Max(Aggregate): name = 'Max' class Min(Aggregate): name = 'Min' class StdDev(Aggregate): name = 'StdDev' class Sum(Aggregate): name = 'Sum' class Variance(Aggregate): name = 'Variance'
[ [ 8, 0, 0.0299, 0.0448, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 3, 0, 0.3806, 0.6269, 0, 0.66, 0.125, 451, 0, 3, 0, 0, 186, 0, 4 ], [ 8, 1, 0.1045, 0.0448, 1, 0.13,...
[ "\"\"\"\nClasses to represent the definitions of aggregate functions.\n\"\"\"", "class Aggregate(object):\n \"\"\"\n Default Aggregate definition.\n \"\"\"\n def __init__(self, lookup, **extra):\n \"\"\"Instantiate a new aggregate.\n\n * lookup is the field on which the aggregate operat...
import re from bisect import bisect from django.conf import settings from django.db.models.related import RelatedObject from django.db.models.fields.related import ManyToManyRel from django.db.models.fields import AutoField, FieldDoesNotExist from django.db.models.fields.proxy import OrderWrt from django.db.models.loading import get_models, app_cache_ready from django.utils.translation import activate, deactivate_all, get_language, string_concat from django.utils.encoding import force_unicode, smart_str from django.utils.datastructures import SortedDict try: all except NameError: from django.utils.itercompat import all # Calculate the verbose_name by converting from InitialCaps to "lowercase with spaces". get_verbose_name = lambda class_name: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', ' \\1', class_name).lower().strip() DEFAULT_NAMES = ('verbose_name', 'db_table', 'ordering', 'unique_together', 'permissions', 'get_latest_by', 'order_with_respect_to', 'app_label', 'db_tablespace', 'abstract', 'managed', 'proxy', 'auto_created') class Options(object): def __init__(self, meta, app_label=None): self.local_fields, self.local_many_to_many = [], [] self.virtual_fields = [] self.module_name, self.verbose_name = None, None self.verbose_name_plural = None self.db_table = '' self.ordering = [] self.unique_together = [] self.permissions = [] self.object_name, self.app_label = None, app_label self.get_latest_by = None self.order_with_respect_to = None self.db_tablespace = settings.DEFAULT_TABLESPACE self.admin = None self.meta = meta self.pk = None self.has_auto_field, self.auto_field = False, None self.abstract = False self.managed = True self.proxy = False self.proxy_for_model = None self.parents = SortedDict() self.duplicate_targets = {} self.auto_created = False # To handle various inheritance situations, we need to track where # managers came from (concrete or abstract base classes). self.abstract_managers = [] self.concrete_managers = [] def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.util import truncate_name cls._meta = self self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS # First, construct the default values for these options. self.object_name = cls.__name__ self.module_name = self.object_name.lower() self.verbose_name = get_verbose_name(self.object_name) # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) # unique_together can be either a tuple of tuples, or a single # tuple of two strings. Normalize it to a tuple of tuples, so that # calling code can uniformly expect that. ut = meta_attrs.pop('unique_together', self.unique_together) if ut and not isinstance(ut[0], (tuple, list)): ut = (ut,) self.unique_together = ut # verbose_name_plural is a special case because it uses a 's' # by default. self.verbose_name_plural = meta_attrs.pop('verbose_name_plural', string_concat(self.verbose_name, 's')) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())) else: self.verbose_name_plural = string_concat(self.verbose_name, 's') del self.meta # If the db_table wasn't provided, use the app_label + module_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.module_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) def _prepare(self, model): if self.order_with_respect_to: self.order_with_respect_to = self.get_field(self.order_with_respect_to) self.ordering = ('_order',) model.add_to_class('_order', OrderWrt()) else: self.order_with_respect_to = None if self.pk is None: if self.parents: # Promote the first parent link in lieu of adding yet another # field. field = self.parents.value_for_index(0) field.primary_key = True self.setup_pk(field) else: auto = AutoField(verbose_name='ID', primary_key=True, auto_created=True) model.add_to_class('id', auto) # Determine any sets of fields that are pointing to the same targets # (e.g. two ForeignKeys to the same remote model). The query # construction code needs to know this. At the end of this, # self.duplicate_targets will map each duplicate field column to the # columns it duplicates. collections = {} for column, target in self.duplicate_targets.iteritems(): try: collections[target].add(column) except KeyError: collections[target] = set([column]) self.duplicate_targets = {} for elt in collections.itervalues(): if len(elt) == 1: continue for column in elt: self.duplicate_targets[column] = elt.difference(set([column])) def add_field(self, field): # Insert the given field in the order in which it was created, using # the "creation_counter" attribute of the field. # Move many-to-many related fields from self.fields into # self.many_to_many. if field.rel and isinstance(field.rel, ManyToManyRel): self.local_many_to_many.insert(bisect(self.local_many_to_many, field), field) if hasattr(self, '_m2m_cache'): del self._m2m_cache else: self.local_fields.insert(bisect(self.local_fields, field), field) self.setup_pk(field) if hasattr(self, '_field_cache'): del self._field_cache del self._field_name_cache if hasattr(self, '_name_map'): del self._name_map def add_virtual_field(self, field): self.virtual_fields.append(field) def setup_pk(self, field): if not self.pk and field.primary_key: self.pk = field field.serialize = False def setup_proxy(self, target): """ Does the internal setup so that the current model is a proxy for "target". """ self.pk = target._meta.pk self.proxy_for_model = target self.db_table = target._meta.db_table def __repr__(self): return '<Options for %s>' % self.object_name def __str__(self): return "%s.%s" % (smart_str(self.app_label), smart_str(self.module_name)) def verbose_name_raw(self): """ There are a few places where the untranslated verbose name is needed (so that we get the same value regardless of currently active locale). """ lang = get_language() deactivate_all() raw = force_unicode(self.verbose_name) activate(lang) return raw verbose_name_raw = property(verbose_name_raw) def _fields(self): """ The getter for self.fields. This returns the list of field objects available to this model (including through parent models). Callers are not permitted to modify this list, since it's a reference to this instance (not a copy). """ try: self._field_name_cache except AttributeError: self._fill_fields_cache() return self._field_name_cache fields = property(_fields) def get_fields_with_model(self): """ Returns a sequence of (field, model) pairs for all fields. The "model" element is None for fields on the current model. Mostly of use when constructing queries so that we know which model a field belongs to. """ try: self._field_cache except AttributeError: self._fill_fields_cache() return self._field_cache def _fill_fields_cache(self): cache = [] for parent in self.parents: for field, model in parent._meta.get_fields_with_model(): if model: cache.append((field, model)) else: cache.append((field, parent)) cache.extend([(f, None) for f in self.local_fields]) self._field_cache = tuple(cache) self._field_name_cache = [x for x, _ in cache] def _many_to_many(self): try: self._m2m_cache except AttributeError: self._fill_m2m_cache() return self._m2m_cache.keys() many_to_many = property(_many_to_many) def get_m2m_with_model(self): """ The many-to-many version of get_fields_with_model(). """ try: self._m2m_cache except AttributeError: self._fill_m2m_cache() return self._m2m_cache.items() def _fill_m2m_cache(self): cache = SortedDict() for parent in self.parents: for field, model in parent._meta.get_m2m_with_model(): if model: cache[field] = model else: cache[field] = parent for field in self.local_many_to_many: cache[field] = None self._m2m_cache = cache def get_field(self, name, many_to_many=True): """ Returns the requested field by name. Raises FieldDoesNotExist on error. """ to_search = many_to_many and (self.fields + self.many_to_many) or self.fields for f in to_search: if f.name == name: return f raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name)) def get_field_by_name(self, name): """ Returns the (field_object, model, direct, m2m), where field_object is the Field instance for the given name, model is the model containing this field (None for local fields), direct is True if the field exists on this model, and m2m is True for many-to-many relations. When 'direct' is False, 'field_object' is the corresponding RelatedObject for this field (since the field doesn't have an instance associated with it). Uses a cache internally, so after the first access, this is very fast. """ try: try: return self._name_map[name] except AttributeError: cache = self.init_name_map() return cache[name] except KeyError: raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name)) def get_all_field_names(self): """ Returns a list of all field names that are possible for this model (including reverse relation names). This is used for pretty printing debugging output (a list of choices), so any internal-only field names are not included. """ try: cache = self._name_map except AttributeError: cache = self.init_name_map() names = cache.keys() names.sort() # Internal-only names end with "+" (symmetrical m2m related names being # the main example). Trim them. return [val for val in names if not val.endswith('+')] def init_name_map(self): """ Initialises the field name -> field object mapping. """ cache = {} # We intentionally handle related m2m objects first so that symmetrical # m2m accessor names can be overridden, if necessary. for f, model in self.get_all_related_m2m_objects_with_model(): cache[f.field.related_query_name()] = (f, model, False, True) for f, model in self.get_all_related_objects_with_model(): cache[f.field.related_query_name()] = (f, model, False, False) for f, model in self.get_m2m_with_model(): cache[f.name] = (f, model, True, True) for f, model in self.get_fields_with_model(): cache[f.name] = (f, model, True, False) if app_cache_ready(): self._name_map = cache return cache def get_add_permission(self): return 'add_%s' % self.object_name.lower() def get_change_permission(self): return 'change_%s' % self.object_name.lower() def get_delete_permission(self): return 'delete_%s' % self.object_name.lower() def get_all_related_objects(self, local_only=False, include_hidden=False): return [k for k, v in self.get_all_related_objects_with_model( local_only=local_only, include_hidden=include_hidden)] def get_all_related_objects_with_model(self, local_only=False, include_hidden=False): """ Returns a list of (related-object, model) pairs. Similar to get_fields_with_model(). """ try: self._related_objects_cache except AttributeError: self._fill_related_objects_cache() predicates = [] if local_only: predicates.append(lambda k, v: not v) if not include_hidden: predicates.append(lambda k, v: not k.field.rel.is_hidden()) return filter(lambda t: all([p(*t) for p in predicates]), self._related_objects_cache.items()) def _fill_related_objects_cache(self): cache = SortedDict() parent_list = self.get_parent_list() for parent in self.parents: for obj, model in parent._meta.get_all_related_objects_with_model(): if (obj.field.creation_counter < 0 or obj.field.rel.parent_link) and obj.model not in parent_list: continue if not model: cache[obj] = parent else: cache[obj] = model for klass in get_models(include_auto_created=True): for f in klass._meta.local_fields: if f.rel and not isinstance(f.rel.to, str) and self == f.rel.to._meta: cache[RelatedObject(f.rel.to, klass, f)] = None self._related_objects_cache = cache def get_all_related_many_to_many_objects(self, local_only=False): try: cache = self._related_many_to_many_cache except AttributeError: cache = self._fill_related_many_to_many_cache() if local_only: return [k for k, v in cache.items() if not v] return cache.keys() def get_all_related_m2m_objects_with_model(self): """ Returns a list of (related-m2m-object, model) pairs. Similar to get_fields_with_model(). """ try: cache = self._related_many_to_many_cache except AttributeError: cache = self._fill_related_many_to_many_cache() return cache.items() def _fill_related_many_to_many_cache(self): cache = SortedDict() parent_list = self.get_parent_list() for parent in self.parents: for obj, model in parent._meta.get_all_related_m2m_objects_with_model(): if obj.field.creation_counter < 0 and obj.model not in parent_list: continue if not model: cache[obj] = parent else: cache[obj] = model for klass in get_models(): for f in klass._meta.local_many_to_many: if f.rel and not isinstance(f.rel.to, str) and self == f.rel.to._meta: cache[RelatedObject(f.rel.to, klass, f)] = None if app_cache_ready(): self._related_many_to_many_cache = cache return cache def get_base_chain(self, model): """ Returns a list of parent classes leading to 'model' (order from closet to most distant ancestor). This has to handle the case were 'model' is a granparent or even more distant relation. """ if not self.parents: return if model in self.parents: return [model] for parent in self.parents: res = parent._meta.get_base_chain(model) if res: res.insert(0, parent) return res raise TypeError('%r is not an ancestor of this model' % model._meta.module_name) def get_parent_list(self): """ Returns a list of all the ancestor of this model as a list. Useful for determining if something is an ancestor, regardless of lineage. """ result = set() for parent in self.parents: result.add(parent) result.update(parent._meta.get_parent_list()) return result def get_ancestor_link(self, ancestor): """ Returns the field on the current model which points to the given "ancestor". This is possible an indirect link (a pointer to a parent model, which points, eventually, to the ancestor). Used when constructing table joins for model inheritance. Returns None if the model isn't an ancestor of this one. """ if ancestor in self.parents: return self.parents[ancestor] for parent in self.parents: # Tries to get a link field from the immediate parent parent_link = parent._meta.get_ancestor_link(ancestor) if parent_link: # In case of a proxied model, the first link # of the chain to the ancestor is that parent # links return self.parents[parent] or parent_link def get_ordered_objects(self): "Returns a list of Options objects that are ordered with respect to this object." if not hasattr(self, '_ordered_objects'): objects = [] # TODO #for klass in get_models(get_app(self.app_label)): # opts = klass._meta # if opts.order_with_respect_to and opts.order_with_respect_to.rel \ # and self == opts.order_with_respect_to.rel.to._meta: # objects.append(opts) self._ordered_objects = objects return self._ordered_objects def pk_index(self): """ Returns the index of the primary key field in the self.fields list. """ return self.fields.index(self.pk)
[ [ 1, 0, 0.002, 0.002, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0041, 0.002, 0, 0.66, 0.0714, 325, 0, 1, 0, 0, 325, 0, 0 ], [ 1, 0, 0.0081, 0.002, 0, 0.66...
[ "import re", "from bisect import bisect", "from django.conf import settings", "from django.db.models.related import RelatedObject", "from django.db.models.fields.related import ManyToManyRel", "from django.db.models.fields import AutoField, FieldDoesNotExist", "from django.db.models.fields.proxy import ...
class BoundRelatedObject(object): def __init__(self, related_object, field_mapping, original): self.relation = related_object self.field_mappings = field_mapping[related_object.name] def template_name(self): raise NotImplementedError def __repr__(self): return repr(self.__dict__) class RelatedObject(object): def __init__(self, parent_model, model, field): self.parent_model = parent_model self.model = model self.opts = model._meta self.field = field self.name = '%s:%s' % (self.opts.app_label, self.opts.module_name) self.var_name = self.opts.object_name.lower() def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): # Defer to the actual field definition for db prep return self.field.get_db_prep_lookup(lookup_type, value, connection=connection, prepared=prepared) def editable_fields(self): "Get the fields in this class that should be edited inline." return [f for f in self.opts.fields + self.opts.many_to_many if f.editable and f != self.field] def __repr__(self): return "<RelatedObject: %s related to %s>" % (self.name, self.field.name) def bind(self, field_mapping, original, bound_related_object_class=BoundRelatedObject): return bound_related_object_class(self, field_mapping, original) def get_accessor_name(self): # This method encapsulates the logic that decides what name to give an # accessor descriptor that retrieves related many-to-one or # many-to-many objects. It uses the lower-cased object_name + "_set", # but this can be overridden with the "related_name" option. if self.field.rel.multiple: # If this is a symmetrical m2m relation on self, there is no reverse accessor. if getattr(self.field.rel, 'symmetrical', False) and self.model == self.parent_model: return None return self.field.rel.related_name or (self.opts.object_name.lower() + '_set') else: return self.field.rel.related_name or (self.opts.object_name.lower()) def get_cache_name(self): return "_%s_cache" % self.get_accessor_name()
[ [ 3, 0, 0.11, 0.2, 0, 0.66, 0, 875, 0, 3, 0, 0, 186, 0, 1 ], [ 2, 1, 0.06, 0.06, 1, 0.51, 0, 555, 0, 4, 0, 0, 0, 0, 0 ], [ 14, 2, 0.06, 0.02, 2, 0.73, 0, 25...
[ "class BoundRelatedObject(object):\n def __init__(self, related_object, field_mapping, original):\n self.relation = related_object\n self.field_mappings = field_mapping[related_object.name]\n\n def template_name(self):\n raise NotImplementedError", " def __init__(self, related_object...
from django.conf import settings from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured from django.db import connection from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models from django.db.models.query import Q from django.db.models.expressions import F from django.db.models.manager import Manager from django.db.models.base import Model from django.db.models.aggregates import * from django.db.models.fields import * from django.db.models.fields.subclassing import SubfieldBase from django.db.models.fields.files import FileField, ImageField from django.db.models.fields.related import ForeignKey, OneToOneField, ManyToManyField, ManyToOneRel, ManyToManyRel, OneToOneRel from django.db.models.deletion import CASCADE, PROTECT, SET, SET_NULL, SET_DEFAULT, DO_NOTHING from django.db.models import signals # Admin stages. ADD, CHANGE, BOTH = 1, 2, 3 def permalink(func): """ Decorator that calls urlresolvers.reverse() to return a URL using parameters returned by the decorated function "func". "func" should be a function that returns a tuple in one of the following formats: (viewname, viewargs) (viewname, viewargs, viewkwargs) """ from django.core.urlresolvers import reverse def inner(*args, **kwargs): bits = func(*args, **kwargs) return reverse(bits[0], None, *bits[1:3]) return inner
[ [ 1, 0, 0.0294, 0.0294, 0, 0.66, 0, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0588, 0.0294, 0, 0.66, 0.0625, 160, 0, 2, 0, 0, 160, 0, 0 ], [ 1, 0, 0.0882, 0.0294, 0, ...
[ "from django.conf import settings", "from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured", "from django.db import connection", "from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models", "from django.db.models.query import Q", "from django.db.m...
from django.utils import copycompat as copy from django.conf import settings from django.db import router from django.db.models.query import QuerySet, EmptyQuerySet, insert_query, RawQuerySet from django.db.models import signals from django.db.models.fields import FieldDoesNotExist def ensure_default_manager(sender, **kwargs): """ Ensures that a Model subclass contains a default manager and sets the _default_manager attribute on the class. Also sets up the _base_manager points to a plain Manager instance (which could be the same as _default_manager if it's not a subclass of Manager). """ cls = sender if cls._meta.abstract: return if not getattr(cls, '_default_manager', None): # Create the default manager, if needed. try: cls._meta.get_field('objects') raise ValueError("Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__) except FieldDoesNotExist: pass cls.add_to_class('objects', Manager()) cls._base_manager = cls.objects elif not getattr(cls, '_base_manager', None): default_mgr = cls._default_manager.__class__ if (default_mgr is Manager or getattr(default_mgr, "use_for_related_fields", False)): cls._base_manager = cls._default_manager else: # Default manager isn't a plain Manager class, or a suitable # replacement, so we walk up the base class hierarchy until we hit # something appropriate. for base_class in default_mgr.mro()[1:]: if (base_class is Manager or getattr(base_class, "use_for_related_fields", False)): cls.add_to_class('_base_manager', base_class()) return raise AssertionError("Should never get here. Please report a bug, including your model and model manager setup.") signals.class_prepared.connect(ensure_default_manager) class Manager(object): # Tracks each time a Manager instance is created. Used to retain order. creation_counter = 0 def __init__(self): super(Manager, self).__init__() self._set_creation_counter() self.model = None self._inherited = False self._db = None def contribute_to_class(self, model, name): # TODO: Use weakref because of possible memory leak / circular reference. self.model = model setattr(model, name, ManagerDescriptor(self)) if not getattr(model, '_default_manager', None) or self.creation_counter < model._default_manager.creation_counter: model._default_manager = self if model._meta.abstract or (self._inherited and not self.model._meta.proxy): model._meta.abstract_managers.append((self.creation_counter, name, self)) else: model._meta.concrete_managers.append((self.creation_counter, name, self)) def _set_creation_counter(self): """ Sets the creation counter value for this instance and increments the class-level copy. """ self.creation_counter = Manager.creation_counter Manager.creation_counter += 1 def _copy_to_model(self, model): """ Makes a copy of the manager and assigns it to 'model', which should be a child of the existing model (used when inheriting a manager from an abstract base class). """ assert issubclass(model, self.model) mgr = copy.copy(self) mgr._set_creation_counter() mgr.model = model mgr._inherited = True return mgr def db_manager(self, using): obj = copy.copy(self) obj._db = using return obj @property def db(self): return self._db or router.db_for_read(self.model) ####################### # PROXIES TO QUERYSET # ####################### def get_empty_query_set(self): return EmptyQuerySet(self.model, using=self._db) def get_query_set(self): """Returns a new QuerySet object. Subclasses can override this method to easily customize the behavior of the Manager. """ return QuerySet(self.model, using=self._db) def none(self): return self.get_empty_query_set() def all(self): return self.get_query_set() def count(self): return self.get_query_set().count() def dates(self, *args, **kwargs): return self.get_query_set().dates(*args, **kwargs) def distinct(self, *args, **kwargs): return self.get_query_set().distinct(*args, **kwargs) def extra(self, *args, **kwargs): return self.get_query_set().extra(*args, **kwargs) def get(self, *args, **kwargs): return self.get_query_set().get(*args, **kwargs) def get_or_create(self, **kwargs): return self.get_query_set().get_or_create(**kwargs) def create(self, **kwargs): return self.get_query_set().create(**kwargs) def filter(self, *args, **kwargs): return self.get_query_set().filter(*args, **kwargs) def aggregate(self, *args, **kwargs): return self.get_query_set().aggregate(*args, **kwargs) def annotate(self, *args, **kwargs): return self.get_query_set().annotate(*args, **kwargs) def complex_filter(self, *args, **kwargs): return self.get_query_set().complex_filter(*args, **kwargs) def exclude(self, *args, **kwargs): return self.get_query_set().exclude(*args, **kwargs) def in_bulk(self, *args, **kwargs): return self.get_query_set().in_bulk(*args, **kwargs) def iterator(self, *args, **kwargs): return self.get_query_set().iterator(*args, **kwargs) def latest(self, *args, **kwargs): return self.get_query_set().latest(*args, **kwargs) def order_by(self, *args, **kwargs): return self.get_query_set().order_by(*args, **kwargs) def select_related(self, *args, **kwargs): return self.get_query_set().select_related(*args, **kwargs) def values(self, *args, **kwargs): return self.get_query_set().values(*args, **kwargs) def values_list(self, *args, **kwargs): return self.get_query_set().values_list(*args, **kwargs) def update(self, *args, **kwargs): return self.get_query_set().update(*args, **kwargs) def reverse(self, *args, **kwargs): return self.get_query_set().reverse(*args, **kwargs) def defer(self, *args, **kwargs): return self.get_query_set().defer(*args, **kwargs) def only(self, *args, **kwargs): return self.get_query_set().only(*args, **kwargs) def using(self, *args, **kwargs): return self.get_query_set().using(*args, **kwargs) def exists(self, *args, **kwargs): return self.get_query_set().exists(*args, **kwargs) def _insert(self, values, **kwargs): return insert_query(self.model, values, **kwargs) def _update(self, values, **kwargs): return self.get_query_set()._update(values, **kwargs) def raw(self, raw_query, params=None, *args, **kwargs): return RawQuerySet(raw_query=raw_query, model=self.model, params=params, using=self._db, *args, **kwargs) class ManagerDescriptor(object): # This class ensures managers aren't accessible via model instances. # For example, Poll.objects works, but poll_obj.objects raises AttributeError. def __init__(self, manager): self.manager = manager def __get__(self, instance, type=None): if instance != None: raise AttributeError("Manager isn't accessible via %s instances" % type.__name__) return self.manager class EmptyManager(Manager): def get_query_set(self): return self.get_empty_query_set()
[ [ 1, 0, 0.0046, 0.0046, 0, 0.66, 0, 944, 0, 1, 0, 0, 944, 0, 0 ], [ 1, 0, 0.0093, 0.0046, 0, 0.66, 0.1, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0139, 0.0046, 0, 0.6...
[ "from django.utils import copycompat as copy", "from django.conf import settings", "from django.db import router", "from django.db.models.query import QuerySet, EmptyQuerySet, insert_query, RawQuerySet", "from django.db.models import signals", "from django.db.models.fields import FieldDoesNotExist", "de...
""" Various data structures used in query construction. Factored out from django.db.models.query to avoid making the main module very large and/or so that they can be used by other modules without getting into circular import difficulties. """ import weakref from django.utils.copycompat import deepcopy from django.db.backends import util from django.utils import tree from django.utils.datastructures import SortedDict class InvalidQuery(Exception): """ The query passed to raw isn't a safe query to use with raw. """ pass class QueryWrapper(object): """ A type that indicates the contents are an SQL fragment and the associate parameters. Can be used to pass opaque data to a where-clause, for example. """ def __init__(self, sql, params): self.data = sql, params def as_sql(self, qn=None, connection=None): return self.data class Q(tree.Node): """ Encapsulates filters as objects that can then be combined logically (using & and |). """ # Connection types AND = 'AND' OR = 'OR' default = AND def __init__(self, *args, **kwargs): super(Q, self).__init__(children=list(args) + kwargs.items()) def _combine(self, other, conn): if not isinstance(other, Q): raise TypeError(other) obj = type(self)() obj.add(self, conn) obj.add(other, conn) return obj def __or__(self, other): return self._combine(other, self.OR) def __and__(self, other): return self._combine(other, self.AND) def __invert__(self): obj = type(self)() obj.add(self, self.AND) obj.negate() return obj class DeferredAttribute(object): """ A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed. """ def __init__(self, field_name, model): self.field_name = field_name self.model_ref = weakref.ref(model) self.loaded = False def __get__(self, instance, owner): """ Retrieves and caches the value from the datastore on the first lookup. Returns the cached value. """ from django.db.models.fields import FieldDoesNotExist assert instance is not None cls = self.model_ref() data = instance.__dict__ if data.get(self.field_name, self) is self: # self.field_name is the attname of the field, but only() takes the # actual name, so we need to translate it here. try: cls._meta.get_field_by_name(self.field_name) name = self.field_name except FieldDoesNotExist: name = [f.name for f in cls._meta.fields if f.attname == self.field_name][0] # We use only() instead of values() here because we want the # various data coersion methods (to_python(), etc.) to be called # here. val = getattr( cls._base_manager.filter(pk=instance.pk).only(name).using( instance._state.db).get(), self.field_name ) data[self.field_name] = val return data[self.field_name] def __set__(self, instance, value): """ Deferred loading attributes can be set normally (which means there will never be a database lookup involved. """ instance.__dict__[self.field_name] = value def select_related_descend(field, restricted, requested, reverse=False): """ Returns True if this field should be used to descend deeper for select_related() purposes. Used by both the query construction code (sql.query.fill_related_selections()) and the model instance creation code (query.get_cached_row()). Arguments: * field - the field to be checked * restricted - a boolean field, indicating if the field list has been manually restricted using a requested clause) * requested - The select_related() dictionary. * reverse - boolean, True if we are checking a reverse select related """ if not field.rel: return False if field.rel.parent_link and not reverse: return False if restricted: if reverse and field.related_query_name() not in requested: return False if not reverse and field.name not in requested: return False if not restricted and field.null: return False return True # This function is needed because data descriptors must be defined on a class # object, not an instance, to have any effect. def deferred_class_factory(model, attrs): """ Returns a class object that is a copy of "model" with the specified "attrs" being replaced with DeferredAttribute objects. The "pk_value" ties the deferred attributes to a particular instance of the model. """ class Meta: proxy = True app_label = model._meta.app_label # The app_cache wants a unique name for each model, otherwise the new class # won't be created (we get an old one back). Therefore, we generate the # name using the passed in attrs. It's OK to reuse an existing class # object if the attrs are identical. name = "%s_Deferred_%s" % (model.__name__, '_'.join(sorted(list(attrs)))) name = util.truncate_name(name, 80, 32) overrides = dict([(attr, DeferredAttribute(attr, model)) for attr in attrs]) overrides["Meta"] = Meta overrides["__module__"] = model.__module__ overrides["_deferred"] = True return type(name, (model,), overrides) # The above function is also used to unpickle model instances with deferred # fields. deferred_class_factory.__safe_for_unpickling__ = True
[ [ 8, 0, 0.0234, 0.0409, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0526, 0.0058, 0, 0.66, 0.0833, 708, 0, 1, 0, 0, 708, 0, 0 ], [ 1, 0, 0.0585, 0.0058, 0, 0.66...
[ "\"\"\"\nVarious data structures used in query construction.\n\nFactored out from django.db.models.query to avoid making the main module very\nlarge and/or so that they can be used by other modules without getting into\ncircular import difficulties.\n\"\"\"", "import weakref", "from django.utils.copycompat impo...
""" This module implements a transaction manager that can be used to define transaction handling in a request or view function. It is used by transaction control middleware and decorators. The transaction manager can be in managed or in auto state. Auto state means the system is using a commit-on-save strategy (actually it's more like commit-on-change). As soon as the .save() or .delete() (or related) methods are called, a commit is made. Managed transactions don't do those commits, but will need some kind of manual or implicit commits or rollbacks. """ import sys try: import thread except ImportError: import dummy_thread as thread try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.4 fallback. from django.conf import settings from django.db import connections, DEFAULT_DB_ALIAS class TransactionManagementError(Exception): """ This exception is thrown when something bad happens with transaction management. """ pass # The states are dictionaries of dictionaries of lists. The key to the outer # dict is the current thread, and the key to the inner dictionary is the # connection alias and the list is handled as a stack of values. state = {} savepoint_state = {} # The dirty flag is set by *_unless_managed functions to denote that the # code under transaction management has changed things to require a # database commit. # This is a dictionary mapping thread to a dictionary mapping connection # alias to a boolean. dirty = {} def enter_transaction_management(managed=True, using=None): """ Enters transaction management for a running thread. It must be balanced with the appropriate leave_transaction_management call, since the actual state is managed as a stack. The state and dirty flag are carried over from the surrounding block or from the settings, if there is no surrounding block (dirty is always false when no current block is running). """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] thread_ident = thread.get_ident() if thread_ident in state and state[thread_ident].get(using): state[thread_ident][using].append(state[thread_ident][using][-1]) else: state.setdefault(thread_ident, {}) state[thread_ident][using] = [settings.TRANSACTIONS_MANAGED] if thread_ident not in dirty or using not in dirty[thread_ident]: dirty.setdefault(thread_ident, {}) dirty[thread_ident][using] = False connection._enter_transaction_management(managed) def leave_transaction_management(using=None): """ Leaves transaction management for a running thread. A dirty flag is carried over to the surrounding block, as a commit will commit all changes, even those from outside. (Commits are on connection level.) """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] connection._leave_transaction_management(is_managed(using=using)) thread_ident = thread.get_ident() if thread_ident in state and state[thread_ident].get(using): del state[thread_ident][using][-1] else: raise TransactionManagementError("This code isn't under transaction management") if dirty.get(thread_ident, {}).get(using, False): rollback(using=using) raise TransactionManagementError("Transaction managed block ended with pending COMMIT/ROLLBACK") dirty[thread_ident][using] = False def is_dirty(using=None): """ Returns True if the current transaction requires a commit for changes to happen. """ if using is None: using = DEFAULT_DB_ALIAS return dirty.get(thread.get_ident(), {}).get(using, False) def set_dirty(using=None): """ Sets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether there are open changes waiting for commit. """ if using is None: using = DEFAULT_DB_ALIAS thread_ident = thread.get_ident() if thread_ident in dirty and using in dirty[thread_ident]: dirty[thread_ident][using] = True else: raise TransactionManagementError("This code isn't under transaction management") def set_clean(using=None): """ Resets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether a commit or rollback should happen. """ if using is None: using = DEFAULT_DB_ALIAS thread_ident = thread.get_ident() if thread_ident in dirty and using in dirty[thread_ident]: dirty[thread_ident][using] = False else: raise TransactionManagementError("This code isn't under transaction management") clean_savepoints(using=using) def clean_savepoints(using=None): if using is None: using = DEFAULT_DB_ALIAS thread_ident = thread.get_ident() if thread_ident in savepoint_state and using in savepoint_state[thread_ident]: del savepoint_state[thread_ident][using] def is_managed(using=None): """ Checks whether the transaction manager is in manual or in auto state. """ if using is None: using = DEFAULT_DB_ALIAS thread_ident = thread.get_ident() if thread_ident in state and using in state[thread_ident]: if state[thread_ident][using]: return state[thread_ident][using][-1] return settings.TRANSACTIONS_MANAGED def managed(flag=True, using=None): """ Puts the transaction manager into a manual state: managed transactions have to be committed explicitly by the user. If you switch off transaction management and there is a pending commit/rollback, the data will be commited. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] thread_ident = thread.get_ident() top = state.get(thread_ident, {}).get(using, None) if top: top[-1] = flag if not flag and is_dirty(using=using): connection._commit() set_clean(using=using) else: raise TransactionManagementError("This code isn't under transaction management") def commit_unless_managed(using=None): """ Commits changes if the system is not in managed transaction mode. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] if not is_managed(using=using): connection._commit() clean_savepoints(using=using) else: set_dirty(using=using) def rollback_unless_managed(using=None): """ Rolls back changes if the system is not in managed transaction mode. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] if not is_managed(using=using): connection._rollback() else: set_dirty(using=using) def commit(using=None): """ Does the commit itself and resets the dirty flag. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] connection._commit() set_clean(using=using) def rollback(using=None): """ This function does the rollback itself and resets the dirty flag. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] connection._rollback() set_clean(using=using) def savepoint(using=None): """ Creates a savepoint (if supported and required by the backend) inside the current transaction. Returns an identifier for the savepoint that will be used for the subsequent rollback or commit. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] thread_ident = thread.get_ident() if thread_ident in savepoint_state and using in savepoint_state[thread_ident]: savepoint_state[thread_ident][using].append(None) else: savepoint_state.setdefault(thread_ident, {}) savepoint_state[thread_ident][using] = [None] tid = str(thread_ident).replace('-', '') sid = "s%s_x%d" % (tid, len(savepoint_state[thread_ident][using])) connection._savepoint(sid) return sid def savepoint_rollback(sid, using=None): """ Rolls back the most recent savepoint (if one exists). Does nothing if savepoints are not supported. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] thread_ident = thread.get_ident() if thread_ident in savepoint_state and using in savepoint_state[thread_ident]: connection._savepoint_rollback(sid) def savepoint_commit(sid, using=None): """ Commits the most recent savepoint (if one exists). Does nothing if savepoints are not supported. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] thread_ident = thread.get_ident() if thread_ident in savepoint_state and using in savepoint_state[thread_ident]: connection._savepoint_commit(sid) ############## # DECORATORS # ############## class Transaction(object): """ Acts as either a decorator, or a context manager. If it's a decorator it takes a function and returns a wrapped function. If it's a contextmanager it's used with the ``with`` statement. In either event entering/exiting are called before and after, respectively, the function/block is executed. autocommit, commit_on_success, and commit_manually contain the implementations of entering and exiting. """ def __init__(self, entering, exiting, using): self.entering = entering self.exiting = exiting self.using = using def __enter__(self): self.entering(self.using) def __exit__(self, exc_type, exc_value, traceback): self.exiting(exc_value, self.using) def __call__(self, func): @wraps(func) def inner(*args, **kwargs): # Once we drop support for Python 2.4 this block should become: # with self: # func(*args, **kwargs) self.__enter__() try: res = func(*args, **kwargs) except: self.__exit__(*sys.exc_info()) raise else: self.__exit__(None, None, None) return res return inner def _transaction_func(entering, exiting, using): """ Takes 3 things, an entering function (what to do to start this block of transaction management), an exiting function (what to do to end it, on both success and failure, and using which can be: None, indiciating using is DEFAULT_DB_ALIAS, a callable, indicating that using is DEFAULT_DB_ALIAS and to return the function already wrapped. Returns either a Transaction objects, which is both a decorator and a context manager, or a wrapped function, if using is a callable. """ # Note that although the first argument is *called* `using`, it # may actually be a function; @autocommit and @autocommit('foo') # are both allowed forms. if using is None: using = DEFAULT_DB_ALIAS if callable(using): return Transaction(entering, exiting, DEFAULT_DB_ALIAS)(using) return Transaction(entering, exiting, using) def autocommit(using=None): """ Decorator that activates commit on save. This is Django's default behavior; this decorator is useful if you globally activated transaction management in your settings file and want the default behavior in some view functions. """ def entering(using): enter_transaction_management(managed=False, using=using) managed(False, using=using) def exiting(exc_value, using): leave_transaction_management(using=using) return _transaction_func(entering, exiting, using) def commit_on_success(using=None): """ This decorator activates commit on response. This way, if the view function runs successfully, a commit is made; if the viewfunc produces an exception, a rollback is made. This is one of the most common ways to do transaction control in Web apps. """ def entering(using): enter_transaction_management(using=using) managed(True, using=using) def exiting(exc_value, using): try: if exc_value is not None: if is_dirty(using=using): rollback(using=using) else: if is_dirty(using=using): try: commit(using=using) except: rollback(using=using) raise finally: leave_transaction_management(using=using) return _transaction_func(entering, exiting, using) def commit_manually(using=None): """ Decorator that activates manual transaction control. It just disables automatic transaction control and doesn't do any commit/rollback of its own -- it's up to the user to call the commit and rollback functions themselves. """ def entering(using): enter_transaction_management(using=using) managed(True, using=using) def exiting(exc_value, using): leave_transaction_management(using=using) return _transaction_func(entering, exiting, using)
[ [ 8, 0, 0.0185, 0.0344, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.037, 0.0026, 0, 0.66, 0.0345, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 7, 0, 0.0463, 0.0106, 0, 0.66,...
[ "\"\"\"\nThis module implements a transaction manager that can be used to define\ntransaction handling in a request or view function. It is used by transaction\ncontrol middleware and decorators.\n\nThe transaction manager can be in managed or in auto state. Auto state means the\nsystem is using a commit-on-save st...
from django.db.backends.postgresql.introspection import DatabaseIntrospection as PostgresDatabaseIntrospection class DatabaseIntrospection(PostgresDatabaseIntrospection): def get_relations(self, cursor, table_name): """ Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based. """ cursor.execute(""" SELECT con.conkey, con.confkey, c2.relname FROM pg_constraint con, pg_class c1, pg_class c2 WHERE c1.oid = con.conrelid AND c2.oid = con.confrelid AND c1.relname = %s AND con.contype = 'f'""", [table_name]) relations = {} for row in cursor.fetchall(): # row[0] and row[1] are single-item lists, so grab the single item. relations[row[0][0] - 1] = (row[1][0] - 1, row[2]) return relations
[ [ 1, 0, 0.0476, 0.0476, 0, 0.66, 0, 789, 0, 1, 0, 0, 789, 0, 0 ], [ 3, 0, 0.5714, 0.9048, 0, 0.66, 1, 77, 0, 1, 0, 0, 531, 0, 2 ], [ 2, 1, 0.619, 0.8095, 1, 0.21, ...
[ "from django.db.backends.postgresql.introspection import DatabaseIntrospection as PostgresDatabaseIntrospection", "class DatabaseIntrospection(PostgresDatabaseIntrospection):\n\n def get_relations(self, cursor, table_name):\n \"\"\"\n Returns a dictionary of {field_index: (field_index_other_table...
from django.db.backends import BaseDatabaseIntrospection from MySQLdb import ProgrammingError, OperationalError from MySQLdb.constants import FIELD_TYPE import re foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)") class DatabaseIntrospection(BaseDatabaseIntrospection): data_types_reverse = { FIELD_TYPE.BLOB: 'TextField', FIELD_TYPE.CHAR: 'CharField', FIELD_TYPE.DECIMAL: 'DecimalField', FIELD_TYPE.NEWDECIMAL: 'DecimalField', FIELD_TYPE.DATE: 'DateField', FIELD_TYPE.DATETIME: 'DateTimeField', FIELD_TYPE.DOUBLE: 'FloatField', FIELD_TYPE.FLOAT: 'FloatField', FIELD_TYPE.INT24: 'IntegerField', FIELD_TYPE.LONG: 'IntegerField', FIELD_TYPE.LONGLONG: 'BigIntegerField', FIELD_TYPE.SHORT: 'IntegerField', FIELD_TYPE.STRING: 'CharField', FIELD_TYPE.TIMESTAMP: 'DateTimeField', FIELD_TYPE.TINY: 'IntegerField', FIELD_TYPE.TINY_BLOB: 'TextField', FIELD_TYPE.MEDIUM_BLOB: 'TextField', FIELD_TYPE.LONG_BLOB: 'TextField', FIELD_TYPE.VAR_STRING: 'CharField', } def get_table_list(self, cursor): "Returns a list of table names in the current database." cursor.execute("SHOW TABLES") return [row[0] for row in cursor.fetchall()] def get_table_description(self, cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name)) return cursor.description def _name_to_index(self, cursor, table_name): """ Returns a dictionary of {field_name: field_index} for the given table. Indexes are 0-based. """ return dict([(d[0], i) for i, d in enumerate(self.get_table_description(cursor, table_name))]) def get_relations(self, cursor, table_name): """ Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based. """ my_field_dict = self._name_to_index(cursor, table_name) constraints = [] relations = {} try: # This should work for MySQL 5.0. cursor.execute(""" SELECT column_name, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE table_name = %s AND table_schema = DATABASE() AND referenced_table_name IS NOT NULL AND referenced_column_name IS NOT NULL""", [table_name]) constraints.extend(cursor.fetchall()) except (ProgrammingError, OperationalError): # Fall back to "SHOW CREATE TABLE", for previous MySQL versions. # Go through all constraints and save the equal matches. cursor.execute("SHOW CREATE TABLE %s" % self.connection.ops.quote_name(table_name)) for row in cursor.fetchall(): pos = 0 while True: match = foreign_key_re.search(row[1], pos) if match == None: break pos = match.end() constraints.append(match.groups()) for my_fieldname, other_table, other_field in constraints: other_field_index = self._name_to_index(cursor, other_table)[other_field] my_field_index = my_field_dict[my_fieldname] relations[my_field_index] = (other_field_index, other_table) return relations def get_indexes(self, cursor, table_name): """ Returns a dictionary of fieldname -> infodict for the given table, where each infodict is in the format: {'primary_key': boolean representing whether it's the primary key, 'unique': boolean representing whether it's a unique index} """ cursor.execute("SHOW INDEX FROM %s" % self.connection.ops.quote_name(table_name)) indexes = {} for row in cursor.fetchall(): indexes[row[4]] = {'primary_key': (row[2] == 'PRIMARY'), 'unique': not bool(row[1])} return indexes
[ [ 1, 0, 0.0102, 0.0102, 0, 0.66, 0, 981, 0, 1, 0, 0, 981, 0, 0 ], [ 1, 0, 0.0204, 0.0102, 0, 0.66, 0.2, 838, 0, 2, 0, 0, 838, 0, 0 ], [ 1, 0, 0.0306, 0.0102, 0, 0.6...
[ "from django.db.backends import BaseDatabaseIntrospection", "from MySQLdb import ProgrammingError, OperationalError", "from MySQLdb.constants import FIELD_TYPE", "import re", "foreign_key_re = re.compile(r\"\\sCONSTRAINT `[^`]*` FOREIGN KEY \\(`([^`]*)`\\) REFERENCES `([^`]*)` \\(`([^`]*)`\\)\")", "class ...