id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
3,800
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/pt/forms.py
""" PT-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re phone_digits_re = re.compile(r'^(\d{9}|(00|\+)\d*)$') class PTZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXX-XXX.'), } def __init__(self, *args, **kwargs): super(PTZipCodeField, self).__init__(r'^(\d{4}-\d{3}|\d{7})$', max_length=None, min_length=None, *args, **kwargs) def clean(self,value): cleaned = super(PTZipCodeField, self).clean(value) if len(cleaned) == 7: return u'%s-%s' % (cleaned[:4],cleaned[4:]) else: return cleaned class PTPhoneNumberField(Field): """ Validate local Portuguese phone number (including international ones) It should have 9 digits (may include spaces) or start by 00 or + (international) """ default_error_messages = { 'invalid': _('Phone numbers must have 9 digits, or start by + or 00.'), } def clean(self, value): super(PTPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\.|\s)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: return u'%s' % value raise ValidationError(self.error_messages['invalid'])
1,561
Python
.py
40
32.675
84
0.643854
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,801
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/kw/forms.py
""" Kuwait-specific Form helpers """ import re from datetime import date from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField from django.utils.translation import gettext as _ id_re = re.compile(r'^(?P<initial>\d{1})(?P<yy>\d\d)(?P<mm>\d\d)(?P<dd>\d\d)(?P<mid>\d{4})(?P<checksum>\d{1})') class KWCivilIDNumberField(Field): """ Kuwaiti Civil ID numbers are 12 digits, second to seventh digits represents the person's birthdate. Checks the following rules to determine the validty of the number: * The number consist of 12 digits. * The birthdate of the person is a valid date. * The calculated checksum equals to the last digit of the Civil ID. """ default_error_messages = { 'invalid': _('Enter a valid Kuwaiti Civil ID number'), } def has_valid_checksum(self, value): weight = (2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2) calculated_checksum = 0 for i in range(11): calculated_checksum += int(value[i]) * weight[i] remainder = calculated_checksum % 11 checkdigit = 11 - remainder if checkdigit != int(value[11]): return False return True def clean(self, value): super(KWCivilIDNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' if not re.match(r'^\d{12}$', value): raise ValidationError(self.error_messages['invalid']) match = re.match(id_re, value) if not match: raise ValidationError(self.error_messages['invalid']) gd = match.groupdict() try: d = date(int(gd['yy']), int(gd['mm']), int(gd['dd'])) except ValueError: raise ValidationError(self.error_messages['invalid']) if not self.has_valid_checksum(value): raise ValidationError(self.error_messages['invalid']) return value
1,988
Python
.py
49
33.163265
111
0.637922
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,802
ie_counties.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/ie/ie_counties.py
""" Sources: Irish Counties: http://en.wikipedia.org/wiki/Counties_of_Ireland """ from django.utils.translation import ugettext_lazy as _ IE_COUNTY_CHOICES = ( ('antrim', _('Antrim')), ('armagh', _('Armagh')), ('carlow', _('Carlow')), ('cavan', _('Cavan')), ('clare', _('Clare')), ('cork', _('Cork')), ('derry', _('Derry')), ('donegal', _('Donegal')), ('down', _('Down')), ('dublin', _('Dublin')), ('fermanagh', _('Fermanagh')), ('galway', _('Galway')), ('kerry', _('Kerry')), ('kildare', _('Kildare')), ('kilkenny', _('Kilkenny')), ('laois', _('Laois')), ('leitrim', _('Leitrim')), ('limerick', _('Limerick')), ('longford', _('Longford')), ('louth', _('Louth')), ('mayo', _('Mayo')), ('meath', _('Meath')), ('monaghan', _('Monaghan')), ('offaly', _('Offaly')), ('roscommon', _('Roscommon')), ('sligo', _('Sligo')), ('tipperary', _('Tipperary')), ('tyrone', _('Tyrone')), ('waterford', _('Waterford')), ('westmeath', _('Westmeath')), ('wexford', _('Wexford')), ('wicklow', _('Wicklow')), )
1,127
Python
.py
39
24.384615
72
0.48942
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,803
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/ie/forms.py
""" UK-specific Form helpers """ from django.forms.fields import Select class IECountySelect(Select): """ A Select widget that uses a list of Irish Counties as its choices. """ def __init__(self, attrs=None): from ie_counties import IE_COUNTY_CHOICES super(IECountySelect, self).__init__(attrs, choices=IE_COUNTY_CHOICES)
356
Python
.py
11
28.272727
78
0.702624
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,804
at_states.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/at/at_states.py
# -*- coding: utf-8 -* from django.utils.translation import ugettext_lazy as _ STATE_CHOICES = ( ('BL', _('Burgenland')), ('KA', _('Carinthia')), ('NO', _('Lower Austria')), ('OO', _('Upper Austria')), ('SA', _('Salzburg')), ('ST', _('Styria')), ('TI', _('Tyrol')), ('VO', _('Vorarlberg')), ('WI', _('Vienna')), )
350
Python
.py
13
23.153846
55
0.486647
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,805
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/at/forms.py
""" AT-specific Form helpers """ import re from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ re_ssn = re.compile(r'^\d{4} \d{6}') class ATZipCodeField(RegexField): """ A form field that validates its input is an Austrian postcode. Accepts 4 digits. """ default_error_messages = { 'invalid': _('Enter a zip code in the format XXXX.'), } def __init__(self, *args, **kwargs): super(ATZipCodeField, self).__init__(r'^\d{4}$', max_length=None, min_length=None, *args, **kwargs) class ATStateSelect(Select): """ A Select widget that uses a list of AT states as its choices. """ def __init__(self, attrs=None): from django.contrib.localflavor.at.at_states import STATE_CHOICES super(ATStateSelect, self).__init__(attrs, choices=STATE_CHOICES) class ATSocialSecurityNumberField(Field): """ Austrian Social Security numbers are composed of a 4 digits and 6 digits field. The latter represents in most cases the person's birthdate while the first 4 digits represent a 3-digits counter and a one-digit checksum. The 6-digits field can also differ from the person's birthdate if the 3-digits counter suffered an overflow. This code is based on information available on http://de.wikipedia.org/wiki/Sozialversicherungsnummer#.C3.96sterreich """ default_error_messages = { 'invalid': _(u'Enter a valid Austrian Social Security Number in XXXX XXXXXX format.'), } def clean(self, value): value = super(ATSocialSecurityNumberField, self).clean(value) if value in EMPTY_VALUES: return u"" if not re_ssn.search(value): raise ValidationError(self.error_messages['invalid']) sqnr, date = value.split(" ") sqnr, check = (sqnr[:3], (sqnr[3])) if int(sqnr) < 100: raise ValidationError(self.error_messages['invalid']) res = int(sqnr[0])*3 + int(sqnr[1])*7 + int(sqnr[2])*9 \ + int(date[0])*5 + int(date[1])*8 + int(date[2])*4 \ + int(date[3])*2 + int(date[4])*1 + int(date[5])*6 res = res % 11 if res != int(check): raise ValidationError(self.error_messages['invalid']) return u'%s%s %s'%(sqnr, check, date,)
2,446
Python
.py
57
36.508772
94
0.658393
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,806
jp_prefectures.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/jp/jp_prefectures.py
from django.utils.translation import ugettext_lazy JP_PREFECTURES = ( ('hokkaido', ugettext_lazy('Hokkaido'),), ('aomori', ugettext_lazy('Aomori'),), ('iwate', ugettext_lazy('Iwate'),), ('miyagi', ugettext_lazy('Miyagi'),), ('akita', ugettext_lazy('Akita'),), ('yamagata', ugettext_lazy('Yamagata'),), ('fukushima', ugettext_lazy('Fukushima'),), ('ibaraki', ugettext_lazy('Ibaraki'),), ('tochigi', ugettext_lazy('Tochigi'),), ('gunma', ugettext_lazy('Gunma'),), ('saitama', ugettext_lazy('Saitama'),), ('chiba', ugettext_lazy('Chiba'),), ('tokyo', ugettext_lazy('Tokyo'),), ('kanagawa', ugettext_lazy('Kanagawa'),), ('yamanashi', ugettext_lazy('Yamanashi'),), ('nagano', ugettext_lazy('Nagano'),), ('niigata', ugettext_lazy('Niigata'),), ('toyama', ugettext_lazy('Toyama'),), ('ishikawa', ugettext_lazy('Ishikawa'),), ('fukui', ugettext_lazy('Fukui'),), ('gifu', ugettext_lazy('Gifu'),), ('shizuoka', ugettext_lazy('Shizuoka'),), ('aichi', ugettext_lazy('Aichi'),), ('mie', ugettext_lazy('Mie'),), ('shiga', ugettext_lazy('Shiga'),), ('kyoto', ugettext_lazy('Kyoto'),), ('osaka', ugettext_lazy('Osaka'),), ('hyogo', ugettext_lazy('Hyogo'),), ('nara', ugettext_lazy('Nara'),), ('wakayama', ugettext_lazy('Wakayama'),), ('tottori', ugettext_lazy('Tottori'),), ('shimane', ugettext_lazy('Shimane'),), ('okayama', ugettext_lazy('Okayama'),), ('hiroshima', ugettext_lazy('Hiroshima'),), ('yamaguchi', ugettext_lazy('Yamaguchi'),), ('tokushima', ugettext_lazy('Tokushima'),), ('kagawa', ugettext_lazy('Kagawa'),), ('ehime', ugettext_lazy('Ehime'),), ('kochi', ugettext_lazy('Kochi'),), ('fukuoka', ugettext_lazy('Fukuoka'),), ('saga', ugettext_lazy('Saga'),), ('nagasaki', ugettext_lazy('Nagasaki'),), ('kumamoto', ugettext_lazy('Kumamoto'),), ('oita', ugettext_lazy('Oita'),), ('miyazaki', ugettext_lazy('Miyazaki'),), ('kagoshima', ugettext_lazy('Kagoshima'),), ('okinawa', ugettext_lazy('Okinawa'),), )
2,089
Python
.py
50
37
50
0.602061
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,807
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/jp/forms.py
""" JP-specific Form helpers """ from django.forms import ValidationError from django.utils.translation import ugettext_lazy as _ from django.forms.fields import RegexField, Select class JPPostalCodeField(RegexField): """ A form field that validates its input is a Japanese postcode. Accepts 7 digits, with or without a hyphen. """ default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), } def __init__(self, *args, **kwargs): super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$', max_length=None, min_length=None, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(JPPostalCodeField, self).clean(value) return v.replace('-', '') class JPPrefectureSelect(Select): """ A Select widget that uses a list of Japanese prefectures as its choices. """ def __init__(self, attrs=None): from jp_prefectures import JP_PREFECTURES super(JPPrefectureSelect, self).__init__(attrs, choices=JP_PREFECTURES)
1,211
Python
.py
31
33.354839
79
0.668654
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,808
is_postalcodes.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/is_/is_postalcodes.py
# -*- coding: utf-8 -*- IS_POSTALCODES = ( ('101', u'101 Reykjavík'), ('103', u'103 Reykjavík'), ('104', u'104 Reykjavík'), ('105', u'105 Reykjavík'), ('107', u'107 Reykjavík'), ('108', u'108 Reykjavík'), ('109', u'109 Reykjavík'), ('110', u'110 Reykjavík'), ('111', u'111 Reykjavík'), ('112', u'112 Reykjavík'), ('113', u'113 Reykjavík'), ('116', u'116 Kjalarnes'), ('121', u'121 Reykjavík'), ('123', u'123 Reykjavík'), ('124', u'124 Reykjavík'), ('125', u'125 Reykjavík'), ('127', u'127 Reykjavík'), ('128', u'128 Reykjavík'), ('129', u'129 Reykjavík'), ('130', u'130 Reykjavík'), ('132', u'132 Reykjavík'), ('150', u'150 Reykjavík'), ('155', u'155 Reykjavík'), ('170', u'170 Seltjarnarnes'), ('172', u'172 Seltjarnarnes'), ('190', u'190 Vogar'), ('200', u'200 Kópavogur'), ('201', u'201 Kópavogur'), ('202', u'202 Kópavogur'), ('203', u'203 Kópavogur'), ('210', u'210 Garðabær'), ('212', u'212 Garðabær'), ('220', u'220 Hafnarfjörður'), ('221', u'221 Hafnarfjörður'), ('222', u'222 Hafnarfjörður'), ('225', u'225 Álftanes'), ('230', u'230 Reykjanesbær'), ('232', u'232 Reykjanesbær'), ('233', u'233 Reykjanesbær'), ('235', u'235 Keflavíkurflugvöllur'), ('240', u'240 Grindavík'), ('245', u'245 Sandgerði'), ('250', u'250 Garður'), ('260', u'260 Reykjanesbær'), ('270', u'270 Mosfellsbær'), ('300', u'300 Akranes'), ('301', u'301 Akranes'), ('302', u'302 Akranes'), ('310', u'310 Borgarnes'), ('311', u'311 Borgarnes'), ('320', u'320 Reykholt í Borgarfirði'), ('340', u'340 Stykkishólmur'), ('345', u'345 Flatey á Breiðafirði'), ('350', u'350 Grundarfjörður'), ('355', u'355 Ólafsvík'), ('356', u'356 Snæfellsbær'), ('360', u'360 Hellissandur'), ('370', u'370 Búðardalur'), ('371', u'371 Búðardalur'), ('380', u'380 Reykhólahreppur'), ('400', u'400 Ísafjörður'), ('401', u'401 Ísafjörður'), ('410', u'410 Hnífsdalur'), ('415', u'415 Bolungarvík'), ('420', u'420 Súðavík'), ('425', u'425 Flateyri'), ('430', u'430 Suðureyri'), ('450', u'450 Patreksfjörður'), ('451', u'451 Patreksfjörður'), ('460', u'460 Tálknafjörður'), ('465', u'465 Bíldudalur'), ('470', u'470 Þingeyri'), ('471', u'471 Þingeyri'), ('500', u'500 Staður'), ('510', u'510 Hólmavík'), ('512', u'512 Hólmavík'), ('520', u'520 Drangsnes'), ('522', u'522 Kjörvogur'), ('523', u'523 Bær'), ('524', u'524 Norðurfjörður'), ('530', u'530 Hvammstangi'), ('531', u'531 Hvammstangi'), ('540', u'540 Blönduós'), ('541', u'541 Blönduós'), ('545', u'545 Skagaströnd'), ('550', u'550 Sauðárkrókur'), ('551', u'551 Sauðárkrókur'), ('560', u'560 Varmahlíð'), ('565', u'565 Hofsós'), ('566', u'566 Hofsós'), ('570', u'570 Fljót'), ('580', u'580 Siglufjörður'), ('600', u'600 Akureyri'), ('601', u'601 Akureyri'), ('602', u'602 Akureyri'), ('603', u'603 Akureyri'), ('610', u'610 Grenivík'), ('611', u'611 Grímsey'), ('620', u'620 Dalvík'), ('621', u'621 Dalvík'), ('625', u'625 Ólafsfjörður'), ('630', u'630 Hrísey'), ('640', u'640 Húsavík'), ('641', u'641 Húsavík'), ('645', u'645 Fosshóll'), ('650', u'650 Laugar'), ('660', u'660 Mývatn'), ('670', u'670 Kópasker'), ('671', u'671 Kópasker'), ('675', u'675 Raufarhöfn'), ('680', u'680 Þórshöfn'), ('681', u'681 Þórshöfn'), ('685', u'685 Bakkafjörður'), ('690', u'690 Vopnafjörður'), ('700', u'700 Egilsstaðir'), ('701', u'701 Egilsstaðir'), ('710', u'710 Seyðisfjörður'), ('715', u'715 Mjóifjörður'), ('720', u'720 Borgarfjörður eystri'), ('730', u'730 Reyðarfjörður'), ('735', u'735 Eskifjörður'), ('740', u'740 Neskaupstaður'), ('750', u'750 Fáskrúðsfjörður'), ('755', u'755 Stöðvarfjörður'), ('760', u'760 Breiðdalsvík'), ('765', u'765 Djúpivogur'), ('780', u'780 Höfn í Hornafirði'), ('781', u'781 Höfn í Hornafirði'), ('785', u'785 Öræfi'), ('800', u'800 Selfoss'), ('801', u'801 Selfoss'), ('802', u'802 Selfoss'), ('810', u'810 Hveragerði'), ('815', u'815 Þorlákshöfn'), ('820', u'820 Eyrarbakki'), ('825', u'825 Stokkseyri'), ('840', u'840 Laugarvatn'), ('845', u'845 Flúðir'), ('850', u'850 Hella'), ('851', u'851 Hella'), ('860', u'860 Hvolsvöllur'), ('861', u'861 Hvolsvöllur'), ('870', u'870 Vík'), ('871', u'871 Vík'), ('880', u'880 Kirkjubæjarklaustur'), ('900', u'900 Vestmannaeyjar'), ('902', u'902 Vestmannaeyjar') )
4,913
Python
.py
150
26.573333
43
0.544163
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,809
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/is_/forms.py
""" Iceland specific form helpers. """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import RegexField from django.forms.widgets import Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode class ISIdNumberField(RegexField): """ Icelandic identification number (kennitala). This is a number every citizen of Iceland has. """ default_error_messages = { 'invalid': _('Enter a valid Icelandic identification number. The format is XXXXXX-XXXX.'), 'checksum': _(u'The Icelandic identification number is not valid.'), } def __init__(self, *args, **kwargs): kwargs['min_length'],kwargs['max_length'] = 10,11 super(ISIdNumberField, self).__init__(r'^\d{6}(-| )?\d{4}$', *args, **kwargs) def clean(self, value): value = super(ISIdNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = self._canonify(value) if self._validate(value): return self._format(value) else: raise ValidationError(self.error_messages['checksum']) def _canonify(self, value): """ Returns the value as only digits. """ return value.replace('-', '').replace(' ', '') def _validate(self, value): """ Takes in the value in canonical form and checks the verifier digit. The method is modulo 11. """ check = [3, 2, 7, 6, 5, 4, 3, 2, 1, 0] return sum([int(value[i]) * check[i] for i in range(10)]) % 11 == 0 def _format(self, value): """ Takes in the value in canonical form and returns it in the common display format. """ return smart_unicode(value[:6]+'-'+value[6:]) class ISPhoneNumberField(RegexField): """ Icelandic phone number. Seven digits with an optional hyphen or space after the first three digits. """ def __init__(self, *args, **kwargs): kwargs['min_length'], kwargs['max_length'] = 7,8 super(ISPhoneNumberField, self).__init__(r'^\d{3}(-| )?\d{4}$', *args, **kwargs) def clean(self, value): value = super(ISPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' return value.replace('-', '').replace(' ', '') class ISPostalCodeSelect(Select): """ A Select widget that uses a list of Icelandic postal codes as its choices. """ def __init__(self, attrs=None): from is_postalcodes import IS_POSTALCODES super(ISPostalCodeSelect, self).__init__(attrs, choices=IS_POSTALCODES)
2,706
Python
.py
68
32.985294
98
0.632101
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,810
id_choices.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/id/id_choices.py
from django.utils.translation import ugettext_lazy as _ # Reference: http://id.wikipedia.org/wiki/Daftar_provinsi_Indonesia # Indonesia does not have an official Province code standard. # I decided to use unambiguous and consistent (some are common) 3-letter codes. PROVINCE_CHOICES = ( ('BLI', _('Bali')), ('BTN', _('Banten')), ('BKL', _('Bengkulu')), ('DIY', _('Yogyakarta')), ('JKT', _('Jakarta')), ('GOR', _('Gorontalo')), ('JMB', _('Jambi')), ('JBR', _('Jawa Barat')), ('JTG', _('Jawa Tengah')), ('JTM', _('Jawa Timur')), ('KBR', _('Kalimantan Barat')), ('KSL', _('Kalimantan Selatan')), ('KTG', _('Kalimantan Tengah')), ('KTM', _('Kalimantan Timur')), ('BBL', _('Kepulauan Bangka-Belitung')), ('KRI', _('Kepulauan Riau')), ('LPG', _('Lampung')), ('MLK', _('Maluku')), ('MUT', _('Maluku Utara')), ('NAD', _('Nanggroe Aceh Darussalam')), ('NTB', _('Nusa Tenggara Barat')), ('NTT', _('Nusa Tenggara Timur')), ('PPA', _('Papua')), ('PPB', _('Papua Barat')), ('RIU', _('Riau')), ('SLB', _('Sulawesi Barat')), ('SLS', _('Sulawesi Selatan')), ('SLT', _('Sulawesi Tengah')), ('SLR', _('Sulawesi Tenggara')), ('SLU', _('Sulawesi Utara')), ('SMB', _('Sumatera Barat')), ('SMS', _('Sumatera Selatan')), ('SMU', _('Sumatera Utara')), ) LICENSE_PLATE_PREFIX_CHOICES = ( ('A', _('Banten')), ('AA', _('Magelang')), ('AB', _('Yogyakarta')), ('AD', _('Surakarta - Solo')), ('AE', _('Madiun')), ('AG', _('Kediri')), ('B', _('Jakarta')), ('BA', _('Sumatera Barat')), ('BB', _('Tapanuli')), ('BD', _('Bengkulu')), ('BE', _('Lampung')), ('BG', _('Sumatera Selatan')), ('BH', _('Jambi')), ('BK', _('Sumatera Utara')), ('BL', _('Nanggroe Aceh Darussalam')), ('BM', _('Riau')), ('BN', _('Kepulauan Bangka Belitung')), ('BP', _('Kepulauan Riau')), ('CC', _('Corps Consulate')), ('CD', _('Corps Diplomatic')), ('D', _('Bandung')), ('DA', _('Kalimantan Selatan')), ('DB', _('Sulawesi Utara Daratan')), ('DC', _('Sulawesi Barat')), ('DD', _('Sulawesi Selatan')), ('DE', _('Maluku')), ('DG', _('Maluku Utara')), ('DH', _('NTT - Timor')), ('DK', _('Bali')), ('DL', _('Sulawesi Utara Kepulauan')), ('DM', _('Gorontalo')), ('DN', _('Sulawesi Tengah')), ('DR', _('NTB - Lombok')), ('DS', _('Papua dan Papua Barat')), ('DT', _('Sulawesi Tenggara')), ('E', _('Cirebon')), ('EA', _('NTB - Sumbawa')), ('EB', _('NTT - Flores')), ('ED', _('NTT - Sumba')), ('F', _('Bogor')), ('G', _('Pekalongan')), ('H', _('Semarang')), ('K', _('Pati')), ('KB', _('Kalimantan Barat')), ('KH', _('Kalimantan Tengah')), ('KT', _('Kalimantan Timur')), ('L', _('Surabaya')), ('M', _('Madura')), ('N', _('Malang')), ('P', _('Jember')), ('R', _('Banyumas')), ('RI', _('Federal Government')), ('S', _('Bojonegoro')), ('T', _('Purwakarta')), ('W', _('Sidoarjo')), ('Z', _('Garut')), )
3,089
Python
.py
97
27.134021
79
0.478246
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,811
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/id/forms.py
""" ID-specific Form helpers """ import re import time from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode postcode_re = re.compile(r'^[1-9]\d{4}$') phone_re = re.compile(r'^(\+62|0)[2-9]\d{7,10}$') plate_re = re.compile(r'^(?P<prefix>[A-Z]{1,2}) ' + \ r'(?P<number>\d{1,5})( (?P<suffix>([A-Z]{1,3}|[1-9][0-9]{,2})))?$') nik_re = re.compile(r'^\d{16}$') class IDPostCodeField(Field): """ An Indonesian post code field. http://id.wikipedia.org/wiki/Kode_pos """ default_error_messages = { 'invalid': _('Enter a valid post code'), } def clean(self, value): super(IDPostCodeField, self).clean(value) if value in EMPTY_VALUES: return u'' value = value.strip() if not postcode_re.search(value): raise ValidationError(self.error_messages['invalid']) if int(value) < 10110: raise ValidationError(self.error_messages['invalid']) # 1xxx0 if value[0] == '1' and value[4] != '0': raise ValidationError(self.error_messages['invalid']) return u'%s' % (value, ) class IDProvinceSelect(Select): """ A Select widget that uses a list of provinces of Indonesia as its choices. """ def __init__(self, attrs=None): from id_choices import PROVINCE_CHOICES super(IDProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES) class IDPhoneNumberField(Field): """ An Indonesian telephone number field. http://id.wikipedia.org/wiki/Daftar_kode_telepon_di_Indonesia """ default_error_messages = { 'invalid': _('Enter a valid phone number'), } def clean(self, value): super(IDPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' phone_number = re.sub(r'[\-\s\(\)]', '', smart_unicode(value)) if phone_re.search(phone_number): return smart_unicode(value) raise ValidationError(self.error_messages['invalid']) class IDLicensePlatePrefixSelect(Select): """ A Select widget that uses a list of vehicle license plate prefix code of Indonesia as its choices. http://id.wikipedia.org/wiki/Tanda_Nomor_Kendaraan_Bermotor """ def __init__(self, attrs=None): from id_choices import LICENSE_PLATE_PREFIX_CHOICES super(IDLicensePlatePrefixSelect, self).__init__(attrs, choices=LICENSE_PLATE_PREFIX_CHOICES) class IDLicensePlateField(Field): """ An Indonesian vehicle license plate field. http://id.wikipedia.org/wiki/Tanda_Nomor_Kendaraan_Bermotor Plus: "B 12345 12" """ default_error_messages = { 'invalid': _('Enter a valid vehicle license plate number'), } def clean(self, value): super(IDLicensePlateField, self).clean(value) if value in EMPTY_VALUES: return u'' plate_number = re.sub(r'\s+', ' ', smart_unicode(value.strip())).upper() matches = plate_re.search(plate_number) if matches is None: raise ValidationError(self.error_messages['invalid']) # Make sure prefix is in the list of known codes. from id_choices import LICENSE_PLATE_PREFIX_CHOICES prefix = matches.group('prefix') if prefix not in [choice[0] for choice in LICENSE_PLATE_PREFIX_CHOICES]: raise ValidationError(self.error_messages['invalid']) # Only Jakarta (prefix B) can have 3 letter suffix. suffix = matches.group('suffix') if suffix is not None and len(suffix) == 3 and prefix != 'B': raise ValidationError(self.error_messages['invalid']) # RI plates don't have suffix. if prefix == 'RI' and suffix is not None and suffix != '': raise ValidationError(self.error_messages['invalid']) # Number can't be zero. number = matches.group('number') if number == '0': raise ValidationError(self.error_messages['invalid']) # CD, CC and B 12345 12 if len(number) == 5 or prefix in ('CD', 'CC'): # suffix must be numeric and non-empty if re.match(r'^\d+$', suffix) is None: raise ValidationError(self.error_messages['invalid']) # Known codes range is 12-124 if prefix in ('CD', 'CC') and not (12 <= int(number) <= 124): raise ValidationError(self.error_messages['invalid']) if len(number) == 5 and not (12 <= int(suffix) <= 124): raise ValidationError(self.error_messages['invalid']) else: # suffix must be non-numeric if suffix is not None and re.match(r'^[A-Z]{,3}$', suffix) is None: raise ValidationError(self.error_messages['invalid']) return plate_number class IDNationalIdentityNumberField(Field): """ An Indonesian national identity number (NIK/KTP#) field. http://id.wikipedia.org/wiki/Nomor_Induk_Kependudukan xx.xxxx.ddmmyy.xxxx - 16 digits (excl. dots) """ default_error_messages = { 'invalid': _('Enter a valid NIK/KTP number'), } def clean(self, value): super(IDNationalIdentityNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub(r'[\s.]', '', smart_unicode(value)) if not nik_re.search(value): raise ValidationError(self.error_messages['invalid']) if int(value) == 0: raise ValidationError(self.error_messages['invalid']) def valid_nik_date(year, month, day): try: t1 = (int(year), int(month), int(day), 0, 0, 0, 0, 0, -1) d = time.mktime(t1) t2 = time.localtime(d) if t1[:3] != t2[:3]: return False else: return True except (OverflowError, ValueError): return False year = int(value[10:12]) month = int(value[8:10]) day = int(value[6:8]) current_year = time.localtime().tm_year if year < int(str(current_year)[-2:]): if not valid_nik_date(2000 + int(year), month, day): raise ValidationError(self.error_messages['invalid']) elif not valid_nik_date(1900 + int(year), month, day): raise ValidationError(self.error_messages['invalid']) if value[:6] == '000000' or value[12:] == '0000': raise ValidationError(self.error_messages['invalid']) return '%s.%s.%s.%s' % (value[:2], value[2:6], value[6:12], value[12:])
6,834
Python
.py
160
33.96875
80
0.610297
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,812
uk_regions.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/uk/uk_regions.py
""" Sources: English regions: http://www.statistics.gov.uk/geography/downloads/31_10_01_REGION_names_and_codes_12_00.xls Northern Ireland regions: http://en.wikipedia.org/wiki/List_of_Irish_counties_by_area Welsh regions: http://en.wikipedia.org/wiki/Preserved_counties_of_Wales Scottish regions: http://en.wikipedia.org/wiki/Regions_and_districts_of_Scotland """ from django.utils.translation import ugettext_lazy as _ ENGLAND_REGION_CHOICES = ( ("Bedfordshire", _("Bedfordshire")), ("Buckinghamshire", _("Buckinghamshire")), ("Cambridgeshire", ("Cambridgeshire")), ("Cheshire", _("Cheshire")), ("Cornwall and Isles of Scilly", _("Cornwall and Isles of Scilly")), ("Cumbria", _("Cumbria")), ("Derbyshire", _("Derbyshire")), ("Devon", _("Devon")), ("Dorset", _("Dorset")), ("Durham", _("Durham")), ("East Sussex", _("East Sussex")), ("Essex", _("Essex")), ("Gloucestershire", _("Gloucestershire")), ("Greater London", _("Greater London")), ("Greater Manchester", _("Greater Manchester")), ("Hampshire", _("Hampshire")), ("Hertfordshire", _("Hertfordshire")), ("Kent", _("Kent")), ("Lancashire", _("Lancashire")), ("Leicestershire", _("Leicestershire")), ("Lincolnshire", _("Lincolnshire")), ("Merseyside", _("Merseyside")), ("Norfolk", _("Norfolk")), ("North Yorkshire", _("North Yorkshire")), ("Northamptonshire", _("Northamptonshire")), ("Northumberland", _("Northumberland")), ("Nottinghamshire", _("Nottinghamshire")), ("Oxfordshire", _("Oxfordshire")), ("Shropshire", _("Shropshire")), ("Somerset", _("Somerset")), ("South Yorkshire", _("South Yorkshire")), ("Staffordshire", _("Staffordshire")), ("Suffolk", _("Suffolk")), ("Surrey", _("Surrey")), ("Tyne and Wear", _("Tyne and Wear")), ("Warwickshire", _("Warwickshire")), ("West Midlands", _("West Midlands")), ("West Sussex", _("West Sussex")), ("West Yorkshire", _("West Yorkshire")), ("Wiltshire", _("Wiltshire")), ("Worcestershire", _("Worcestershire")), ) NORTHERN_IRELAND_REGION_CHOICES = ( ("County Antrim", _("County Antrim")), ("County Armagh", _("County Armagh")), ("County Down", _("County Down")), ("County Fermanagh", _("County Fermanagh")), ("County Londonderry", _("County Londonderry")), ("County Tyrone", _("County Tyrone")), ) WALES_REGION_CHOICES = ( ("Clwyd", _("Clwyd")), ("Dyfed", _("Dyfed")), ("Gwent", _("Gwent")), ("Gwynedd", _("Gwynedd")), ("Mid Glamorgan", _("Mid Glamorgan")), ("Powys", _("Powys")), ("South Glamorgan", _("South Glamorgan")), ("West Glamorgan", _("West Glamorgan")), ) SCOTTISH_REGION_CHOICES = ( ("Borders", _("Borders")), ("Central Scotland", _("Central Scotland")), ("Dumfries and Galloway", _("Dumfries and Galloway")), ("Fife", _("Fife")), ("Grampian", _("Grampian")), ("Highland", _("Highland")), ("Lothian", _("Lothian")), ("Orkney Islands", _("Orkney Islands")), ("Shetland Islands", _("Shetland Islands")), ("Strathclyde", _("Strathclyde")), ("Tayside", _("Tayside")), ("Western Isles", _("Western Isles")), ) UK_NATIONS_CHOICES = ( ("England", _("England")), ("Northern Ireland", _("Northern Ireland")), ("Scotland", _("Scotland")), ("Wales", _("Wales")), ) UK_REGION_CHOICES = ENGLAND_REGION_CHOICES + NORTHERN_IRELAND_REGION_CHOICES + WALES_REGION_CHOICES + SCOTTISH_REGION_CHOICES
3,504
Python
.py
90
34.522222
125
0.603757
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,813
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/uk/forms.py
""" UK-specific Form helpers """ import re from django.forms.fields import CharField, Select from django.forms import ValidationError from django.utils.translation import ugettext_lazy as _ class UKPostcodeField(CharField): """ A form field that validates its input is a UK postcode. The regular expression used is sourced from the schema for British Standard BS7666 address types: http://www.govtalk.gov.uk/gdsc/schemas/bs7666-v2-0.xsd The value is uppercased and a space added in the correct place, if required. """ default_error_messages = { 'invalid': _(u'Enter a valid postcode.'), } outcode_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])' incode_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}' postcode_regex = re.compile(r'^(GIR 0AA|%s %s)$' % (outcode_pattern, incode_pattern)) space_regex = re.compile(r' *(%s)$' % incode_pattern) def clean(self, value): value = super(UKPostcodeField, self).clean(value) if value == u'': return value postcode = value.upper().strip() # Put a single space before the incode (second part). postcode = self.space_regex.sub(r' \1', postcode) if not self.postcode_regex.search(postcode): raise ValidationError(self.error_messages['invalid']) return postcode class UKCountySelect(Select): """ A Select widget that uses a list of UK Counties/Regions as its choices. """ def __init__(self, attrs=None): from uk_regions import UK_REGION_CHOICES super(UKCountySelect, self).__init__(attrs, choices=UK_REGION_CHOICES) class UKNationSelect(Select): """ A Select widget that uses a list of UK Nations as its choices. """ def __init__(self, attrs=None): from uk_regions import UK_NATIONS_CHOICES super(UKNationSelect, self).__init__(attrs, choices=UK_NATIONS_CHOICES)
1,943
Python
.py
45
37.466667
104
0.674074
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,814
sk_regions.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/sk/sk_regions.py
""" Slovak regions according to http://sk.wikipedia.org/wiki/Administrat%C3%ADvne_%C4%8Dlenenie_Slovenska """ from django.utils.translation import ugettext_lazy as _ REGION_CHOICES = ( ('BB', _('Banska Bystrica region')), ('BA', _('Bratislava region')), ('KE', _('Kosice region')), ('NR', _('Nitra region')), ('PO', _('Presov region')), ('TN', _('Trencin region')), ('TT', _('Trnava region')), ('ZA', _('Zilina region')), )
458
Python
.py
14
29.285714
101
0.604072
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,815
sk_districts.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/sk/sk_districts.py
""" Slovak districts according to http://sk.wikipedia.org/wiki/Administrat%C3%ADvne_%C4%8Dlenenie_Slovenska """ from django.utils.translation import ugettext_lazy as _ DISTRICT_CHOICES = ( ('BB', _('Banska Bystrica')), ('BS', _('Banska Stiavnica')), ('BJ', _('Bardejov')), ('BN', _('Banovce nad Bebravou')), ('BR', _('Brezno')), ('BA1', _('Bratislava I')), ('BA2', _('Bratislava II')), ('BA3', _('Bratislava III')), ('BA4', _('Bratislava IV')), ('BA5', _('Bratislava V')), ('BY', _('Bytca')), ('CA', _('Cadca')), ('DT', _('Detva')), ('DK', _('Dolny Kubin')), ('DS', _('Dunajska Streda')), ('GA', _('Galanta')), ('GL', _('Gelnica')), ('HC', _('Hlohovec')), ('HE', _('Humenne')), ('IL', _('Ilava')), ('KK', _('Kezmarok')), ('KN', _('Komarno')), ('KE1', _('Kosice I')), ('KE2', _('Kosice II')), ('KE3', _('Kosice III')), ('KE4', _('Kosice IV')), ('KEO', _('Kosice - okolie')), ('KA', _('Krupina')), ('KM', _('Kysucke Nove Mesto')), ('LV', _('Levice')), ('LE', _('Levoca')), ('LM', _('Liptovsky Mikulas')), ('LC', _('Lucenec')), ('MA', _('Malacky')), ('MT', _('Martin')), ('ML', _('Medzilaborce')), ('MI', _('Michalovce')), ('MY', _('Myjava')), ('NO', _('Namestovo')), ('NR', _('Nitra')), ('NM', _('Nove Mesto nad Vahom')), ('NZ', _('Nove Zamky')), ('PE', _('Partizanske')), ('PK', _('Pezinok')), ('PN', _('Piestany')), ('PT', _('Poltar')), ('PP', _('Poprad')), ('PB', _('Povazska Bystrica')), ('PO', _('Presov')), ('PD', _('Prievidza')), ('PU', _('Puchov')), ('RA', _('Revuca')), ('RS', _('Rimavska Sobota')), ('RV', _('Roznava')), ('RK', _('Ruzomberok')), ('SB', _('Sabinov')), ('SC', _('Senec')), ('SE', _('Senica')), ('SI', _('Skalica')), ('SV', _('Snina')), ('SO', _('Sobrance')), ('SN', _('Spisska Nova Ves')), ('SL', _('Stara Lubovna')), ('SP', _('Stropkov')), ('SK', _('Svidnik')), ('SA', _('Sala')), ('TO', _('Topolcany')), ('TV', _('Trebisov')), ('TN', _('Trencin')), ('TT', _('Trnava')), ('TR', _('Turcianske Teplice')), ('TS', _('Tvrdosin')), ('VK', _('Velky Krtis')), ('VT', _('Vranov nad Toplou')), ('ZM', _('Zlate Moravce')), ('ZV', _('Zvolen')), ('ZC', _('Zarnovica')), ('ZH', _('Ziar nad Hronom')), ('ZA', _('Zilina')), )
2,453
Python
.py
85
24.117647
103
0.434066
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,816
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/sk/forms.py
""" Slovak-specific form helpers """ from django.forms.fields import Select, RegexField from django.utils.translation import ugettext_lazy as _ class SKRegionSelect(Select): """ A select widget widget with list of Slovak regions as choices. """ def __init__(self, attrs=None): from sk_regions import REGION_CHOICES super(SKRegionSelect, self).__init__(attrs, choices=REGION_CHOICES) class SKDistrictSelect(Select): """ A select widget with list of Slovak districts as choices. """ def __init__(self, attrs=None): from sk_districts import DISTRICT_CHOICES super(SKDistrictSelect, self).__init__(attrs, choices=DISTRICT_CHOICES) class SKPostalCodeField(RegexField): """ A form field that validates its input as Slovak postal code. Valid form is XXXXX or XXX XX, where X represents integer. """ default_error_messages = { 'invalid': _(u'Enter a postal code in the format XXXXX or XXX XX.'), } def __init__(self, *args, **kwargs): super(SKPostalCodeField, self).__init__(r'^\d{5}$|^\d{3} \d{2}$', max_length=None, min_length=None, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(SKPostalCodeField, self).clean(value) return v.replace(' ', '')
1,439
Python
.py
37
33.081081
79
0.66404
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,817
fr_department.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/fr/fr_department.py
# -*- coding: utf-8 -*- DEPARTMENT_ASCII_CHOICES = ( ('01', '01 - Ain'), ('02', '02 - Aisne'), ('03', '03 - Allier'), ('04', '04 - Alpes-de-Haute-Provence'), ('05', '05 - Hautes-Alpes'), ('06', '06 - Alpes-Maritimes'), ('07', '07 - Ardeche'), ('08', '08 - Ardennes'), ('09', '09 - Ariege'), ('10', '10 - Aube'), ('11', '11 - Aude'), ('12', '12 - Aveyron'), ('13', '13 - Bouches-du-Rhone'), ('14', '14 - Calvados'), ('15', '15 - Cantal'), ('16', '16 - Charente'), ('17', '17 - Charente-Maritime'), ('18', '18 - Cher'), ('19', '19 - Correze'), ('21', '21 - Cote-d\'Or'), ('22', '22 - Cotes-d\'Armor'), ('23', '23 - Creuse'), ('24', '24 - Dordogne'), ('25', '25 - Doubs'), ('26', '26 - Drome'), ('27', '27 - Eure'), ('28', '28 - Eure-et-Loire'), ('29', '29 - Finistere'), ('2A', '2A - Corse-du-Sud'), ('2B', '2B - Haute-Corse'), ('30', '30 - Gard'), ('31', '31 - Haute-Garonne'), ('32', '32 - Gers'), ('33', '33 - Gironde'), ('34', '34 - Herault'), ('35', '35 - Ille-et-Vilaine'), ('36', '36 - Indre'), ('37', '37 - Indre-et-Loire'), ('38', '38 - Isere'), ('39', '39 - Jura'), ('40', '40 - Landes'), ('41', '41 - Loir-et-Cher'), ('42', '42 - Loire'), ('43', '43 - Haute-Loire'), ('44', '44 - Loire-Atlantique'), ('45', '45 - Loiret'), ('46', '46 - Lot'), ('47', '47 - Lot-et-Garonne'), ('48', '48 - Lozere'), ('49', '49 - Maine-et-Loire'), ('50', '50 - Manche'), ('51', '51 - Marne'), ('52', '52 - Haute-Marne'), ('53', '53 - Mayenne'), ('54', '54 - Meurthe-et-Moselle'), ('55', '55 - Meuse'), ('56', '56 - Morbihan'), ('57', '57 - Moselle'), ('58', '58 - Nievre'), ('59', '59 - Nord'), ('60', '60 - Oise'), ('61', '61 - Orne'), ('62', '62 - Pas-de-Calais'), ('63', '63 - Puy-de-Dome'), ('64', '64 - Pyrenees-Atlantiques'), ('65', '65 - Hautes-Pyrenees'), ('66', '66 - Pyrenees-Orientales'), ('67', '67 - Bas-Rhin'), ('68', '68 - Haut-Rhin'), ('69', '69 - Rhone'), ('70', '70 - Haute-Saone'), ('71', '71 - Saone-et-Loire'), ('72', '72 - Sarthe'), ('73', '73 - Savoie'), ('74', '74 - Haute-Savoie'), ('75', '75 - Paris'), ('76', '76 - Seine-Maritime'), ('77', '77 - Seine-et-Marne'), ('78', '78 - Yvelines'), ('79', '79 - Deux-Sevres'), ('80', '80 - Somme'), ('81', '81 - Tarn'), ('82', '82 - Tarn-et-Garonne'), ('83', '83 - Var'), ('84', '84 - Vaucluse'), ('85', '85 - Vendee'), ('86', '86 - Vienne'), ('87', '87 - Haute-Vienne'), ('88', '88 - Vosges'), ('89', '89 - Yonne'), ('90', '90 - Territoire de Belfort'), ('91', '91 - Essonne'), ('92', '92 - Hauts-de-Seine'), ('93', '93 - Seine-Saint-Denis'), ('94', '94 - Val-de-Marne'), ('95', '95 - Val-d\'Oise'), ('971', '971 - Guadeloupe'), ('972', '972 - Martinique'), ('973', '973 - Guyane'), ('974', '974 - La Reunion'), ('975', '975 - Saint-Pierre-et-Miquelon'), ('976', '976 - Mayotte'), ('984', '984 - Terres Australes et Antarctiques'), ('986', '986 - Wallis et Futuna'), ('987', '987 - Polynesie Francaise'), ('988', '988 - Nouvelle-Caledonie'), )
3,326
Python
.py
109
25.614679
54
0.442475
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,818
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/localflavor/fr/forms.py
""" FR-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re phone_digits_re = re.compile(r'^0\d(\s|\.)?(\d{2}(\s|\.)?){3}\d{2}$') class FRZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXXX.'), } def __init__(self, *args, **kwargs): super(FRZipCodeField, self).__init__(r'^\d{5}$', max_length=None, min_length=None, *args, **kwargs) class FRPhoneNumberField(Field): """ Validate local French phone number (not international ones) The correct format is '0X XX XX XX XX'. '0X.XX.XX.XX.XX' and '0XXXXXXXXX' validate but are corrected to '0X XX XX XX XX'. """ default_error_messages = { 'invalid': _('Phone numbers must be in 0X XX XX XX XX format.'), } def clean(self, value): super(FRPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\.|\s)', '', smart_unicode(value)) m = phone_digits_re.search(value) if m: return u'%s %s %s %s %s' % (value[0:2], value[2:4], value[4:6], value[6:8], value[8:10]) raise ValidationError(self.error_messages['invalid']) class FRDepartmentSelect(Select): """ A Select widget that uses a list of FR departments as its choices. """ def __init__(self, attrs=None): from fr_department import DEPARTMENT_ASCII_CHOICES super(FRDepartmentSelect, self).__init__(attrs, choices=DEPARTMENT_ASCII_CHOICES)
1,747
Python
.py
43
35.069767
100
0.65566
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,819
signals.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/signals.py
""" Signals relating to comments. """ from django.dispatch import Signal # Sent just before a comment will be posted (after it's been approved and # moderated; this can be used to modify the comment (in place) with posting # details or other such actions. If any receiver returns False the comment will be # discarded and a 403 (not allowed) response. This signal is sent at more or less # the same time (just before, actually) as the Comment object's pre-save signal, # except that the HTTP request is sent along with this signal. comment_will_be_posted = Signal(providing_args=["comment", "request"]) # Sent just after a comment was posted. See above for how this differs # from the Comment object's post-save signal. comment_was_posted = Signal(providing_args=["comment", "request"]) # Sent after a comment was "flagged" in some way. Check the flag to see if this # was a user requesting removal of a comment, a moderator approving/removing a # comment, or some other custom user flag. comment_was_flagged = Signal(providing_args=["comment", "flag", "created", "request"])
1,079
Python
.py
18
58.777778
86
0.769376
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,820
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/models.py
import datetime from django.contrib.auth.models import User from django.contrib.comments.managers import CommentManager from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.db import models from django.core import urlresolvers from django.utils.translation import ugettext_lazy as _ from django.conf import settings COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH',3000) class BaseCommentAbstractModel(models.Model): """ An abstract base class that any custom comment models probably should subclass. """ # Content-object field content_type = models.ForeignKey(ContentType, verbose_name=_('content type'), related_name="content_type_set_for_%(class)s") object_pk = models.TextField(_('object ID')) content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk") # Metadata about the comment site = models.ForeignKey(Site) class Meta: abstract = True def get_content_object_url(self): """ Get a URL suitable for redirecting to the content object. """ return urlresolvers.reverse( "comments-url-redirect", args=(self.content_type_id, self.object_pk) ) class Comment(BaseCommentAbstractModel): """ A user comment about some object. """ # Who posted this comment? If ``user`` is set then it was an authenticated # user; otherwise at least user_name should have been set and the comment # was posted by a non-authenticated user. user = models.ForeignKey(User, verbose_name=_('user'), blank=True, null=True, related_name="%(class)s_comments") user_name = models.CharField(_("user's name"), max_length=50, blank=True) user_email = models.EmailField(_("user's email address"), blank=True) user_url = models.URLField(_("user's URL"), blank=True) comment = models.TextField(_('comment'), max_length=COMMENT_MAX_LENGTH) # Metadata about the comment submit_date = models.DateTimeField(_('date/time submitted'), default=None) ip_address = models.IPAddressField(_('IP address'), blank=True, null=True) is_public = models.BooleanField(_('is public'), default=True, help_text=_('Uncheck this box to make the comment effectively ' \ 'disappear from the site.')) is_removed = models.BooleanField(_('is removed'), default=False, help_text=_('Check this box if the comment is inappropriate. ' \ 'A "This comment has been removed" message will ' \ 'be displayed instead.')) # Manager objects = CommentManager() class Meta: db_table = "django_comments" ordering = ('submit_date',) permissions = [("can_moderate", "Can moderate comments")] verbose_name = _('comment') verbose_name_plural = _('comments') def __unicode__(self): return "%s: %s..." % (self.name, self.comment[:50]) def save(self, *args, **kwargs): if self.submit_date is None: self.submit_date = datetime.datetime.now() super(Comment, self).save(*args, **kwargs) def _get_userinfo(self): """ Get a dictionary that pulls together information about the poster safely for both authenticated and non-authenticated comments. This dict will have ``name``, ``email``, and ``url`` fields. """ if not hasattr(self, "_userinfo"): self._userinfo = { "name" : self.user_name, "email" : self.user_email, "url" : self.user_url } if self.user_id: u = self.user if u.email: self._userinfo["email"] = u.email # If the user has a full name, use that for the user name. # However, a given user_name overrides the raw user.username, # so only use that if this comment has no associated name. if u.get_full_name(): self._userinfo["name"] = self.user.get_full_name() elif not self.user_name: self._userinfo["name"] = u.username return self._userinfo userinfo = property(_get_userinfo, doc=_get_userinfo.__doc__) def _get_name(self): return self.userinfo["name"] def _set_name(self, val): if self.user_id: raise AttributeError(_("This comment was posted by an authenticated "\ "user and thus the name is read-only.")) self.user_name = val name = property(_get_name, _set_name, doc="The name of the user who posted this comment") def _get_email(self): return self.userinfo["email"] def _set_email(self, val): if self.user_id: raise AttributeError(_("This comment was posted by an authenticated "\ "user and thus the email is read-only.")) self.user_email = val email = property(_get_email, _set_email, doc="The email of the user who posted this comment") def _get_url(self): return self.userinfo["url"] def _set_url(self, val): self.user_url = val url = property(_get_url, _set_url, doc="The URL given by the user who posted this comment") def get_absolute_url(self, anchor_pattern="#c%(id)s"): return self.get_content_object_url() + (anchor_pattern % self.__dict__) def get_as_text(self): """ Return this comment as plain text. Useful for emails. """ d = { 'user': self.user or self.name, 'date': self.submit_date, 'comment': self.comment, 'domain': self.site.domain, 'url': self.get_absolute_url() } return _('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % d class CommentFlag(models.Model): """ Records a flag on a comment. This is intentionally flexible; right now, a flag could be: * A "removal suggestion" -- where a user suggests a comment for (potential) removal. * A "moderator deletion" -- used when a moderator deletes a comment. You can (ab)use this model to add other flags, if needed. However, by design users are only allowed to flag a comment with a given flag once; if you want rating look elsewhere. """ user = models.ForeignKey(User, verbose_name=_('user'), related_name="comment_flags") comment = models.ForeignKey(Comment, verbose_name=_('comment'), related_name="flags") flag = models.CharField(_('flag'), max_length=30, db_index=True) flag_date = models.DateTimeField(_('date'), default=None) # Constants for flag types SUGGEST_REMOVAL = "removal suggestion" MODERATOR_DELETION = "moderator deletion" MODERATOR_APPROVAL = "moderator approval" class Meta: db_table = 'django_comment_flags' unique_together = [('user', 'comment', 'flag')] verbose_name = _('comment flag') verbose_name_plural = _('comment flags') def __unicode__(self): return "%s flag of comment ID %s by %s" % \ (self.flag, self.comment_id, self.user.username) def save(self, *args, **kwargs): if self.flag_date is None: self.flag_date = datetime.datetime.now() super(CommentFlag, self).save(*args, **kwargs)
7,636
Python
.py
161
38.378882
97
0.619476
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,821
feeds.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/feeds.py
from django.conf import settings from django.contrib.syndication.views import Feed from django.contrib.sites.models import Site from django.contrib import comments from django.utils.translation import ugettext as _ class LatestCommentFeed(Feed): """Feed of latest comments on the current site.""" def title(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return _("%(site_name)s comments") % dict(site_name=self._site.name) def link(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "http://%s/" % (self._site.domain) def description(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return _("Latest comments on %(site_name)s") % dict(site_name=self._site.name) def items(self): qs = comments.get_model().objects.filter( site__pk = settings.SITE_ID, is_public = True, is_removed = False, ) if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None): where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)'] params = [settings.COMMENTS_BANNED_USERS_GROUP] qs = qs.extra(where=where, params=params) return qs.order_by('-submit_date')[:40] def item_pubdate(self, item): return item.submit_date
1,439
Python
.py
32
36.90625
97
0.635261
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,822
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('django.contrib.comments.views', url(r'^post/$', 'comments.post_comment', name='comments-post-comment'), url(r'^posted/$', 'comments.comment_done', name='comments-comment-done'), url(r'^flag/(\d+)/$', 'moderation.flag', name='comments-flag'), url(r'^flagged/$', 'moderation.flag_done', name='comments-flag-done'), url(r'^delete/(\d+)/$', 'moderation.delete', name='comments-delete'), url(r'^deleted/$', 'moderation.delete_done', name='comments-delete-done'), url(r'^approve/(\d+)/$', 'moderation.approve', name='comments-approve'), url(r'^approved/$', 'moderation.approve_done', name='comments-approve-done'), ) urlpatterns += patterns('', url(r'^cr/(\d+)/(.+)/$', 'django.contrib.contenttypes.views.shortcut', name='comments-url-redirect'), )
941
Python
.py
14
63.5
105
0.601081
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,823
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/__init__.py
from django.conf import settings from django.core import urlresolvers from django.core.exceptions import ImproperlyConfigured from django.contrib.comments.models import Comment from django.contrib.comments.forms import CommentForm from django.utils.importlib import import_module DEFAULT_COMMENTS_APP = 'django.contrib.comments' def get_comment_app(): """ Get the comment app (i.e. "django.contrib.comments") as defined in the settings """ # Make sure the app's in INSTALLED_APPS comments_app = get_comment_app_name() if comments_app not in settings.INSTALLED_APPS: raise ImproperlyConfigured("The COMMENTS_APP (%r) "\ "must be in INSTALLED_APPS" % settings.COMMENTS_APP) # Try to import the package try: package = import_module(comments_app) except ImportError: raise ImproperlyConfigured("The COMMENTS_APP setting refers to "\ "a non-existing package.") return package def get_comment_app_name(): """ Returns the name of the comment app (either the setting value, if it exists, or the default). """ return getattr(settings, 'COMMENTS_APP', DEFAULT_COMMENTS_APP) def get_model(): """ Returns the comment model class. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_model"): return get_comment_app().get_model() else: return Comment def get_form(): """ Returns the comment ModelForm class. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_form"): return get_comment_app().get_form() else: return CommentForm def get_form_target(): """ Returns the target URL for the comment form submission view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_form_target"): return get_comment_app().get_form_target() else: return urlresolvers.reverse("django.contrib.comments.views.comments.post_comment") def get_flag_url(comment): """ Get the URL for the "flag this comment" view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_flag_url"): return get_comment_app().get_flag_url(comment) else: return urlresolvers.reverse("django.contrib.comments.views.moderation.flag", args=(comment.id,)) def get_delete_url(comment): """ Get the URL for the "delete this comment" view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_delete_url"): return get_comment_app().get_delete_url(comment) else: return urlresolvers.reverse("django.contrib.comments.views.moderation.delete", args=(comment.id,)) def get_approve_url(comment): """ Get the URL for the "approve this comment from moderation" view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_approve_url"): return get_comment_app().get_approve_url(comment) else: return urlresolvers.reverse("django.contrib.comments.views.moderation.approve", args=(comment.id,))
3,333
Python
.py
80
34.55
104
0.663171
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,824
admin.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/admin.py
from django.contrib import admin from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _, ungettext from django.contrib.comments import get_model from django.contrib.comments.views.moderation import perform_flag, perform_approve, perform_delete class CommentsAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('content_type', 'object_pk', 'site')} ), (_('Content'), {'fields': ('user', 'user_name', 'user_email', 'user_url', 'comment')} ), (_('Metadata'), {'fields': ('submit_date', 'ip_address', 'is_public', 'is_removed')} ), ) list_display = ('name', 'content_type', 'object_pk', 'ip_address', 'submit_date', 'is_public', 'is_removed') list_filter = ('submit_date', 'site', 'is_public', 'is_removed') date_hierarchy = 'submit_date' ordering = ('-submit_date',) raw_id_fields = ('user',) search_fields = ('comment', 'user__username', 'user_name', 'user_email', 'user_url', 'ip_address') actions = ["flag_comments", "approve_comments", "remove_comments"] def get_actions(self, request): actions = super(CommentsAdmin, self).get_actions(request) # Only superusers should be able to delete the comments from the DB. if not request.user.is_superuser and 'delete_selected' in actions: actions.pop('delete_selected') if not request.user.has_perm('comments.can_moderate'): if 'approve_comments' in actions: actions.pop('approve_comments') if 'remove_comments' in actions: actions.pop('remove_comments') return actions def flag_comments(self, request, queryset): self._bulk_flag(request, queryset, perform_flag, lambda n: ungettext('flagged', 'flagged', n)) flag_comments.short_description = _("Flag selected comments") def approve_comments(self, request, queryset): self._bulk_flag(request, queryset, perform_approve, lambda n: ungettext('approved', 'approved', n)) approve_comments.short_description = _("Approve selected comments") def remove_comments(self, request, queryset): self._bulk_flag(request, queryset, perform_delete, lambda n: ungettext('removed', 'removed', n)) remove_comments.short_description = _("Remove selected comments") def _bulk_flag(self, request, queryset, action, done_message): """ Flag, approve, or remove some comments from an admin action. Actually calls the `action` argument to perform the heavy lifting. """ n_comments = 0 for comment in queryset: action(request, comment) n_comments += 1 msg = ungettext(u'1 comment was successfully %(action)s.', u'%(count)s comments were successfully %(action)s.', n_comments) self.message_user(request, msg % {'count': n_comments, 'action': done_message(n_comments)}) # Only register the default admin if the model is the built-in comment model # (this won't be true if there's a custom comment app). if get_model() is Comment: admin.site.register(Comment, CommentsAdmin)
3,299
Python
.py
64
42.6875
112
0.636392
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,825
moderation.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/moderation.py
""" A generic comment-moderation system which allows configuration of moderation options on a per-model basis. To use, do two things: 1. Create or import a subclass of ``CommentModerator`` defining the options you want. 2. Import ``moderator`` from this module and register one or more models, passing the models and the ``CommentModerator`` options class you want to use. Example ------- First, we define a simple model class which might represent entries in a Weblog:: from django.db import models class Entry(models.Model): title = models.CharField(maxlength=250) body = models.TextField() pub_date = models.DateField() enable_comments = models.BooleanField() Then we create a ``CommentModerator`` subclass specifying some moderation options:: from django.contrib.comments.moderation import CommentModerator, moderator class EntryModerator(CommentModerator): email_notification = True enable_field = 'enable_comments' And finally register it for moderation:: moderator.register(Entry, EntryModerator) This sample class would apply two moderation steps to each new comment submitted on an Entry: * If the entry's ``enable_comments`` field is set to ``False``, the comment will be rejected (immediately deleted). * If the comment is successfully posted, an email notification of the comment will be sent to site staff. For a full list of built-in moderation options and other configurability, see the documentation for the ``CommentModerator`` class. """ import datetime from django.conf import settings from django.core.mail import send_mail from django.contrib.comments import signals from django.db.models.base import ModelBase from django.template import Context, loader from django.contrib import comments from django.contrib.sites.models import Site class AlreadyModerated(Exception): """ Raised when a model which is already registered for moderation is attempting to be registered again. """ pass class NotModerated(Exception): """ Raised when a model which is not registered for moderation is attempting to be unregistered. """ pass class CommentModerator(object): """ Encapsulates comment-moderation options for a given model. This class is not designed to be used directly, since it doesn't enable any of the available moderation options. Instead, subclass it and override attributes to enable different options:: ``auto_close_field`` If this is set to the name of a ``DateField`` or ``DateTimeField`` on the model for which comments are being moderated, new comments for objects of that model will be disallowed (immediately deleted) when a certain number of days have passed after the date specified in that field. Must be used in conjunction with ``close_after``, which specifies the number of days past which comments should be disallowed. Default value is ``None``. ``auto_moderate_field`` Like ``auto_close_field``, but instead of outright deleting new comments when the requisite number of days have elapsed, it will simply set the ``is_public`` field of new comments to ``False`` before saving them. Must be used in conjunction with ``moderate_after``, which specifies the number of days past which comments should be moderated. Default value is ``None``. ``close_after`` If ``auto_close_field`` is used, this must specify the number of days past the value of the field specified by ``auto_close_field`` after which new comments for an object should be disallowed. Default value is ``None``. ``email_notification`` If ``True``, any new comment on an object of this model which survives moderation will generate an email to site staff. Default value is ``False``. ``enable_field`` If this is set to the name of a ``BooleanField`` on the model for which comments are being moderated, new comments on objects of that model will be disallowed (immediately deleted) whenever the value of that field is ``False`` on the object the comment would be attached to. Default value is ``None``. ``moderate_after`` If ``auto_moderate_field`` is used, this must specify the number of days past the value of the field specified by ``auto_moderate_field`` after which new comments for an object should be marked non-public. Default value is ``None``. Most common moderation needs can be covered by changing these attributes, but further customization can be obtained by subclassing and overriding the following methods. Each method will be called with three arguments: ``comment``, which is the comment being submitted, ``content_object``, which is the object the comment will be attached to, and ``request``, which is the ``HttpRequest`` in which the comment is being submitted:: ``allow`` Should return ``True`` if the comment should be allowed to post on the content object, and ``False`` otherwise (in which case the comment will be immediately deleted). ``email`` If email notification of the new comment should be sent to site staff or moderators, this method is responsible for sending the email. ``moderate`` Should return ``True`` if the comment should be moderated (in which case its ``is_public`` field will be set to ``False`` before saving), and ``False`` otherwise (in which case the ``is_public`` field will not be changed). Subclasses which want to introspect the model for which comments are being moderated can do so through the attribute ``_model``, which will be the model class. """ auto_close_field = None auto_moderate_field = None close_after = None email_notification = False enable_field = None moderate_after = None def __init__(self, model): self._model = model def _get_delta(self, now, then): """ Internal helper which will return a ``datetime.timedelta`` representing the time between ``now`` and ``then``. Assumes ``now`` is a ``datetime.date`` or ``datetime.datetime`` later than ``then``. If ``now`` and ``then`` are not of the same type due to one of them being a ``datetime.date`` and the other being a ``datetime.datetime``, both will be coerced to ``datetime.date`` before calculating the delta. """ if now.__class__ is not then.__class__: now = datetime.date(now.year, now.month, now.day) then = datetime.date(then.year, then.month, then.day) if now < then: raise ValueError("Cannot determine moderation rules because date field is set to a value in the future") return now - then def allow(self, comment, content_object, request): """ Determine whether a given comment is allowed to be posted on a given object. Return ``True`` if the comment should be allowed, ``False otherwise. """ if self.enable_field: if not getattr(content_object, self.enable_field): return False if self.auto_close_field and self.close_after: if self._get_delta(datetime.datetime.now(), getattr(content_object, self.auto_close_field)).days >= self.close_after: return False return True def moderate(self, comment, content_object, request): """ Determine whether a given comment on a given object should be allowed to show up immediately, or should be marked non-public and await approval. Return ``True`` if the comment should be moderated (marked non-public), ``False`` otherwise. """ if self.auto_moderate_field and self.moderate_after: if self._get_delta(datetime.datetime.now(), getattr(content_object, self.auto_moderate_field)).days >= self.moderate_after: return True return False def email(self, comment, content_object, request): """ Send email notification of a new comment to site staff when email notifications have been requested. """ if not self.email_notification: return recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS] t = loader.get_template('comments/comment_notification_email.txt') c = Context({ 'comment': comment, 'content_object': content_object }) subject = '[%s] New comment posted on "%s"' % (Site.objects.get_current().name, content_object) message = t.render(c) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True) class Moderator(object): """ Handles moderation of a set of models. An instance of this class will maintain a list of one or more models registered for comment moderation, and their associated moderation classes, and apply moderation to all incoming comments. To register a model, obtain an instance of ``Moderator`` (this module exports one as ``moderator``), and call its ``register`` method, passing the model class and a moderation class (which should be a subclass of ``CommentModerator``). Note that both of these should be the actual classes, not instances of the classes. To cease moderation for a model, call the ``unregister`` method, passing the model class. For convenience, both ``register`` and ``unregister`` can also accept a list of model classes in place of a single model; this allows easier registration of multiple models with the same ``CommentModerator`` class. The actual moderation is applied in two phases: one prior to saving a new comment, and the other immediately after saving. The pre-save moderation may mark a comment as non-public or mark it to be removed; the post-save moderation may delete a comment which was disallowed (there is currently no way to prevent the comment being saved once before removal) and, if the comment is still around, will send any notification emails the comment generated. """ def __init__(self): self._registry = {} self.connect() def connect(self): """ Hook up the moderation methods to pre- and post-save signals from the comment models. """ signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=comments.get_model()) signals.comment_was_posted.connect(self.post_save_moderation, sender=comments.get_model()) def register(self, model_or_iterable, moderation_class): """ Register a model or a list of models for comment moderation, using a particular moderation class. Raise ``AlreadyModerated`` if any of the models are already registered. """ if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model in self._registry: raise AlreadyModerated("The model '%s' is already being moderated" % model._meta.module_name) self._registry[model] = moderation_class(model) def unregister(self, model_or_iterable): """ Remove a model or a list of models from the list of models whose comments will be moderated. Raise ``NotModerated`` if any of the models are not currently registered for moderation. """ if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model not in self._registry: raise NotModerated("The model '%s' is not currently being moderated" % model._meta.module_name) del self._registry[model] def pre_save_moderation(self, sender, comment, request, **kwargs): """ Apply any necessary pre-save moderation steps to new comments. """ model = comment.content_type.model_class() if model not in self._registry: return content_object = comment.content_object moderation_class = self._registry[model] # Comment will be disallowed outright (HTTP 403 response) if not moderation_class.allow(comment, content_object, request): return False if moderation_class.moderate(comment, content_object, request): comment.is_public = False def post_save_moderation(self, sender, comment, request, **kwargs): """ Apply any necessary post-save moderation steps to new comments. """ model = comment.content_type.model_class() if model not in self._registry: return self._registry[model].email(comment, comment.content_object, request) # Import this instance in your own code to use in registering # your models for moderation. moderator = Moderator()
13,333
Python
.py
281
39.850534
135
0.682126
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,826
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/forms.py
import time import datetime from django import forms from django.forms.util import ErrorDict from django.conf import settings from django.contrib.contenttypes.models import ContentType from models import Comment from django.utils.encoding import force_unicode from django.utils.hashcompat import sha_constructor from django.utils.text import get_text_list from django.utils.translation import ungettext, ugettext_lazy as _ COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH', 3000) class CommentSecurityForm(forms.Form): """ Handles the security aspects (anti-spoofing) for comment forms. """ content_type = forms.CharField(widget=forms.HiddenInput) object_pk = forms.CharField(widget=forms.HiddenInput) timestamp = forms.IntegerField(widget=forms.HiddenInput) security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput) def __init__(self, target_object, data=None, initial=None): self.target_object = target_object if initial is None: initial = {} initial.update(self.generate_security_data()) super(CommentSecurityForm, self).__init__(data=data, initial=initial) def security_errors(self): """Return just those errors associated with security""" errors = ErrorDict() for f in ["honeypot", "timestamp", "security_hash"]: if f in self.errors: errors[f] = self.errors[f] return errors def clean_security_hash(self): """Check the security hash.""" security_hash_dict = { 'content_type' : self.data.get("content_type", ""), 'object_pk' : self.data.get("object_pk", ""), 'timestamp' : self.data.get("timestamp", ""), } expected_hash = self.generate_security_hash(**security_hash_dict) actual_hash = self.cleaned_data["security_hash"] if expected_hash != actual_hash: raise forms.ValidationError("Security hash check failed.") return actual_hash def clean_timestamp(self): """Make sure the timestamp isn't too far (> 2 hours) in the past.""" ts = self.cleaned_data["timestamp"] if time.time() - ts > (2 * 60 * 60): raise forms.ValidationError("Timestamp check failed") return ts def generate_security_data(self): """Generate a dict of security data for "initial" data.""" timestamp = int(time.time()) security_dict = { 'content_type' : str(self.target_object._meta), 'object_pk' : str(self.target_object._get_pk_val()), 'timestamp' : str(timestamp), 'security_hash' : self.initial_security_hash(timestamp), } return security_dict def initial_security_hash(self, timestamp): """ Generate the initial security hash from self.content_object and a (unix) timestamp. """ initial_security_dict = { 'content_type' : str(self.target_object._meta), 'object_pk' : str(self.target_object._get_pk_val()), 'timestamp' : str(timestamp), } return self.generate_security_hash(**initial_security_dict) def generate_security_hash(self, content_type, object_pk, timestamp): """Generate a (SHA1) security hash from the provided info.""" info = (content_type, object_pk, timestamp, settings.SECRET_KEY) return sha_constructor("".join(info)).hexdigest() class CommentDetailsForm(CommentSecurityForm): """ Handles the specific details of the comment (name, comment, etc.). """ name = forms.CharField(label=_("Name"), max_length=50) email = forms.EmailField(label=_("Email address")) url = forms.URLField(label=_("URL"), required=False) comment = forms.CharField(label=_('Comment'), widget=forms.Textarea, max_length=COMMENT_MAX_LENGTH) def get_comment_object(self): """ Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user`` or ``ip_address``). """ if not self.is_valid(): raise ValueError("get_comment_object may only be called on valid forms") CommentModel = self.get_comment_model() new = CommentModel(**self.get_comment_create_data()) new = self.check_for_duplicate_comment(new) return new def get_comment_model(self): """ Get the comment model to create with this form. Subclasses in custom comment apps should override this, get_comment_create_data, and perhaps check_for_duplicate_comment to provide custom comment models. """ return Comment def get_comment_create_data(self): """ Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model can override this method to add extra fields onto a custom comment model. """ return dict( content_type = ContentType.objects.get_for_model(self.target_object), object_pk = force_unicode(self.target_object._get_pk_val()), user_name = self.cleaned_data["name"], user_email = self.cleaned_data["email"], user_url = self.cleaned_data["url"], comment = self.cleaned_data["comment"], submit_date = datetime.datetime.now(), site_id = settings.SITE_ID, is_public = True, is_removed = False, ) def check_for_duplicate_comment(self, new): """ Check that a submitted comment isn't a duplicate. This might be caused by someone posting a comment twice. If it is a dup, silently return the *previous* comment. """ possible_duplicates = self.get_comment_model()._default_manager.using( self.target_object._state.db ).filter( content_type = new.content_type, object_pk = new.object_pk, user_name = new.user_name, user_email = new.user_email, user_url = new.user_url, ) for old in possible_duplicates: if old.submit_date.date() == new.submit_date.date() and old.comment == new.comment: return old return new def clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ comment = self.cleaned_data["comment"] if settings.COMMENTS_ALLOW_PROFANITIES == False: bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()] if bad_words: plural = len(bad_words) > 1 raise forms.ValidationError(ungettext( "Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", plural) % \ get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in bad_words], 'and')) return comment class CommentForm(CommentDetailsForm): honeypot = forms.CharField(required=False, label=_('If you enter anything in this field '\ 'your comment will be treated as spam')) def clean_honeypot(self): """Check that nothing's been entered into the honeypot.""" value = self.cleaned_data["honeypot"] if value: raise forms.ValidationError(self.fields["honeypot"].label) return value
7,896
Python
.py
167
37.724551
106
0.619907
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,827
managers.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/managers.py
from django.db import models from django.contrib.contenttypes.models import ContentType from django.utils.encoding import force_unicode class CommentManager(models.Manager): def in_moderation(self): """ QuerySet for all comments currently in the moderation queue. """ return self.get_query_set().filter(is_public=False, is_removed=False) def for_model(self, model): """ QuerySet for all comments for a particular model (either an instance or a class). """ ct = ContentType.objects.get_for_model(model) qs = self.get_query_set().filter(content_type=ct) if isinstance(model, models.Model): qs = qs.filter(object_pk=force_unicode(model._get_pk_val())) return qs
778
Python
.py
19
33.684211
79
0.67328
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,828
comments.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/templatetags/comments.py
from django import template from django.template.loader import render_to_string from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib import comments from django.utils.encoding import smart_unicode register = template.Library() class BaseCommentNode(template.Node): """ Base helper class (abstract) for handling the get_comment_* template tags. Looks a bit strange, but the subclasses below should make this a bit more obvious. """ #@classmethod def handle_token(cls, parser, token): """Class method to parse get_comment_list/count/form and return a Node.""" tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% get_whatever for obj as varname %} if len(tokens) == 5: if tokens[3] != 'as': raise template.TemplateSyntaxError("Third argument in %r must be 'as'" % tokens[0]) return cls( object_expr = parser.compile_filter(tokens[2]), as_varname = tokens[4], ) # {% get_whatever for app.model pk as varname %} elif len(tokens) == 6: if tokens[4] != 'as': raise template.TemplateSyntaxError("Fourth argument in %r must be 'as'" % tokens[0]) return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]), as_varname = tokens[5] ) else: raise template.TemplateSyntaxError("%r tag requires 4 or 5 arguments" % tokens[0]) handle_token = classmethod(handle_token) #@staticmethod def lookup_content_type(token, tagname): try: app, model = token.split('.') return ContentType.objects.get(app_label=app, model=model) except ValueError: raise template.TemplateSyntaxError("Third argument in %r must be in the format 'app.model'" % tagname) except ContentType.DoesNotExist: raise template.TemplateSyntaxError("%r tag has non-existant content-type: '%s.%s'" % (tagname, app, model)) lookup_content_type = staticmethod(lookup_content_type) def __init__(self, ctype=None, object_pk_expr=None, object_expr=None, as_varname=None, comment=None): if ctype is None and object_expr is None: raise template.TemplateSyntaxError("Comment nodes must be given either a literal object or a ctype and object pk.") self.comment_model = comments.get_model() self.as_varname = as_varname self.ctype = ctype self.object_pk_expr = object_pk_expr self.object_expr = object_expr self.comment = comment def render(self, context): qs = self.get_query_set(context) context[self.as_varname] = self.get_context_value_from_queryset(context, qs) return '' def get_query_set(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if not object_pk: return self.comment_model.objects.none() qs = self.comment_model.objects.filter( content_type = ctype, object_pk = smart_unicode(object_pk), site__pk = settings.SITE_ID, ) # The is_public and is_removed fields are implementation details of the # built-in comment model's spam filtering system, so they might not # be present on a custom comment model subclass. If they exist, we # should filter on them. field_names = [f.name for f in self.comment_model._meta.fields] if 'is_public' in field_names: qs = qs.filter(is_public=True) if getattr(settings, 'COMMENTS_HIDE_REMOVED', True) and 'is_removed' in field_names: qs = qs.filter(is_removed=False) return qs def get_target_ctype_pk(self, context): if self.object_expr: try: obj = self.object_expr.resolve(context) except template.VariableDoesNotExist: return None, None return ContentType.objects.get_for_model(obj), obj.pk else: return self.ctype, self.object_pk_expr.resolve(context, ignore_failures=True) def get_context_value_from_queryset(self, context, qs): """Subclasses should override this.""" raise NotImplementedError class CommentListNode(BaseCommentNode): """Insert a list of comments into the context.""" def get_context_value_from_queryset(self, context, qs): return list(qs) class CommentCountNode(BaseCommentNode): """Insert a count of comments into the context.""" def get_context_value_from_queryset(self, context, qs): return qs.count() class CommentFormNode(BaseCommentNode): """Insert a form for the comment model into the context.""" def get_form(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if object_pk: return comments.get_form()(ctype.get_object_for_this_type(pk=object_pk)) else: return None def render(self, context): context[self.as_varname] = self.get_form(context) return '' class RenderCommentFormNode(CommentFormNode): """Render the comment form directly""" #@classmethod def handle_token(cls, parser, token): """Class method to parse render_comment_form and return a Node.""" tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% render_comment_form for obj %} if len(tokens) == 3: return cls(object_expr=parser.compile_filter(tokens[2])) # {% render_comment_form for app.models pk %} elif len(tokens) == 4: return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]) ) handle_token = classmethod(handle_token) def render(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if object_pk: template_search_list = [ "comments/%s/%s/form.html" % (ctype.app_label, ctype.model), "comments/%s/form.html" % ctype.app_label, "comments/form.html" ] context.push() formstr = render_to_string(template_search_list, {"form" : self.get_form(context)}, context) context.pop() return formstr else: return '' class RenderCommentListNode(CommentListNode): """Render the comment list directly""" #@classmethod def handle_token(cls, parser, token): """Class method to parse render_comment_list and return a Node.""" tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) # {% render_comment_list for obj %} if len(tokens) == 3: return cls(object_expr=parser.compile_filter(tokens[2])) # {% render_comment_list for app.models pk %} elif len(tokens) == 4: return cls( ctype = BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr = parser.compile_filter(tokens[3]) ) handle_token = classmethod(handle_token) def render(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if object_pk: template_search_list = [ "comments/%s/%s/list.html" % (ctype.app_label, ctype.model), "comments/%s/list.html" % ctype.app_label, "comments/list.html" ] qs = self.get_query_set(context) context.push() liststr = render_to_string(template_search_list, { "comment_list" : self.get_context_value_from_queryset(context, qs) }, context) context.pop() return liststr else: return '' # We could just register each classmethod directly, but then we'd lose out on # the automagic docstrings-into-admin-docs tricks. So each node gets a cute # wrapper function that just exists to hold the docstring. #@register.tag def get_comment_count(parser, token): """ Gets the comment count for the given params and populates the template context with a variable containing that value, whose name is defined by the 'as' clause. Syntax:: {% get_comment_count for [object] as [varname] %} {% get_comment_count for [app].[model] [object_id] as [varname] %} Example usage:: {% get_comment_count for event as comment_count %} {% get_comment_count for calendar.event event.id as comment_count %} {% get_comment_count for calendar.event 17 as comment_count %} """ return CommentCountNode.handle_token(parser, token) #@register.tag def get_comment_list(parser, token): """ Gets the list of comments for the given params and populates the template context with a variable containing that value, whose name is defined by the 'as' clause. Syntax:: {% get_comment_list for [object] as [varname] %} {% get_comment_list for [app].[model] [object_id] as [varname] %} Example usage:: {% get_comment_list for event as comment_list %} {% for comment in comment_list %} ... {% endfor %} """ return CommentListNode.handle_token(parser, token) #@register.tag def render_comment_list(parser, token): """ Render the comment list (as returned by ``{% get_comment_list %}``) through the ``comments/list.html`` template Syntax:: {% render_comment_list for [object] %} {% render_comment_list for [app].[model] [object_id] %} Example usage:: {% render_comment_list for event %} """ return RenderCommentListNode.handle_token(parser, token) #@register.tag def get_comment_form(parser, token): """ Get a (new) form object to post a new comment. Syntax:: {% get_comment_form for [object] as [varname] %} {% get_comment_form for [app].[model] [object_id] as [varname] %} """ return CommentFormNode.handle_token(parser, token) #@register.tag def render_comment_form(parser, token): """ Render the comment form (as returned by ``{% render_comment_form %}``) through the ``comments/form.html`` template. Syntax:: {% render_comment_form for [object] %} {% render_comment_form for [app].[model] [object_id] %} """ return RenderCommentFormNode.handle_token(parser, token) #@register.simple_tag def comment_form_target(): """ Get the target URL for the comment form. Example:: <form action="{% comment_form_target %}" method="post"> """ return comments.get_form_target() #@register.simple_tag def get_comment_permalink(comment, anchor_pattern=None): """ Get the permalink for a comment, optionally specifying the format of the named anchor to be appended to the end of the URL. Example:: {{ get_comment_permalink comment "#c%(id)s-by-%(user_name)s" }} """ if anchor_pattern: return comment.get_absolute_url(anchor_pattern) return comment.get_absolute_url() register.tag(get_comment_count) register.tag(get_comment_list) register.tag(get_comment_form) register.tag(render_comment_form) register.simple_tag(comment_form_target) register.simple_tag(get_comment_permalink) register.tag(render_comment_list)
11,845
Python
.py
270
35.57037
127
0.638377
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,829
utils.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/views/utils.py
""" A few bits of helper functions for comment views. """ import urllib import textwrap from django.http import HttpResponseRedirect from django.core import urlresolvers from django.shortcuts import render_to_response from django.template import RequestContext from django.core.exceptions import ObjectDoesNotExist from django.contrib import comments def next_redirect(data, default, default_view, **get_kwargs): """ Handle the "where should I go next?" part of comment views. The next value could be a kwarg to the function (``default``), or a ``?next=...`` GET arg, or the URL of a given view (``default_view``). See the view modules for examples. Returns an ``HttpResponseRedirect``. """ next = data.get("next", default) if next is None: next = urlresolvers.reverse(default_view) if get_kwargs: joiner = ('?' in next) and '&' or '?' next += joiner + urllib.urlencode(get_kwargs) return HttpResponseRedirect(next) def confirmation_view(template, doc="Display a confirmation view."): """ Confirmation view generator for the "comment was posted/flagged/deleted/approved" views. """ def confirmed(request): comment = None if 'c' in request.GET: try: comment = comments.get_model().objects.get(pk=request.GET['c']) except (ObjectDoesNotExist, ValueError): pass return render_to_response(template, {'comment': comment}, context_instance=RequestContext(request) ) confirmed.__doc__ = textwrap.dedent("""\ %s Templates: `%s`` Context: comment The posted comment """ % (doc, template) ) return confirmed
1,777
Python
.py
51
28.372549
79
0.655032
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,830
comments.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/views/comments.py
from django import http from django.conf import settings from utils import next_redirect, confirmation_view from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.db import models from django.shortcuts import render_to_response from django.template import RequestContext from django.template.loader import render_to_string from django.utils.html import escape from django.views.decorators.http import require_POST from django.contrib import comments from django.contrib.comments import signals from django.views.decorators.csrf import csrf_protect class CommentPostBadRequest(http.HttpResponseBadRequest): """ Response returned when a comment post is invalid. If ``DEBUG`` is on a nice-ish error message will be displayed (for debugging purposes), but in production mode a simple opaque 400 page will be displayed. """ def __init__(self, why): super(CommentPostBadRequest, self).__init__() if settings.DEBUG: self.content = render_to_string("comments/400-debug.html", {"why": why}) @csrf_protect @require_POST def post_comment(request, next=None, using=None): """ Post a comment. HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are errors a preview template, ``comments/preview.html``, will be rendered. """ # Fill out some initial data fields from an authenticated user, if present data = request.POST.copy() if request.user.is_authenticated(): if not data.get('name', ''): data["name"] = request.user.get_full_name() or request.user.username if not data.get('email', ''): data["email"] = request.user.email # Check to see if the POST data overrides the view's next argument. next = data.get("next", next) # Look up the object we're trying to comment about ctype = data.get("content_type") object_pk = data.get("object_pk") if ctype is None or object_pk is None: return CommentPostBadRequest("Missing content_type or object_pk field.") try: model = models.get_model(*ctype.split(".", 1)) target = model._default_manager.using(using).get(pk=object_pk) except TypeError: return CommentPostBadRequest( "Invalid content_type value: %r" % escape(ctype)) except AttributeError: return CommentPostBadRequest( "The given content-type %r does not resolve to a valid model." % \ escape(ctype)) except ObjectDoesNotExist: return CommentPostBadRequest( "No object matching content-type %r and object PK %r exists." % \ (escape(ctype), escape(object_pk))) except (ValueError, ValidationError), e: return CommentPostBadRequest( "Attempting go get content-type %r and object PK %r exists raised %s" % \ (escape(ctype), escape(object_pk), e.__class__.__name__)) # Do we want to preview the comment? preview = "preview" in data # Construct the comment form form = comments.get_form()(target, data=data) # Check security information if form.security_errors(): return CommentPostBadRequest( "The comment form failed security verification: %s" % \ escape(str(form.security_errors()))) # If there are errors or if we requested a preview show the comment if form.errors or preview: template_list = [ # These first two exist for purely historical reasons. # Django v1.0 and v1.1 allowed the underscore format for # preview templates, so we have to preserve that format. "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.module_name), "comments/%s_preview.html" % model._meta.app_label, # Now the usual directory based template heirarchy. "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.module_name), "comments/%s/preview.html" % model._meta.app_label, "comments/preview.html", ] return render_to_response( template_list, { "comment" : form.data.get("comment", ""), "form" : form, "next": next, }, RequestContext(request, {}) ) # Otherwise create the comment comment = form.get_comment_object() comment.ip_address = request.META.get("REMOTE_ADDR", None) if request.user.is_authenticated(): comment.user = request.user # Signal that the comment is about to be saved responses = signals.comment_will_be_posted.send( sender = comment.__class__, comment = comment, request = request ) for (receiver, response) in responses: if response == False: return CommentPostBadRequest( "comment_will_be_posted receiver %r killed the comment" % receiver.__name__) # Save the comment and signal that it was saved comment.save() signals.comment_was_posted.send( sender = comment.__class__, comment = comment, request = request ) return next_redirect(data, next, comment_done, c=comment._get_pk_val()) comment_done = confirmation_view( template = "comments/posted.html", doc = """Display a "comment was posted" success page.""" )
5,359
Python
.py
120
37.158333
93
0.661114
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,831
moderation.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/comments/views/moderation.py
from django import template from django.conf import settings from django.shortcuts import get_object_or_404, render_to_response from django.contrib.auth.decorators import login_required, permission_required from utils import next_redirect, confirmation_view from django.contrib import comments from django.contrib.comments import signals from django.views.decorators.csrf import csrf_protect @csrf_protect @login_required def flag(request, comment_id, next=None): """ Flags a comment. Confirmation on GET, action on POST. Templates: `comments/flag.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) # Flag on POST if request.method == 'POST': perform_flag(request, comment) return next_redirect(request.POST.copy(), next, flag_done, c=comment.pk) # Render a form on GET else: return render_to_response('comments/flag.html', {'comment': comment, "next": next}, template.RequestContext(request) ) @csrf_protect @permission_required("comments.can_moderate") def delete(request, comment_id, next=None): """ Deletes a comment. Confirmation on GET, action on POST. Requires the "can moderate comments" permission. Templates: `comments/delete.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) # Delete on POST if request.method == 'POST': # Flag the comment as deleted instead of actually deleting it. perform_delete(request, comment) return next_redirect(request.POST.copy(), next, delete_done, c=comment.pk) # Render a form on GET else: return render_to_response('comments/delete.html', {'comment': comment, "next": next}, template.RequestContext(request) ) @csrf_protect @permission_required("comments.can_moderate") def approve(request, comment_id, next=None): """ Approve a comment (that is, mark it as public and non-removed). Confirmation on GET, action on POST. Requires the "can moderate comments" permission. Templates: `comments/approve.html`, Context: comment the `comments.comment` object for approval """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) # Delete on POST if request.method == 'POST': # Flag the comment as approved. perform_approve(request, comment) return next_redirect(request.POST.copy(), next, approve_done, c=comment.pk) # Render a form on GET else: return render_to_response('comments/approve.html', {'comment': comment, "next": next}, template.RequestContext(request) ) # The following functions actually perform the various flag/aprove/delete # actions. They've been broken out into seperate functions to that they # may be called from admin actions. def perform_flag(request, comment): """ Actually perform the flagging of a comment from a request. """ flag, created = comments.models.CommentFlag.objects.get_or_create( comment = comment, user = request.user, flag = comments.models.CommentFlag.SUGGEST_REMOVAL ) signals.comment_was_flagged.send( sender = comment.__class__, comment = comment, flag = flag, created = created, request = request, ) def perform_delete(request, comment): flag, created = comments.models.CommentFlag.objects.get_or_create( comment = comment, user = request.user, flag = comments.models.CommentFlag.MODERATOR_DELETION ) comment.is_removed = True comment.save() signals.comment_was_flagged.send( sender = comment.__class__, comment = comment, flag = flag, created = created, request = request, ) def perform_approve(request, comment): flag, created = comments.models.CommentFlag.objects.get_or_create( comment = comment, user = request.user, flag = comments.models.CommentFlag.MODERATOR_APPROVAL, ) comment.is_removed = False comment.is_public = True comment.save() signals.comment_was_flagged.send( sender = comment.__class__, comment = comment, flag = flag, created = created, request = request, ) # Confirmation views. flag_done = confirmation_view( template = "comments/flagged.html", doc = 'Displays a "comment was flagged" success page.' ) delete_done = confirmation_view( template = "comments/deleted.html", doc = 'Displays a "comment was deleted" success page.' ) approve_done = confirmation_view( template = "comments/approved.html", doc = 'Displays a "comment was approved" success page.' )
5,037
Python
.py
138
30.507246
95
0.676097
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,832
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/models.py
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User from django.contrib.admin.util import quote from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode from django.utils.safestring import mark_safe ADDITION = 1 CHANGE = 2 DELETION = 3 class LogEntryManager(models.Manager): def log_action(self, user_id, content_type_id, object_id, object_repr, action_flag, change_message=''): e = self.model(None, None, user_id, content_type_id, smart_unicode(object_id), object_repr[:200], action_flag, change_message) e.save() class LogEntry(models.Model): action_time = models.DateTimeField(_('action time'), auto_now=True) user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType, blank=True, null=True) object_id = models.TextField(_('object id'), blank=True, null=True) object_repr = models.CharField(_('object repr'), max_length=200) action_flag = models.PositiveSmallIntegerField(_('action flag')) change_message = models.TextField(_('change message'), blank=True) objects = LogEntryManager() class Meta: verbose_name = _('log entry') verbose_name_plural = _('log entries') db_table = 'django_admin_log' ordering = ('-action_time',) def __repr__(self): return smart_unicode(self.action_time) def is_addition(self): return self.action_flag == ADDITION def is_change(self): return self.action_flag == CHANGE def is_deletion(self): return self.action_flag == DELETION def get_edited_object(self): "Returns the edited object represented by this log entry" return self.content_type.get_object_for_this_type(pk=self.object_id) def get_admin_url(self): """ Returns the admin URL to edit the object represented by this log entry. This is relative to the Django admin index page. """ return mark_safe(u"%s/%s/%s/" % (self.content_type.app_label, self.content_type.model, quote(self.object_id)))
2,135
Python
.py
45
41.8
134
0.703508
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,833
util.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/util.py
from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.db.models.related import RelatedObject from django.forms.forms import pretty_name from django.utils import formats from django.utils.html import escape from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.encoding import force_unicode, smart_unicode, smart_str from django.utils.translation import ungettext, ugettext as _ from django.core.urlresolvers import reverse, NoReverseMatch from django.utils.datastructures import SortedDict def quote(s): """ Ensure that primary key values do not confuse the admin URLs by escaping any '/', '_' and ':' characters. Similar to urllib.quote, except that the quoting is slightly different so that it doesn't get automatically unquoted by the Web browser. """ if not isinstance(s, basestring): return s res = list(s) for i in range(len(res)): c = res[i] if c in """:/_#?;@&=+$,"<>%\\""": res[i] = '_%02X' % ord(c) return ''.join(res) def unquote(s): """ Undo the effects of quote(). Based heavily on urllib.unquote(). """ mychr = chr myatoi = int list = s.split('_') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend(mychr(myatoi(item[:2], 16)) + item[2:]) except ValueError: myappend('_' + item) else: myappend('_' + item) return "".join(res) def flatten_fieldsets(fieldsets): """Returns a list of field names from an admin fieldsets structure.""" field_names = [] for name, opts in fieldsets: for field in opts['fields']: # type checking feels dirty, but it seems like the best way here if type(field) == tuple: field_names.extend(field) else: field_names.append(field) return field_names def _format_callback(obj, user, admin_site, levels_to_root, perms_needed): has_admin = obj.__class__ in admin_site._registry opts = obj._meta try: admin_url = reverse('%s:%s_%s_change' % (admin_site.name, opts.app_label, opts.object_name.lower()), None, (quote(obj._get_pk_val()),)) except NoReverseMatch: admin_url = '%s%s/%s/%s/' % ('../'*levels_to_root, opts.app_label, opts.object_name.lower(), quote(obj._get_pk_val())) if has_admin: p = '%s.%s' % (opts.app_label, opts.get_delete_permission()) if not user.has_perm(p): perms_needed.add(opts.verbose_name) # Display a link to the admin page. return mark_safe(u'%s: <a href="%s">%s</a>' % (escape(capfirst(opts.verbose_name)), admin_url, escape(obj))) else: # Don't display link to edit, because it either has no # admin or is edited inline. return u'%s: %s' % (capfirst(opts.verbose_name), force_unicode(obj)) def get_deleted_objects(objs, opts, user, admin_site, levels_to_root=4): """ Find all objects related to ``objs`` that should also be deleted. ``objs`` should be an iterable of objects. Returns a nested list of strings suitable for display in the template with the ``unordered_list`` filter. `levels_to_root` defines the number of directories (../) to reach the admin root path. In a change_view this is 4, in a change_list view 2. This is for backwards compatibility since the options.delete_selected method uses this function also from a change_list view. This will not be used if we can reverse the URL. """ collector = NestedObjects() for obj in objs: # TODO using a private model API! obj._collect_sub_objects(collector) perms_needed = set() to_delete = collector.nested(_format_callback, user=user, admin_site=admin_site, levels_to_root=levels_to_root, perms_needed=perms_needed) return to_delete, perms_needed class NestedObjects(object): """ A directed acyclic graph collection that exposes the add() API expected by Model._collect_sub_objects and can present its data as a nested list of objects. """ def __init__(self): # Use object keys of the form (model, pk) because actual model # objects may not be unique # maps object key to list of child keys self.children = SortedDict() # maps object key to parent key self.parents = SortedDict() # maps object key to actual object self.seen = SortedDict() def add(self, model, pk, obj, parent_model=None, parent_obj=None, nullable=False): """ Add item ``obj`` to the graph. Returns True (and does nothing) if the item has been seen already. The ``parent_obj`` argument must already exist in the graph; if not, it's ignored (but ``obj`` is still added with no parent). In any case, Model._collect_sub_objects (for whom this API exists) will never pass a parent that hasn't already been added itself. These restrictions in combination ensure the graph will remain acyclic (but can have multiple roots). ``model``, ``pk``, and ``parent_model`` arguments are ignored in favor of the appropriate lookups on ``obj`` and ``parent_obj``; unlike CollectedObjects, we can't maintain independence from the knowledge that we're operating on model instances, and we don't want to allow for inconsistency. ``nullable`` arg is ignored: it doesn't affect how the tree of collected objects should be nested for display. """ model, pk = type(obj), obj._get_pk_val() # auto-created M2M models don't interest us if model._meta.auto_created: return True key = model, pk if key in self.seen: return True self.seen.setdefault(key, obj) if parent_obj is not None: parent_model, parent_pk = (type(parent_obj), parent_obj._get_pk_val()) parent_key = (parent_model, parent_pk) if parent_key in self.seen: self.children.setdefault(parent_key, list()).append(key) self.parents.setdefault(key, parent_key) def _nested(self, key, format_callback=None, **kwargs): obj = self.seen[key] if format_callback: ret = [format_callback(obj, **kwargs)] else: ret = [obj] children = [] for child in self.children.get(key, ()): children.extend(self._nested(child, format_callback, **kwargs)) if children: ret.append(children) return ret def nested(self, format_callback=None, **kwargs): """ Return the graph as a nested list. Passes **kwargs back to the format_callback as kwargs. """ roots = [] for key in self.seen.keys(): if key not in self.parents: roots.extend(self._nested(key, format_callback, **kwargs)) return roots def model_format_dict(obj): """ Return a `dict` with keys 'verbose_name' and 'verbose_name_plural', typically for use with string formatting. `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance. """ if isinstance(obj, (models.Model, models.base.ModelBase)): opts = obj._meta elif isinstance(obj, models.query.QuerySet): opts = obj.model._meta else: opts = obj return { 'verbose_name': force_unicode(opts.verbose_name), 'verbose_name_plural': force_unicode(opts.verbose_name_plural) } def model_ngettext(obj, n=None): """ Return the appropriate `verbose_name` or `verbose_name_plural` value for `obj` depending on the count `n`. `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance. If `obj` is a `QuerySet` instance, `n` is optional and the length of the `QuerySet` is used. """ if isinstance(obj, models.query.QuerySet): if n is None: n = obj.count() obj = obj.model d = model_format_dict(obj) singular, plural = d["verbose_name"], d["verbose_name_plural"] return ungettext(singular, plural, n or 0) def lookup_field(name, obj, model_admin=None): opts = obj._meta try: f = opts.get_field(name) except models.FieldDoesNotExist: # For non-field values, the value is either a method, property or # returned via a callable. if callable(name): attr = name value = attr(obj) elif (model_admin is not None and hasattr(model_admin, name) and not name == '__str__' and not name == '__unicode__'): attr = getattr(model_admin, name) value = attr(obj) else: attr = getattr(obj, name) if callable(attr): value = attr() else: value = attr f = None else: attr = None value = getattr(obj, name) return f, attr, value def label_for_field(name, model, model_admin=None, return_attr=False): attr = None try: field = model._meta.get_field_by_name(name)[0] if isinstance(field, RelatedObject): label = field.opts.verbose_name else: label = field.verbose_name except models.FieldDoesNotExist: if name == "__unicode__": label = force_unicode(model._meta.verbose_name) elif name == "__str__": label = smart_str(model._meta.verbose_name) else: if callable(name): attr = name elif model_admin is not None and hasattr(model_admin, name): attr = getattr(model_admin, name) elif hasattr(model, name): attr = getattr(model, name) else: message = "Unable to lookup '%s' on %s" % (name, model._meta.object_name) if model_admin: message += " or %s" % (model_admin.__name__,) raise AttributeError(message) if hasattr(attr, "short_description"): label = attr.short_description elif callable(attr): if attr.__name__ == "<lambda>": label = "--" else: label = pretty_name(attr.__name__) else: label = pretty_name(name) if return_attr: return (label, attr) else: return label def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return _boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateField) or isinstance(field, models.TimeField): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) else: return smart_unicode(value)
12,120
Python
.py
295
31.410169
94
0.597793
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,834
options.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/options.py
from django import forms, template from django.forms.formsets import all_valid from django.forms.models import modelform_factory, modelformset_factory, inlineformset_factory from django.forms.models import BaseInlineFormSet from django.contrib.contenttypes.models import ContentType from django.contrib.admin import widgets from django.contrib.admin import helpers from django.contrib.admin.util import unquote, flatten_fieldsets, get_deleted_objects, model_ngettext, model_format_dict from django.contrib import messages from django.views.decorators.csrf import csrf_protect from django.core.exceptions import PermissionDenied, ValidationError from django.db import models, transaction from django.db.models.related import RelatedObject from django.db.models.fields import BLANK_CHOICE_DASH, FieldDoesNotExist from django.db.models.sql.constants import LOOKUP_SEP, QUERY_TERMS from django.http import Http404, HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render_to_response from django.utils.decorators import method_decorator from django.utils.datastructures import SortedDict from django.utils.functional import update_wrapper from django.utils.html import escape, escapejs from django.utils.safestring import mark_safe from django.utils.functional import curry from django.utils.text import capfirst, get_text_list from django.utils.translation import ugettext as _ from django.utils.translation import ungettext, ugettext_lazy from django.utils.encoding import force_unicode HORIZONTAL, VERTICAL = 1, 2 # returns the <ul> class for a given radio_admin field get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '') class IncorrectLookupParameters(Exception): pass # Defaults for formfield_overrides. ModelAdmin subclasses can change this # by adding to ModelAdmin.formfield_overrides. FORMFIELD_FOR_DBFIELD_DEFAULTS = { models.DateTimeField: { 'form_class': forms.SplitDateTimeField, 'widget': widgets.AdminSplitDateTime }, models.DateField: {'widget': widgets.AdminDateWidget}, models.TimeField: {'widget': widgets.AdminTimeWidget}, models.TextField: {'widget': widgets.AdminTextareaWidget}, models.URLField: {'widget': widgets.AdminURLFieldWidget}, models.IntegerField: {'widget': widgets.AdminIntegerFieldWidget}, models.BigIntegerField: {'widget': widgets.AdminIntegerFieldWidget}, models.CharField: {'widget': widgets.AdminTextInputWidget}, models.ImageField: {'widget': widgets.AdminFileWidget}, models.FileField: {'widget': widgets.AdminFileWidget}, } csrf_protect_m = method_decorator(csrf_protect) class BaseModelAdmin(object): """Functionality common to both ModelAdmin and InlineAdmin.""" __metaclass__ = forms.MediaDefiningClass raw_id_fields = () fields = None exclude = None fieldsets = None form = forms.ModelForm filter_vertical = () filter_horizontal = () radio_fields = {} prepopulated_fields = {} formfield_overrides = {} readonly_fields = () def __init__(self): overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy() overrides.update(self.formfield_overrides) self.formfield_overrides = overrides def formfield_for_dbfield(self, db_field, **kwargs): """ Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, they're passed to the form Field's constructor. """ request = kwargs.pop("request", None) # If the field specifies choices, we don't need to look for special # admin widgets - we just need to use a select widget of some kind. if db_field.choices: return self.formfield_for_choice_field(db_field, request, **kwargs) # ForeignKey or ManyToManyFields if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)): # Combine the field kwargs with any options for formfield_overrides. # Make sure the passed in **kwargs override anything in # formfield_overrides because **kwargs is more specific, and should # always win. if db_field.__class__ in self.formfield_overrides: kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs) # Get the correct formfield. if isinstance(db_field, models.ForeignKey): formfield = self.formfield_for_foreignkey(db_field, request, **kwargs) elif isinstance(db_field, models.ManyToManyField): formfield = self.formfield_for_manytomany(db_field, request, **kwargs) # For non-raw_id fields, wrap the widget with a wrapper that adds # extra HTML -- the "add other" interface -- to the end of the # rendered output. formfield can be None if it came from a # OneToOneField with parent_link=True or a M2M intermediary. if formfield and db_field.name not in self.raw_id_fields: formfield.widget = widgets.RelatedFieldWidgetWrapper(formfield.widget, db_field.rel, self.admin_site) return formfield # If we've got overrides for the formfield defined, use 'em. **kwargs # passed to formfield_for_dbfield override the defaults. for klass in db_field.__class__.mro(): if klass in self.formfield_overrides: kwargs = dict(self.formfield_overrides[klass], **kwargs) return db_field.formfield(**kwargs) # For any other type of field, just call its formfield() method. return db_field.formfield(**kwargs) def formfield_for_choice_field(self, db_field, request=None, **kwargs): """ Get a form Field for a database Field that has declared choices. """ # If the field is named as a radio_field, use a RadioSelect if db_field.name in self.radio_fields: # Avoid stomping on custom widget/choices arguments. if 'widget' not in kwargs: kwargs['widget'] = widgets.AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) if 'choices' not in kwargs: kwargs['choices'] = db_field.get_choices( include_blank = db_field.blank, blank_choice=[('', _('None'))] ) return db_field.formfield(**kwargs) def formfield_for_foreignkey(self, db_field, request=None, **kwargs): """ Get a form Field for a ForeignKey. """ db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel, using=db) elif db_field.name in self.radio_fields: kwargs['widget'] = widgets.AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) kwargs['empty_label'] = db_field.blank and _('None') or None return db_field.formfield(**kwargs) def formfield_for_manytomany(self, db_field, request=None, **kwargs): """ Get a form Field for a ManyToManyField. """ # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.rel.through._meta.auto_created: return None db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, using=db) kwargs['help_text'] = '' elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)): kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical)) return db_field.formfield(**kwargs) def _declared_fieldsets(self): if self.fieldsets: return self.fieldsets elif self.fields: return [(None, {'fields': self.fields})] return None declared_fieldsets = property(_declared_fieldsets) def get_readonly_fields(self, request, obj=None): return self.readonly_fields def lookup_allowed(self, lookup, value): model = self.model # Check FKey lookups that are allowed, so that popups produced by # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to, # are allowed to work. for l in model._meta.related_fkey_lookups: for k, v in widgets.url_params_from_lookup_dict(l).items(): if k == lookup and v == value: return True parts = lookup.split(LOOKUP_SEP) # Last term in lookup is a query term (__exact, __startswith etc) # This term can be ignored. if len(parts) > 1 and parts[-1] in QUERY_TERMS: parts.pop() # Special case -- foo__id__exact and foo__id queries are implied # if foo has been specificially included in the lookup list; so # drop __id if it is the last part. However, first we need to find # the pk attribute name. pk_attr_name = None for part in parts[:-1]: field, _, _, _ = model._meta.get_field_by_name(part) if hasattr(field, 'rel'): model = field.rel.to pk_attr_name = model._meta.pk.name elif isinstance(field, RelatedObject): model = field.model pk_attr_name = model._meta.pk.name else: pk_attr_name = None if pk_attr_name and len(parts) > 1 and parts[-1] == pk_attr_name: parts.pop() try: self.model._meta.get_field_by_name(parts[0]) except FieldDoesNotExist: # Lookups on non-existants fields are ok, since they're ignored # later. return True else: if len(parts) == 1: return True clean_lookup = LOOKUP_SEP.join(parts) return clean_lookup in self.list_filter or clean_lookup == self.date_hierarchy class ModelAdmin(BaseModelAdmin): "Encapsulates all admin options and functionality for a given model." list_display = ('__str__',) list_display_links = () list_filter = () list_select_related = False list_per_page = 100 list_editable = () search_fields = () date_hierarchy = None save_as = False save_on_top = False ordering = None inlines = [] # Custom templates (designed to be over-ridden in subclasses) add_form_template = None change_form_template = None change_list_template = None delete_confirmation_template = None delete_selected_confirmation_template = None object_history_template = None # Actions actions = [] action_form = helpers.ActionForm actions_on_top = True actions_on_bottom = False actions_selection_counter = True def __init__(self, model, admin_site): self.model = model self.opts = model._meta self.admin_site = admin_site self.inline_instances = [] for inline_class in self.inlines: inline_instance = inline_class(self.model, self.admin_site) self.inline_instances.append(inline_instance) if 'action_checkbox' not in self.list_display and self.actions is not None: self.list_display = ['action_checkbox'] + list(self.list_display) if not self.list_display_links: for name in self.list_display: if name != 'action_checkbox': self.list_display_links = [name] break super(ModelAdmin, self).__init__() def get_urls(self): from django.conf.urls.defaults import patterns, url def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = self.model._meta.app_label, self.model._meta.module_name urlpatterns = patterns('', url(r'^$', wrap(self.changelist_view), name='%s_%s_changelist' % info), url(r'^add/$', wrap(self.add_view), name='%s_%s_add' % info), url(r'^(.+)/history/$', wrap(self.history_view), name='%s_%s_history' % info), url(r'^(.+)/delete/$', wrap(self.delete_view), name='%s_%s_delete' % info), url(r'^(.+)/$', wrap(self.change_view), name='%s_%s_change' % info), ) return urlpatterns def urls(self): return self.get_urls() urls = property(urls) def _media(self): from django.conf import settings js = ['js/core.js', 'js/admin/RelatedObjectLookups.js', 'js/jquery.min.js', 'js/jquery.init.js'] if self.actions is not None: js.extend(['js/actions.min.js']) if self.prepopulated_fields: js.append('js/urlify.js') js.append('js/prepopulate.min.js') if self.opts.get_ordered_objects(): js.extend(['js/getElementsBySelector.js', 'js/dom-drag.js' , 'js/admin/ordering.js']) return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js]) media = property(_media) def has_add_permission(self, request): """ Returns True if the given request has permission to add an object. Can be overriden by the user in subclasses. """ opts = self.opts return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission()) def has_change_permission(self, request, obj=None): """ Returns True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overriden by the user in subclasses. In such case it should return True if the given request has permission to change the `obj` model instance. If `obj` is None, this should return True if the given request has permission to change *any* object of the given type. """ opts = self.opts return request.user.has_perm(opts.app_label + '.' + opts.get_change_permission()) def has_delete_permission(self, request, obj=None): """ Returns True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overriden by the user in subclasses. In such case it should return True if the given request has permission to delete the `obj` model instance. If `obj` is None, this should return True if the given request has permission to delete *any* object of the given type. """ opts = self.opts return request.user.has_perm(opts.app_label + '.' + opts.get_delete_permission()) def get_model_perms(self, request): """ Returns a dict of all perms for this model. This dict has the keys ``add``, ``change``, and ``delete`` mapping to the True/False for each of those actions. """ return { 'add': self.has_add_permission(request), 'change': self.has_change_permission(request), 'delete': self.has_delete_permission(request), } def queryset(self, request): """ Returns a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view. """ qs = self.model._default_manager.get_query_set() # TODO: this should be handled by some parameter to the ChangeList. ordering = self.ordering or () # otherwise we might try to *None, which is bad ;) if ordering: qs = qs.order_by(*ordering) return qs def get_fieldsets(self, request, obj=None): "Hook for specifying fieldsets for the add form." if self.declared_fieldsets: return self.declared_fieldsets form = self.get_form(request, obj) fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj)) return [(None, {'fields': fields})] def get_form(self, request, obj=None, **kwargs): """ Returns a Form class for use in the admin add view. This is used by add_view and change_view. """ if self.declared_fieldsets: fields = flatten_fieldsets(self.declared_fieldsets) else: fields = None if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(kwargs.get("exclude", [])) exclude.extend(self.get_readonly_fields(request, obj)) # if exclude is an empty list we pass None to be consistant with the # default on modelform_factory exclude = exclude or None defaults = { "form": self.form, "fields": fields, "exclude": exclude, "formfield_callback": curry(self.formfield_for_dbfield, request=request), } defaults.update(kwargs) return modelform_factory(self.model, **defaults) def get_changelist(self, request, **kwargs): """ Returns the ChangeList class for use on the changelist page. """ from django.contrib.admin.views.main import ChangeList return ChangeList def get_object(self, request, object_id): """ Returns an instance matching the primary key provided. ``None`` is returned if no match is found (or the object_id failed validation against the primary key field). """ queryset = self.queryset(request) model = queryset.model try: object_id = model._meta.pk.to_python(object_id) return queryset.get(pk=object_id) except (model.DoesNotExist, ValidationError): return None def get_changelist_form(self, request, **kwargs): """ Returns a Form class for use in the Formset on the changelist page. """ defaults = { "formfield_callback": curry(self.formfield_for_dbfield, request=request), } defaults.update(kwargs) return modelform_factory(self.model, **defaults) def get_changelist_formset(self, request, **kwargs): """ Returns a FormSet class for use on the changelist page if list_editable is used. """ defaults = { "formfield_callback": curry(self.formfield_for_dbfield, request=request), } defaults.update(kwargs) return modelformset_factory(self.model, self.get_changelist_form(request), extra=0, fields=self.list_editable, **defaults) def get_formsets(self, request, obj=None): for inline in self.inline_instances: yield inline.get_formset(request, obj) def log_addition(self, request, object): """ Log that an object has been successfully added. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import LogEntry, ADDITION LogEntry.objects.log_action( user_id = request.user.pk, content_type_id = ContentType.objects.get_for_model(object).pk, object_id = object.pk, object_repr = force_unicode(object), action_flag = ADDITION ) def log_change(self, request, object, message): """ Log that an object has been successfully changed. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import LogEntry, CHANGE LogEntry.objects.log_action( user_id = request.user.pk, content_type_id = ContentType.objects.get_for_model(object).pk, object_id = object.pk, object_repr = force_unicode(object), action_flag = CHANGE, change_message = message ) def log_deletion(self, request, object, object_repr): """ Log that an object has been successfully deleted. Note that since the object is deleted, it might no longer be safe to call *any* methods on the object, hence this method getting object_repr. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import LogEntry, DELETION LogEntry.objects.log_action( user_id = request.user.id, content_type_id = ContentType.objects.get_for_model(self.model).pk, object_id = object.pk, object_repr = object_repr, action_flag = DELETION ) def action_checkbox(self, obj): """ A list_display column containing a checkbox widget. """ return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_unicode(obj.pk)) action_checkbox.short_description = mark_safe('<input type="checkbox" id="action-toggle" />') action_checkbox.allow_tags = True def get_actions(self, request): """ Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action. """ # If self.actions is explicitally set to None that means that we don't # want *any* actions enabled on this page. if self.actions is None: return SortedDict() actions = [] # Gather actions from the admin site first for (name, func) in self.admin_site.actions: description = getattr(func, 'short_description', name.replace('_', ' ')) actions.append((func, name, description)) # Then gather them from the model admin and all parent classes, # starting with self and working back up. for klass in self.__class__.mro()[::-1]: class_actions = getattr(klass, 'actions', []) # Avoid trying to iterate over None if not class_actions: continue actions.extend([self.get_action(action) for action in class_actions]) # get_action might have returned None, so filter any of those out. actions = filter(None, actions) # Convert the actions into a SortedDict keyed by name # and sorted by description. actions.sort(lambda a,b: cmp(a[2].lower(), b[2].lower())) actions = SortedDict([ (name, (func, name, desc)) for func, name, desc in actions ]) return actions def get_action_choices(self, request, default_choices=BLANK_CHOICE_DASH): """ Return a list of choices for use in a form object. Each choice is a tuple (name, description). """ choices = [] + default_choices for func, name, description in self.get_actions(request).itervalues(): choice = (name, description % model_format_dict(self.opts)) choices.append(choice) return choices def get_action(self, action): """ Return a given action from a parameter, which can either be a callable, or the name of a method on the ModelAdmin. Return is a tuple of (callable, name, description). """ # If the action is a callable, just use it. if callable(action): func = action action = action.__name__ # Next, look for a method. Grab it off self.__class__ to get an unbound # method instead of a bound one; this ensures that the calling # conventions are the same for functions and methods. elif hasattr(self.__class__, action): func = getattr(self.__class__, action) # Finally, look for a named method on the admin site else: try: func = self.admin_site.get_action(action) except KeyError: return None if hasattr(func, 'short_description'): description = func.short_description else: description = capfirst(action.replace('_', ' ')) return func, action, description def construct_change_message(self, request, form, formsets): """ Construct a change message from a changed object. """ change_message = [] if form.changed_data: change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and'))) if formsets: for formset in formsets: for added_object in formset.new_objects: change_message.append(_('Added %(name)s "%(object)s".') % {'name': force_unicode(added_object._meta.verbose_name), 'object': force_unicode(added_object)}) for changed_object, changed_fields in formset.changed_objects: change_message.append(_('Changed %(list)s for %(name)s "%(object)s".') % {'list': get_text_list(changed_fields, _('and')), 'name': force_unicode(changed_object._meta.verbose_name), 'object': force_unicode(changed_object)}) for deleted_object in formset.deleted_objects: change_message.append(_('Deleted %(name)s "%(object)s".') % {'name': force_unicode(deleted_object._meta.verbose_name), 'object': force_unicode(deleted_object)}) change_message = ' '.join(change_message) return change_message or _('No fields changed.') def message_user(self, request, message): """ Send a message to the user. The default implementation posts a message using the django.contrib.messages backend. """ messages.info(request, message) def save_form(self, request, form, change): """ Given a ModelForm return an unsaved instance. ``change`` is True if the object is being changed, and False if it's being added. """ return form.save(commit=False) def save_model(self, request, obj, form, change): """ Given a model instance save it to the database. """ obj.save() def save_formset(self, request, form, formset, change): """ Given an inline formset save it to the database. """ formset.save() def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): opts = self.model._meta app_label = opts.app_label ordered_objects = opts.get_ordered_objects() context.update({ 'add': add, 'change': change, 'has_add_permission': self.has_add_permission(request), 'has_change_permission': self.has_change_permission(request, obj), 'has_delete_permission': self.has_delete_permission(request, obj), 'has_file_field': True, # FIXME - this should check if form or formsets have a FileField, 'has_absolute_url': hasattr(self.model, 'get_absolute_url'), 'ordered_objects': ordered_objects, 'form_url': mark_safe(form_url), 'opts': opts, 'content_type_id': ContentType.objects.get_for_model(self.model).id, 'save_as': self.save_as, 'save_on_top': self.save_on_top, 'root_path': self.admin_site.root_path, }) if add and self.add_form_template is not None: form_template = self.add_form_template else: form_template = self.change_form_template context_instance = template.RequestContext(request, current_app=self.admin_site.name) return render_to_response(form_template or [ "admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()), "admin/%s/change_form.html" % app_label, "admin/change_form.html" ], context, context_instance=context_instance) def response_add(self, request, obj, post_url_continue='../%s/'): """ Determines the HttpResponse for the add_view stage. """ opts = obj._meta pk_value = obj._get_pk_val() msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)} # Here, we distinguish between different save types by checking for # the presence of keys in request.POST. if request.POST.has_key("_continue"): self.message_user(request, msg + ' ' + _("You may edit it again below.")) if request.POST.has_key("_popup"): post_url_continue += "?_popup=1" return HttpResponseRedirect(post_url_continue % pk_value) if request.POST.has_key("_popup"): return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \ # escape() calls force_unicode. (escape(pk_value), escapejs(obj))) elif request.POST.has_key("_addanother"): self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name))) return HttpResponseRedirect(request.path) else: self.message_user(request, msg) # Figure out where to redirect. If the user has change permission, # redirect to the change-list page for this object. Otherwise, # redirect to the admin index. if self.has_change_permission(request, None): post_url = '../' else: post_url = '../../../' return HttpResponseRedirect(post_url) def response_change(self, request, obj): """ Determines the HttpResponse for the change_view stage. """ opts = obj._meta pk_value = obj._get_pk_val() msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)} if request.POST.has_key("_continue"): self.message_user(request, msg + ' ' + _("You may edit it again below.")) if request.REQUEST.has_key('_popup'): return HttpResponseRedirect(request.path + "?_popup=1") else: return HttpResponseRedirect(request.path) elif request.POST.has_key("_saveasnew"): msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_unicode(opts.verbose_name), 'obj': obj} self.message_user(request, msg) return HttpResponseRedirect("../%s/" % pk_value) elif request.POST.has_key("_addanother"): self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name))) return HttpResponseRedirect("../add/") else: self.message_user(request, msg) return HttpResponseRedirect("../") def response_action(self, request, queryset): """ Handle an admin action. This is called if a request is POSTed to the changelist; it returns an HttpResponse if the action was handled, and None otherwise. """ # There can be multiple action forms on the page (at the top # and bottom of the change list, for example). Get the action # whose button was pushed. try: action_index = int(request.POST.get('index', 0)) except ValueError: action_index = 0 # Construct the action form. data = request.POST.copy() data.pop(helpers.ACTION_CHECKBOX_NAME, None) data.pop("index", None) # Use the action whose button was pushed try: data.update({'action': data.getlist('action')[action_index]}) except IndexError: # If we didn't get an action from the chosen form that's invalid # POST data, so by deleting action it'll fail the validation check # below. So no need to do anything here pass action_form = self.action_form(data, auto_id=None) action_form.fields['action'].choices = self.get_action_choices(request) # If the form's valid we can handle the action. if action_form.is_valid(): action = action_form.cleaned_data['action'] select_across = action_form.cleaned_data['select_across'] func, name, description = self.get_actions(request)[action] # Get the list of selected PKs. If nothing's selected, we can't # perform an action on it, so bail. Except we want to perform # the action explicitly on all objects. selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) if not selected and not select_across: # Reminder that something needs to be selected or nothing will happen msg = _("Items must be selected in order to perform " "actions on them. No items have been changed.") self.message_user(request, msg) return None if not select_across: # Perform the action only on the selected objects queryset = queryset.filter(pk__in=selected) response = func(self, request, queryset) # Actions may return an HttpResponse, which will be used as the # response from the POST. If not, we'll be a good little HTTP # citizen and redirect back to the changelist page. if isinstance(response, HttpResponse): return response else: return HttpResponseRedirect(request.get_full_path()) else: msg = _("No action selected.") self.message_user(request, msg) return None @csrf_protect_m @transaction.commit_on_success def add_view(self, request, form_url='', extra_context=None): "The 'add' admin view for this model." model = self.model opts = model._meta if not self.has_add_permission(request): raise PermissionDenied ModelForm = self.get_form(request) formsets = [] if request.method == 'POST': form = ModelForm(request.POST, request.FILES) if form.is_valid(): new_object = self.save_form(request, form, change=False) form_validated = True else: form_validated = False new_object = self.model() prefixes = {} for FormSet, inline in zip(self.get_formsets(request), self.inline_instances): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(data=request.POST, files=request.FILES, instance=new_object, save_as_new=request.POST.has_key("_saveasnew"), prefix=prefix, queryset=inline.queryset(request)) formsets.append(formset) if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, change=False) form.save_m2m() for formset in formsets: self.save_formset(request, form, formset, change=False) self.log_addition(request, new_object) return self.response_add(request, new_object) else: # Prepare the dict of initial data from the request. # We have to special-case M2Ms as a list of comma-separated PKs. initial = dict(request.GET.items()) for k in initial: try: f = opts.get_field(k) except models.FieldDoesNotExist: continue if isinstance(f, models.ManyToManyField): initial[k] = initial[k].split(",") form = ModelForm(initial=initial) prefixes = {} for FormSet, inline in zip(self.get_formsets(request), self.inline_instances): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(instance=self.model(), prefix=prefix, queryset=inline.queryset(request)) formsets.append(formset) adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)), self.prepopulated_fields, self.get_readonly_fields(request), model_admin=self) media = self.media + adminForm.media inline_admin_formsets = [] for inline, formset in zip(self.inline_instances, formsets): fieldsets = list(inline.get_fieldsets(request)) readonly = list(inline.get_readonly_fields(request)) inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets, readonly, model_admin=self) inline_admin_formsets.append(inline_admin_formset) media = media + inline_admin_formset.media context = { 'title': _('Add %s') % force_unicode(opts.verbose_name), 'adminform': adminForm, 'is_popup': request.REQUEST.has_key('_popup'), 'show_delete': False, 'media': mark_safe(media), 'inline_admin_formsets': inline_admin_formsets, 'errors': helpers.AdminErrorList(form, formsets), 'root_path': self.admin_site.root_path, 'app_label': opts.app_label, } context.update(extra_context or {}) return self.render_change_form(request, context, form_url=form_url, add=True) @csrf_protect_m @transaction.commit_on_success def change_view(self, request, object_id, extra_context=None): "The 'change' admin view for this model." model = self.model opts = model._meta obj = self.get_object(request, unquote(object_id)) if not self.has_change_permission(request, obj): raise PermissionDenied if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)}) if request.method == 'POST' and request.POST.has_key("_saveasnew"): return self.add_view(request, form_url='../add/') ModelForm = self.get_form(request, obj) formsets = [] if request.method == 'POST': form = ModelForm(request.POST, request.FILES, instance=obj) if form.is_valid(): form_validated = True new_object = self.save_form(request, form, change=True) else: form_validated = False new_object = obj prefixes = {} for FormSet, inline in zip(self.get_formsets(request, new_object), self.inline_instances): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(request.POST, request.FILES, instance=new_object, prefix=prefix, queryset=inline.queryset(request)) formsets.append(formset) if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, change=True) form.save_m2m() for formset in formsets: self.save_formset(request, form, formset, change=True) change_message = self.construct_change_message(request, form, formsets) self.log_change(request, new_object, change_message) return self.response_change(request, new_object) else: form = ModelForm(instance=obj) prefixes = {} for FormSet, inline in zip(self.get_formsets(request, obj), self.inline_instances): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(instance=obj, prefix=prefix, queryset=inline.queryset(request)) formsets.append(formset) adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields, self.get_readonly_fields(request, obj), model_admin=self) media = self.media + adminForm.media inline_admin_formsets = [] for inline, formset in zip(self.inline_instances, formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(inline.get_readonly_fields(request, obj)) inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets, readonly, model_admin=self) inline_admin_formsets.append(inline_admin_formset) media = media + inline_admin_formset.media context = { 'title': _('Change %s') % force_unicode(opts.verbose_name), 'adminform': adminForm, 'object_id': object_id, 'original': obj, 'is_popup': request.REQUEST.has_key('_popup'), 'media': mark_safe(media), 'inline_admin_formsets': inline_admin_formsets, 'errors': helpers.AdminErrorList(form, formsets), 'root_path': self.admin_site.root_path, 'app_label': opts.app_label, } context.update(extra_context or {}) return self.render_change_form(request, context, change=True, obj=obj) @csrf_protect_m def changelist_view(self, request, extra_context=None): "The 'change list' admin view for this model." from django.contrib.admin.views.main import ERROR_FLAG opts = self.model._meta app_label = opts.app_label if not self.has_change_permission(request, None): raise PermissionDenied # Check actions to see if any are available on this changelist actions = self.get_actions(request) # Remove action checkboxes if there aren't any actions available. list_display = list(self.list_display) if not actions: try: list_display.remove('action_checkbox') except ValueError: pass ChangeList = self.get_changelist(request) try: cl = ChangeList(request, self.model, list_display, self.list_display_links, self.list_filter, self.date_hierarchy, self.search_fields, self.list_select_related, self.list_per_page, self.list_editable, self) except IncorrectLookupParameters: # Wacky lookup parameters were given, so redirect to the main # changelist page, without parameters, and pass an 'invalid=1' # parameter via the query string. If wacky parameters were given # and the 'invalid=1' parameter was already in the query string, # something is screwed up with the database, so display an error # page. if ERROR_FLAG in request.GET.keys(): return render_to_response('admin/invalid_setup.html', {'title': _('Database error')}) return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1') # If the request was POSTed, this might be a bulk action or a bulk # edit. Try to look up an action or confirmation first, but if this # isn't an action the POST will fall through to the bulk edit check, # below. action_failed = False selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) # Actions with no confirmation if (actions and request.method == 'POST' and 'index' in request.POST and '_save' not in request.POST): if selected: response = self.response_action(request, queryset=cl.get_query_set()) if response: return response else: action_failed = True else: msg = _("Items must be selected in order to perform " "actions on them. No items have been changed.") self.message_user(request, msg) action_failed = True # Actions with confirmation if (actions and request.method == 'POST' and helpers.ACTION_CHECKBOX_NAME in request.POST and 'index' not in request.POST and '_save' not in request.POST): if selected: response = self.response_action(request, queryset=cl.get_query_set()) if response: return response else: action_failed = True # If we're allowing changelist editing, we need to construct a formset # for the changelist given all the fields to be edited. Then we'll # use the formset to validate/process POSTed data. formset = cl.formset = None # Handle POSTed bulk-edit data. if (request.method == "POST" and self.list_editable and '_save' in request.POST and not action_failed): FormSet = self.get_changelist_formset(request) formset = cl.formset = FormSet(request.POST, request.FILES, queryset=cl.result_list) if formset.is_valid(): changecount = 0 for form in formset.forms: if form.has_changed(): obj = self.save_form(request, form, change=True) self.save_model(request, obj, form, change=True) form.save_m2m() change_msg = self.construct_change_message(request, form, None) self.log_change(request, obj, change_msg) changecount += 1 if changecount: if changecount == 1: name = force_unicode(opts.verbose_name) else: name = force_unicode(opts.verbose_name_plural) msg = ungettext("%(count)s %(name)s was changed successfully.", "%(count)s %(name)s were changed successfully.", changecount) % {'count': changecount, 'name': name, 'obj': force_unicode(obj)} self.message_user(request, msg) return HttpResponseRedirect(request.get_full_path()) # Handle GET -- construct a formset for display. elif self.list_editable: FormSet = self.get_changelist_formset(request) formset = cl.formset = FormSet(queryset=cl.result_list) # Build the list of media to be used by the formset. if formset: media = self.media + formset.media else: media = self.media # Build the action form and populate it with available actions. if actions: action_form = self.action_form(auto_id=None) action_form.fields['action'].choices = self.get_action_choices(request) else: action_form = None selection_note_all = ungettext('%(total_count)s selected', 'All %(total_count)s selected', cl.result_count) context = { 'module_name': force_unicode(opts.verbose_name_plural), 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)}, 'selection_note_all': selection_note_all % {'total_count': cl.result_count}, 'title': cl.title, 'is_popup': cl.is_popup, 'cl': cl, 'media': media, 'has_add_permission': self.has_add_permission(request), 'root_path': self.admin_site.root_path, 'app_label': app_label, 'action_form': action_form, 'actions_on_top': self.actions_on_top, 'actions_on_bottom': self.actions_on_bottom, 'actions_selection_counter': self.actions_selection_counter, } context.update(extra_context or {}) context_instance = template.RequestContext(request, current_app=self.admin_site.name) return render_to_response(self.change_list_template or [ 'admin/%s/%s/change_list.html' % (app_label, opts.object_name.lower()), 'admin/%s/change_list.html' % app_label, 'admin/change_list.html' ], context, context_instance=context_instance) @csrf_protect_m def delete_view(self, request, object_id, extra_context=None): "The 'delete' admin view for this model." opts = self.model._meta app_label = opts.app_label obj = self.get_object(request, unquote(object_id)) if not self.has_delete_permission(request, obj): raise PermissionDenied if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)}) # Populate deleted_objects, a data structure of all related objects that # will also be deleted. (deleted_objects, perms_needed) = get_deleted_objects((obj,), opts, request.user, self.admin_site) if request.POST: # The user has already confirmed the deletion. if perms_needed: raise PermissionDenied obj_display = force_unicode(obj) self.log_deletion(request, obj, obj_display) obj.delete() self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj_display)}) if not self.has_change_permission(request, None): return HttpResponseRedirect("../../../../") return HttpResponseRedirect("../../") context = { "title": _("Are you sure?"), "object_name": force_unicode(opts.verbose_name), "object": obj, "deleted_objects": deleted_objects, "perms_lacking": perms_needed, "opts": opts, "root_path": self.admin_site.root_path, "app_label": app_label, } context.update(extra_context or {}) context_instance = template.RequestContext(request, current_app=self.admin_site.name) return render_to_response(self.delete_confirmation_template or [ "admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()), "admin/%s/delete_confirmation.html" % app_label, "admin/delete_confirmation.html" ], context, context_instance=context_instance) def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry model = self.model opts = model._meta app_label = opts.app_label action_list = LogEntry.objects.filter( object_id = object_id, content_type__id__exact = ContentType.objects.get_for_model(model).id ).select_related().order_by('action_time') # If no history was found, see whether this object even exists. obj = get_object_or_404(model, pk=unquote(object_id)) context = { 'title': _('Change history: %s') % force_unicode(obj), 'action_list': action_list, 'module_name': capfirst(force_unicode(opts.verbose_name_plural)), 'object': obj, 'root_path': self.admin_site.root_path, 'app_label': app_label, } context.update(extra_context or {}) context_instance = template.RequestContext(request, current_app=self.admin_site.name) return render_to_response(self.object_history_template or [ "admin/%s/%s/object_history.html" % (app_label, opts.object_name.lower()), "admin/%s/object_history.html" % app_label, "admin/object_history.html" ], context, context_instance=context_instance) # # DEPRECATED methods. # def __call__(self, request, url): """ DEPRECATED: this is the old way of URL resolution, replaced by ``get_urls()``. This only called by AdminSite.root(), which is also deprecated. Again, remember that the following code only exists for backwards-compatibility. Any new URLs, changes to existing URLs, or whatever need to be done up in get_urls(), above! This function still exists for backwards-compatibility; it will be removed in Django 1.3. """ # Delegate to the appropriate method, based on the URL. if url is None: return self.changelist_view(request) elif url == "add": return self.add_view(request) elif url.endswith('/history'): return self.history_view(request, unquote(url[:-8])) elif url.endswith('/delete'): return self.delete_view(request, unquote(url[:-7])) else: return self.change_view(request, unquote(url)) class InlineModelAdmin(BaseModelAdmin): """ Options for inline editing of ``model`` instances. Provide ``name`` to specify the attribute name of the ``ForeignKey`` from ``model`` to its parent. This is required if ``model`` has more than one ``ForeignKey`` to its parent. """ model = None fk_name = None formset = BaseInlineFormSet extra = 3 max_num = None template = None verbose_name = None verbose_name_plural = None can_delete = True def __init__(self, parent_model, admin_site): self.admin_site = admin_site self.parent_model = parent_model self.opts = self.model._meta super(InlineModelAdmin, self).__init__() if self.verbose_name is None: self.verbose_name = self.model._meta.verbose_name if self.verbose_name_plural is None: self.verbose_name_plural = self.model._meta.verbose_name_plural def _media(self): from django.conf import settings js = ['js/jquery.min.js', 'js/jquery.init.js', 'js/inlines.min.js'] if self.prepopulated_fields: js.append('js/urlify.js') js.append('js/prepopulate.min.js') if self.filter_vertical or self.filter_horizontal: js.extend(['js/SelectBox.js' , 'js/SelectFilter2.js']) return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js]) media = property(_media) def get_formset(self, request, obj=None, **kwargs): """Returns a BaseInlineFormSet class for use in admin add/change views.""" if self.declared_fieldsets: fields = flatten_fieldsets(self.declared_fieldsets) else: fields = None if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(kwargs.get("exclude", [])) exclude.extend(self.get_readonly_fields(request, obj)) # if exclude is an empty list we use None, since that's the actual # default exclude = exclude or None defaults = { "form": self.form, "formset": self.formset, "fk_name": self.fk_name, "fields": fields, "exclude": exclude, "formfield_callback": curry(self.formfield_for_dbfield, request=request), "extra": self.extra, "max_num": self.max_num, "can_delete": self.can_delete, } defaults.update(kwargs) return inlineformset_factory(self.parent_model, self.model, **defaults) def get_fieldsets(self, request, obj=None): if self.declared_fieldsets: return self.declared_fieldsets form = self.get_formset(request).form fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj)) return [(None, {'fields': fields})] def queryset(self, request): return self.model._default_manager.all() class StackedInline(InlineModelAdmin): template = 'admin/edit_inline/stacked.html' class TabularInline(InlineModelAdmin): template = 'admin/edit_inline/tabular.html'
57,800
Python
.py
1,181
37.637595
173
0.604283
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,835
sites.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/sites.py
import re from django import http, template from django.contrib.admin import ModelAdmin from django.contrib.admin import actions from django.contrib.auth import authenticate, login from django.views.decorators.csrf import csrf_protect from django.db.models.base import ModelBase from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse from django.shortcuts import render_to_response from django.utils.functional import update_wrapper from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext_lazy, ugettext as _ from django.views.decorators.cache import never_cache from django.conf import settings ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.") LOGIN_FORM_KEY = 'this_is_the_login_form' class AlreadyRegistered(Exception): pass class NotRegistered(Exception): pass class AdminSite(object): """ An AdminSite object encapsulates an instance of the Django admin application, ready to be hooked in to your URLconf. Models are registered with the AdminSite using the register() method, and the root() method can then be used as a Django view function that presents a full admin interface for the collection of registered models. """ index_template = None app_index_template = None login_template = None logout_template = None password_change_template = None password_change_done_template = None def __init__(self, name=None, app_name='admin'): self._registry = {} # model_class class -> admin_class instance self.root_path = None if name is None: self.name = 'admin' else: self.name = name self.app_name = app_name self._actions = {'delete_selected': actions.delete_selected} self._global_actions = self._actions.copy() def register(self, model_or_iterable, admin_class=None, **options): """ Registers the given model(s) with the given admin class. The model(s) should be Model classes, not instances. If an admin class isn't given, it will use ModelAdmin (the default admin options). If keyword arguments are given -- e.g., list_display -- they'll be applied as options to the admin class. If a model is already registered, this will raise AlreadyRegistered. """ if not admin_class: admin_class = ModelAdmin # Don't import the humongous validation code unless required if admin_class and settings.DEBUG: from django.contrib.admin.validation import validate else: validate = lambda model, adminclass: None if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model in self._registry: raise AlreadyRegistered('The model %s is already registered' % model.__name__) # If we got **options then dynamically construct a subclass of # admin_class with those **options. if options: # For reasons I don't quite understand, without a __module__ # the created class appears to "live" in the wrong place, # which causes issues later on. options['__module__'] = __name__ admin_class = type("%sAdmin" % model.__name__, (admin_class,), options) # Validate (which might be a no-op) validate(admin_class, model) # Instantiate the admin class to save in the registry self._registry[model] = admin_class(model, self) def unregister(self, model_or_iterable): """ Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered. """ if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model not in self._registry: raise NotRegistered('The model %s is not registered' % model.__name__) del self._registry[model] def add_action(self, action, name=None): """ Register an action to be available globally. """ name = name or action.__name__ self._actions[name] = action self._global_actions[name] = action def disable_action(self, name): """ Disable a globally-registered action. Raises KeyError for invalid names. """ del self._actions[name] def get_action(self, name): """ Explicitally get a registered global action wheather it's enabled or not. Raises KeyError for invalid names. """ return self._global_actions[name] def actions(self): """ Get all the enabled actions as an iterable of (name, func). """ return self._actions.iteritems() actions = property(actions) def has_permission(self, request): """ Returns True if the given HttpRequest has permission to view *at least one* page in the admin site. """ return request.user.is_active and request.user.is_staff def check_dependencies(self): """ Check that all things needed to run the admin have been correctly installed. The default implementation checks that LogEntry, ContentType and the auth context processor are installed. """ from django.contrib.admin.models import LogEntry from django.contrib.contenttypes.models import ContentType if not LogEntry._meta.installed: raise ImproperlyConfigured("Put 'django.contrib.admin' in your " "INSTALLED_APPS setting in order to use the admin application.") if not ContentType._meta.installed: raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in " "your INSTALLED_APPS setting in order to use the admin application.") if not ('django.contrib.auth.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS or 'django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS): raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' " "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.") def admin_view(self, view, cacheable=False): """ Decorator to create an admin view attached to this ``AdminSite``. This wraps the view and provides permission checking by calling ``self.has_permission``. You'll want to use this from within ``AdminSite.get_urls()``: class MyAdminSite(AdminSite): def get_urls(self): from django.conf.urls.defaults import patterns, url urls = super(MyAdminSite, self).get_urls() urls += patterns('', url(r'^my_view/$', self.admin_view(some_view)) ) return urls By default, admin_views are marked non-cacheable using the ``never_cache`` decorator. If the view can be safely cached, set cacheable=True. """ def inner(request, *args, **kwargs): if not self.has_permission(request): return self.login(request) return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view) def get_urls(self): from django.conf.urls.defaults import patterns, url, include if settings.DEBUG: self.check_dependencies() def wrap(view, cacheable=False): def wrapper(*args, **kwargs): return self.admin_view(view, cacheable)(*args, **kwargs) return update_wrapper(wrapper, view) # Admin-site-wide views. urlpatterns = patterns('', url(r'^$', wrap(self.index), name='index'), url(r'^logout/$', wrap(self.logout), name='logout'), url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'), url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True), name='password_change_done'), url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'), url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$', 'django.views.defaults.shortcut'), url(r'^(?P<app_label>\w+)/$', wrap(self.app_index), name='app_list') ) # Add in each model's views. for model, model_admin in self._registry.iteritems(): urlpatterns += patterns('', url(r'^%s/%s/' % (model._meta.app_label, model._meta.module_name), include(model_admin.urls)) ) return urlpatterns def urls(self): return self.get_urls(), self.app_name, self.name urls = property(urls) def password_change(self, request): """ Handles the "change password" task -- both form display and validation. """ from django.contrib.auth.views import password_change if self.root_path is not None: url = '%spassword_change/done/' % self.root_path else: url = reverse('admin:password_change_done', current_app=self.name) defaults = { 'post_change_redirect': url } if self.password_change_template is not None: defaults['template_name'] = self.password_change_template return password_change(request, **defaults) def password_change_done(self, request): """ Displays the "success" page after a password change. """ from django.contrib.auth.views import password_change_done defaults = {} if self.password_change_done_template is not None: defaults['template_name'] = self.password_change_done_template return password_change_done(request, **defaults) def i18n_javascript(self, request): """ Displays the i18n JavaScript that the Django admin requires. This takes into account the USE_I18N setting. If it's set to False, the generated JavaScript will be leaner and faster. """ if settings.USE_I18N: from django.views.i18n import javascript_catalog else: from django.views.i18n import null_javascript_catalog as javascript_catalog return javascript_catalog(request, packages='django.conf') def logout(self, request): """ Logs out the user for the given HttpRequest. This should *not* assume the user is already logged in. """ from django.contrib.auth.views import logout defaults = {} if self.logout_template is not None: defaults['template_name'] = self.logout_template return logout(request, **defaults) logout = never_cache(logout) def login(self, request): """ Displays the login form for the given HttpRequest. """ from django.contrib.auth.models import User # If this isn't already the login page, display it. if not request.POST.has_key(LOGIN_FORM_KEY): if request.POST: message = _("Please log in again, because your session has expired.") else: message = "" return self.display_login_form(request, message) # Check that the user accepts cookies. if not request.session.test_cookie_worked(): message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.") return self.display_login_form(request, message) else: request.session.delete_test_cookie() # Check the password. username = request.POST.get('username', None) password = request.POST.get('password', None) user = authenticate(username=username, password=password) if user is None: message = ERROR_MESSAGE if username is not None and u'@' in username: # Mistakenly entered e-mail address instead of username? Look it up. try: user = User.objects.get(email=username) except (User.DoesNotExist, User.MultipleObjectsReturned): pass else: if user.check_password(password): message = _("Your e-mail address is not your username." " Try '%s' instead.") % user.username return self.display_login_form(request, message) # The user data is correct; log in the user in and continue. else: if user.is_active and user.is_staff: login(request, user) return http.HttpResponseRedirect(request.get_full_path()) else: return self.display_login_form(request, ERROR_MESSAGE) login = never_cache(login) def index(self, request, extra_context=None): """ Displays the main admin index page, which lists all of the installed apps that have been registered in this site. """ app_dict = {} user = request.user for model, model_admin in self._registry.items(): app_label = model._meta.app_label has_module_perms = user.has_module_perms(app_label) if has_module_perms: perms = model_admin.get_model_perms(request) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True in perms.values(): model_dict = { 'name': capfirst(model._meta.verbose_name_plural), 'admin_url': mark_safe('%s/%s/' % (app_label, model.__name__.lower())), 'perms': perms, } if app_label in app_dict: app_dict[app_label]['models'].append(model_dict) else: app_dict[app_label] = { 'name': app_label.title(), 'app_url': app_label + '/', 'has_module_perms': has_module_perms, 'models': [model_dict], } # Sort the apps alphabetically. app_list = app_dict.values() app_list.sort(lambda x, y: cmp(x['name'], y['name'])) # Sort the models alphabetically within each app. for app in app_list: app['models'].sort(lambda x, y: cmp(x['name'], y['name'])) context = { 'title': _('Site administration'), 'app_list': app_list, 'root_path': self.root_path, } context.update(extra_context or {}) context_instance = template.RequestContext(request, current_app=self.name) return render_to_response(self.index_template or 'admin/index.html', context, context_instance=context_instance ) index = never_cache(index) def display_login_form(self, request, error_message='', extra_context=None): request.session.set_test_cookie() context = { 'title': _('Log in'), 'app_path': request.get_full_path(), 'error_message': error_message, 'root_path': self.root_path, } context.update(extra_context or {}) context_instance = template.RequestContext(request, current_app=self.name) return render_to_response(self.login_template or 'admin/login.html', context, context_instance=context_instance ) def app_index(self, request, app_label, extra_context=None): user = request.user has_module_perms = user.has_module_perms(app_label) app_dict = {} for model, model_admin in self._registry.items(): if app_label == model._meta.app_label: if has_module_perms: perms = model_admin.get_model_perms(request) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True in perms.values(): model_dict = { 'name': capfirst(model._meta.verbose_name_plural), 'admin_url': '%s/' % model.__name__.lower(), 'perms': perms, } if app_dict: app_dict['models'].append(model_dict), else: # First time around, now that we know there's # something to display, add in the necessary meta # information. app_dict = { 'name': app_label.title(), 'app_url': '', 'has_module_perms': has_module_perms, 'models': [model_dict], } if not app_dict: raise http.Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(lambda x, y: cmp(x['name'], y['name'])) context = { 'title': _('%s administration') % capfirst(app_label), 'app_list': [app_dict], 'root_path': self.root_path, } context.update(extra_context or {}) context_instance = template.RequestContext(request, current_app=self.name) return render_to_response(self.app_index_template or ('admin/%s/app_index.html' % app_label, 'admin/app_index.html'), context, context_instance=context_instance ) def root(self, request, url): """ DEPRECATED. This function is the old way of handling URL resolution, and is deprecated in favor of real URL resolution -- see ``get_urls()``. This function still exists for backwards-compatibility; it will be removed in Django 1.3. """ import warnings warnings.warn( "AdminSite.root() is deprecated; use include(admin.site.urls) instead.", DeprecationWarning ) # # Again, remember that the following only exists for # backwards-compatibility. Any new URLs, changes to existing URLs, or # whatever need to be done up in get_urls(), above! # if request.method == 'GET' and not request.path.endswith('/'): return http.HttpResponseRedirect(request.path + '/') if settings.DEBUG: self.check_dependencies() # Figure out the admin base URL path and stash it for later use self.root_path = re.sub(re.escape(url) + '$', '', request.path) url = url.rstrip('/') # Trim trailing slash, if it exists. # The 'logout' view doesn't require that the person is logged in. if url == 'logout': return self.logout(request) # Check permission to continue or display login form. if not self.has_permission(request): return self.login(request) if url == '': return self.index(request) elif url == 'password_change': return self.password_change(request) elif url == 'password_change/done': return self.password_change_done(request) elif url == 'jsi18n': return self.i18n_javascript(request) # URLs starting with 'r/' are for the "View on site" links. elif url.startswith('r/'): from django.contrib.contenttypes.views import shortcut return shortcut(request, *url.split('/')[1:]) else: if '/' in url: return self.model_page(request, *url.split('/', 2)) else: return self.app_index(request, url) raise http.Http404('The requested admin page does not exist.') def model_page(self, request, app_label, model_name, rest_of_url=None): """ DEPRECATED. This is the old way of handling a model view on the admin site; the new views should use get_urls(), above. """ from django.db import models model = models.get_model(app_label, model_name) if model is None: raise http.Http404("App %r, model %r, not found." % (app_label, model_name)) try: admin_obj = self._registry[model] except KeyError: raise http.Http404("This model exists but has not been registered with the admin site.") return admin_obj(request, rest_of_url) model_page = never_cache(model_page) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site. site = AdminSite()
21,836
Python
.py
464
35.452586
142
0.596564
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,836
filterspecs.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/filterspecs.py
""" FilterSpec encapsulates the logic for displaying filters in the Django admin. Filters are specified in models with the "list_filter" option. Each filter subclass knows how to display a filter for a field that passes a certain test -- e.g. being a DateField or ForeignKey. """ from django.db import models from django.utils.encoding import smart_unicode, iri_to_uri from django.utils.translation import ugettext as _ from django.utils.html import escape from django.utils.safestring import mark_safe import datetime class FilterSpec(object): filter_specs = [] def __init__(self, f, request, params, model, model_admin): self.field = f self.params = params def register(cls, test, factory): cls.filter_specs.append((test, factory)) register = classmethod(register) def create(cls, f, request, params, model, model_admin): for test, factory in cls.filter_specs: if test(f): return factory(f, request, params, model, model_admin) create = classmethod(create) def has_output(self): return True def choices(self, cl): raise NotImplementedError() def title(self): return self.field.verbose_name def output(self, cl): t = [] if self.has_output(): t.append(_(u'<h3>By %s:</h3>\n<ul>\n') % escape(self.title())) for choice in self.choices(cl): t.append(u'<li%s><a href="%s">%s</a></li>\n' % \ ((choice['selected'] and ' class="selected"' or ''), iri_to_uri(choice['query_string']), choice['display'])) t.append('</ul>\n\n') return mark_safe("".join(t)) class RelatedFilterSpec(FilterSpec): def __init__(self, f, request, params, model, model_admin): super(RelatedFilterSpec, self).__init__(f, request, params, model, model_admin) if isinstance(f, models.ManyToManyField): self.lookup_title = f.rel.to._meta.verbose_name else: self.lookup_title = f.verbose_name rel_name = f.rel.get_related_field().name self.lookup_kwarg = '%s__%s__exact' % (f.name, rel_name) self.lookup_val = request.GET.get(self.lookup_kwarg, None) self.lookup_choices = f.get_choices(include_blank=False) def has_output(self): return len(self.lookup_choices) > 1 def title(self): return self.lookup_title def choices(self, cl): yield {'selected': self.lookup_val is None, 'query_string': cl.get_query_string({}, [self.lookup_kwarg]), 'display': _('All')} for pk_val, val in self.lookup_choices: yield {'selected': self.lookup_val == smart_unicode(pk_val), 'query_string': cl.get_query_string({self.lookup_kwarg: pk_val}), 'display': val} FilterSpec.register(lambda f: bool(f.rel), RelatedFilterSpec) class ChoicesFilterSpec(FilterSpec): def __init__(self, f, request, params, model, model_admin): super(ChoicesFilterSpec, self).__init__(f, request, params, model, model_admin) self.lookup_kwarg = '%s__exact' % f.name self.lookup_val = request.GET.get(self.lookup_kwarg, None) def choices(self, cl): yield {'selected': self.lookup_val is None, 'query_string': cl.get_query_string({}, [self.lookup_kwarg]), 'display': _('All')} for k, v in self.field.flatchoices: yield {'selected': smart_unicode(k) == self.lookup_val, 'query_string': cl.get_query_string({self.lookup_kwarg: k}), 'display': v} FilterSpec.register(lambda f: bool(f.choices), ChoicesFilterSpec) class DateFieldFilterSpec(FilterSpec): def __init__(self, f, request, params, model, model_admin): super(DateFieldFilterSpec, self).__init__(f, request, params, model, model_admin) self.field_generic = '%s__' % self.field.name self.date_params = dict([(k, v) for k, v in params.items() if k.startswith(self.field_generic)]) today = datetime.date.today() one_week_ago = today - datetime.timedelta(days=7) today_str = isinstance(self.field, models.DateTimeField) and today.strftime('%Y-%m-%d 23:59:59') or today.strftime('%Y-%m-%d') self.links = ( (_('Any date'), {}), (_('Today'), {'%s__year' % self.field.name: str(today.year), '%s__month' % self.field.name: str(today.month), '%s__day' % self.field.name: str(today.day)}), (_('Past 7 days'), {'%s__gte' % self.field.name: one_week_ago.strftime('%Y-%m-%d'), '%s__lte' % f.name: today_str}), (_('This month'), {'%s__year' % self.field.name: str(today.year), '%s__month' % f.name: str(today.month)}), (_('This year'), {'%s__year' % self.field.name: str(today.year)}) ) def title(self): return self.field.verbose_name def choices(self, cl): for title, param_dict in self.links: yield {'selected': self.date_params == param_dict, 'query_string': cl.get_query_string(param_dict, [self.field_generic]), 'display': title} FilterSpec.register(lambda f: isinstance(f, models.DateField), DateFieldFilterSpec) class BooleanFieldFilterSpec(FilterSpec): def __init__(self, f, request, params, model, model_admin): super(BooleanFieldFilterSpec, self).__init__(f, request, params, model, model_admin) self.lookup_kwarg = '%s__exact' % f.name self.lookup_kwarg2 = '%s__isnull' % f.name self.lookup_val = request.GET.get(self.lookup_kwarg, None) self.lookup_val2 = request.GET.get(self.lookup_kwarg2, None) def title(self): return self.field.verbose_name def choices(self, cl): for k, v in ((_('All'), None), (_('Yes'), '1'), (_('No'), '0')): yield {'selected': self.lookup_val == v and not self.lookup_val2, 'query_string': cl.get_query_string({self.lookup_kwarg: v}, [self.lookup_kwarg2]), 'display': k} if isinstance(self.field, models.NullBooleanField): yield {'selected': self.lookup_val2 == 'True', 'query_string': cl.get_query_string({self.lookup_kwarg2: 'True'}, [self.lookup_kwarg]), 'display': _('Unknown')} FilterSpec.register(lambda f: isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField), BooleanFieldFilterSpec) # This should be registered last, because it's a last resort. For example, # if a field is eligible to use the BooleanFieldFilterSpec, that'd be much # more appropriate, and the AllValuesFilterSpec won't get used for it. class AllValuesFilterSpec(FilterSpec): def __init__(self, f, request, params, model, model_admin): super(AllValuesFilterSpec, self).__init__(f, request, params, model, model_admin) self.lookup_val = request.GET.get(f.name, None) self.lookup_choices = model_admin.queryset(request).distinct().order_by(f.name).values(f.name) def title(self): return self.field.verbose_name def choices(self, cl): yield {'selected': self.lookup_val is None, 'query_string': cl.get_query_string({}, [self.field.name]), 'display': _('All')} for val in self.lookup_choices: val = smart_unicode(val[self.field.name]) yield {'selected': self.lookup_val == val, 'query_string': cl.get_query_string({self.field.name: val}), 'display': val} FilterSpec.register(lambda f: True, AllValuesFilterSpec)
7,767
Python
.py
146
43.520548
134
0.613205
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,837
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/__init__.py
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL from django.contrib.admin.options import StackedInline, TabularInline from django.contrib.admin.sites import AdminSite, site def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. This forces an import on them to register any admin bits they may want. """ import copy from django.conf import settings from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule for app in settings.INSTALLED_APPS: mod = import_module(app) # Attempt to import the app's admin module. try: before_import_registry = copy.copy(site._registry) import_module('%s.admin' % app) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions # (see #8245). site._registry = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have an admin module, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(mod, 'admin'): raise
1,491
Python
.py
31
39.83871
78
0.690722
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,838
validation.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/validation.py
from django.core.exceptions import ImproperlyConfigured from django.db import models from django.forms.models import (BaseModelForm, BaseModelFormSet, fields_for_model, _get_foreign_key) from django.contrib.admin.options import flatten_fieldsets, BaseModelAdmin from django.contrib.admin.options import HORIZONTAL, VERTICAL from django.contrib.admin.util import lookup_field __all__ = ['validate'] def validate(cls, model): """ Does basic ModelAdmin option validation. Calls custom validation classmethod in the end if it is provided in cls. The signature of the custom validation classmethod should be: def validate(cls, model). """ # Before we can introspect models, they need to be fully loaded so that # inter-relations are set up correctly. We force that here. models.get_apps() opts = model._meta validate_base(cls, model) # list_display if hasattr(cls, 'list_display'): check_isseq(cls, 'list_display', cls.list_display) for idx, field in enumerate(cls.list_display): if not callable(field): if not hasattr(cls, field): if not hasattr(model, field): try: opts.get_field(field) except models.FieldDoesNotExist: raise ImproperlyConfigured("%s.list_display[%d], %r is not a callable or an attribute of %r or found in the model %r." % (cls.__name__, idx, field, cls.__name__, model._meta.object_name)) else: # getattr(model, field) could be an X_RelatedObjectsDescriptor f = fetch_attr(cls, model, opts, "list_display[%d]" % idx, field) if isinstance(f, models.ManyToManyField): raise ImproperlyConfigured("'%s.list_display[%d]', '%s' is a ManyToManyField which is not supported." % (cls.__name__, idx, field)) # list_display_links if hasattr(cls, 'list_display_links'): check_isseq(cls, 'list_display_links', cls.list_display_links) for idx, field in enumerate(cls.list_display_links): fetch_attr(cls, model, opts, 'list_display_links[%d]' % idx, field) if field not in cls.list_display: raise ImproperlyConfigured("'%s.list_display_links[%d]'" "refers to '%s' which is not defined in 'list_display'." % (cls.__name__, idx, field)) # list_filter if hasattr(cls, 'list_filter'): check_isseq(cls, 'list_filter', cls.list_filter) for idx, field in enumerate(cls.list_filter): get_field(cls, model, opts, 'list_filter[%d]' % idx, field) # list_per_page = 100 if hasattr(cls, 'list_per_page') and not isinstance(cls.list_per_page, int): raise ImproperlyConfigured("'%s.list_per_page' should be a integer." % cls.__name__) # list_editable if hasattr(cls, 'list_editable') and cls.list_editable: check_isseq(cls, 'list_editable', cls.list_editable) for idx, field_name in enumerate(cls.list_editable): try: field = opts.get_field_by_name(field_name)[0] except models.FieldDoesNotExist: raise ImproperlyConfigured("'%s.list_editable[%d]' refers to a " "field, '%s', not defined on %s." % (cls.__name__, idx, field_name, model.__name__)) if field_name not in cls.list_display: raise ImproperlyConfigured("'%s.list_editable[%d]' refers to " "'%s' which is not defined in 'list_display'." % (cls.__name__, idx, field_name)) if field_name in cls.list_display_links: raise ImproperlyConfigured("'%s' cannot be in both '%s.list_editable'" " and '%s.list_display_links'" % (field_name, cls.__name__, cls.__name__)) if not cls.list_display_links and cls.list_display[0] in cls.list_editable: raise ImproperlyConfigured("'%s.list_editable[%d]' refers to" " the first field in list_display, '%s', which can't be" " used unless list_display_links is set." % (cls.__name__, idx, cls.list_display[0])) if not field.editable: raise ImproperlyConfigured("'%s.list_editable[%d]' refers to a " "field, '%s', which isn't editable through the admin." % (cls.__name__, idx, field_name)) # search_fields = () if hasattr(cls, 'search_fields'): check_isseq(cls, 'search_fields', cls.search_fields) # date_hierarchy = None if cls.date_hierarchy: f = get_field(cls, model, opts, 'date_hierarchy', cls.date_hierarchy) if not isinstance(f, (models.DateField, models.DateTimeField)): raise ImproperlyConfigured("'%s.date_hierarchy is " "neither an instance of DateField nor DateTimeField." % cls.__name__) # ordering = None if cls.ordering: check_isseq(cls, 'ordering', cls.ordering) for idx, field in enumerate(cls.ordering): if field == '?' and len(cls.ordering) != 1: raise ImproperlyConfigured("'%s.ordering' has the random " "ordering marker '?', but contains other fields as " "well. Please either remove '?' or the other fields." % cls.__name__) if field == '?': continue if field.startswith('-'): field = field[1:] # Skip ordering in the format field1__field2 (FIXME: checking # this format would be nice, but it's a little fiddly). if '__' in field: continue get_field(cls, model, opts, 'ordering[%d]' % idx, field) if hasattr(cls, "readonly_fields"): check_isseq(cls, "readonly_fields", cls.readonly_fields) for idx, field in enumerate(cls.readonly_fields): if not callable(field): if not hasattr(cls, field): if not hasattr(model, field): try: opts.get_field(field) except models.FieldDoesNotExist: raise ImproperlyConfigured("%s.readonly_fields[%d], %r is not a callable or an attribute of %r or found in the model %r." % (cls.__name__, idx, field, cls.__name__, model._meta.object_name)) # list_select_related = False # save_as = False # save_on_top = False for attr in ('list_select_related', 'save_as', 'save_on_top'): if not isinstance(getattr(cls, attr), bool): raise ImproperlyConfigured("'%s.%s' should be a boolean." % (cls.__name__, attr)) # inlines = [] if hasattr(cls, 'inlines'): check_isseq(cls, 'inlines', cls.inlines) for idx, inline in enumerate(cls.inlines): if not issubclass(inline, BaseModelAdmin): raise ImproperlyConfigured("'%s.inlines[%d]' does not inherit " "from BaseModelAdmin." % (cls.__name__, idx)) if not inline.model: raise ImproperlyConfigured("'model' is a required attribute " "of '%s.inlines[%d]'." % (cls.__name__, idx)) if not issubclass(inline.model, models.Model): raise ImproperlyConfigured("'%s.inlines[%d].model' does not " "inherit from models.Model." % (cls.__name__, idx)) validate_base(inline, inline.model) validate_inline(inline, cls, model) def validate_inline(cls, parent, parent_model): # model is already verified to exist and be a Model if cls.fk_name: # default value is None f = get_field(cls, cls.model, cls.model._meta, 'fk_name', cls.fk_name) if not isinstance(f, models.ForeignKey): raise ImproperlyConfigured("'%s.fk_name is not an instance of " "models.ForeignKey." % cls.__name__) fk = _get_foreign_key(parent_model, cls.model, fk_name=cls.fk_name, can_fail=True) # extra = 3 if not isinstance(getattr(cls, 'extra'), int): raise ImproperlyConfigured("'%s.extra' should be a integer." % cls.__name__) # max_num = None max_num = getattr(cls, 'max_num', None) if max_num is not None and not isinstance(max_num, int): raise ImproperlyConfigured("'%s.max_num' should be an integer or None (default)." % cls.__name__) # formset if hasattr(cls, 'formset') and not issubclass(cls.formset, BaseModelFormSet): raise ImproperlyConfigured("'%s.formset' does not inherit from " "BaseModelFormSet." % cls.__name__) # exclude if hasattr(cls, 'exclude') and cls.exclude: if fk and fk.name in cls.exclude: raise ImproperlyConfigured("%s cannot exclude the field " "'%s' - this is the foreign key to the parent model " "%s." % (cls.__name__, fk.name, parent_model.__name__)) def validate_base(cls, model): opts = model._meta # raw_id_fields if hasattr(cls, 'raw_id_fields'): check_isseq(cls, 'raw_id_fields', cls.raw_id_fields) for idx, field in enumerate(cls.raw_id_fields): f = get_field(cls, model, opts, 'raw_id_fields', field) if not isinstance(f, (models.ForeignKey, models.ManyToManyField)): raise ImproperlyConfigured("'%s.raw_id_fields[%d]', '%s' must " "be either a ForeignKey or ManyToManyField." % (cls.__name__, idx, field)) # fields if cls.fields: # default value is None check_isseq(cls, 'fields', cls.fields) for field in cls.fields: if field in cls.readonly_fields: # Stuff can be put in fields that isn't actually a model field # if it's in readonly_fields, readonly_fields will handle the # validation of such things. continue check_formfield(cls, model, opts, 'fields', field) try: f = opts.get_field(field) except models.FieldDoesNotExist: # If we can't find a field on the model that matches, # it could be an extra field on the form. continue if isinstance(f, models.ManyToManyField) and not f.rel.through._meta.auto_created: raise ImproperlyConfigured("'%s.fields' can't include the ManyToManyField " "field '%s' because '%s' manually specifies " "a 'through' model." % (cls.__name__, field, field)) if cls.fieldsets: raise ImproperlyConfigured('Both fieldsets and fields are specified in %s.' % cls.__name__) if len(cls.fields) > len(set(cls.fields)): raise ImproperlyConfigured('There are duplicate field(s) in %s.fields' % cls.__name__) # fieldsets if cls.fieldsets: # default value is None check_isseq(cls, 'fieldsets', cls.fieldsets) for idx, fieldset in enumerate(cls.fieldsets): check_isseq(cls, 'fieldsets[%d]' % idx, fieldset) if len(fieldset) != 2: raise ImproperlyConfigured("'%s.fieldsets[%d]' does not " "have exactly two elements." % (cls.__name__, idx)) check_isdict(cls, 'fieldsets[%d][1]' % idx, fieldset[1]) if 'fields' not in fieldset[1]: raise ImproperlyConfigured("'fields' key is required in " "%s.fieldsets[%d][1] field options dict." % (cls.__name__, idx)) for fields in fieldset[1]['fields']: # The entry in fields might be a tuple. If it is a standalone # field, make it into a tuple to make processing easier. if type(fields) != tuple: fields = (fields,) for field in fields: if field in cls.readonly_fields: # Stuff can be put in fields that isn't actually a # model field if it's in readonly_fields, # readonly_fields will handle the validation of such # things. continue check_formfield(cls, model, opts, "fieldsets[%d][1]['fields']" % idx, field) try: f = opts.get_field(field) if isinstance(f, models.ManyToManyField) and not f.rel.through._meta.auto_created: raise ImproperlyConfigured("'%s.fieldsets[%d][1]['fields']' " "can't include the ManyToManyField field '%s' because " "'%s' manually specifies a 'through' model." % ( cls.__name__, idx, field, field)) except models.FieldDoesNotExist: # If we can't find a field on the model that matches, # it could be an extra field on the form. pass flattened_fieldsets = flatten_fieldsets(cls.fieldsets) if len(flattened_fieldsets) > len(set(flattened_fieldsets)): raise ImproperlyConfigured('There are duplicate field(s) in %s.fieldsets' % cls.__name__) # exclude if cls.exclude: # default value is None check_isseq(cls, 'exclude', cls.exclude) for field in cls.exclude: check_formfield(cls, model, opts, 'exclude', field) try: f = opts.get_field(field) except models.FieldDoesNotExist: # If we can't find a field on the model that matches, # it could be an extra field on the form. continue if len(cls.exclude) > len(set(cls.exclude)): raise ImproperlyConfigured('There are duplicate field(s) in %s.exclude' % cls.__name__) # form if hasattr(cls, 'form') and not issubclass(cls.form, BaseModelForm): raise ImproperlyConfigured("%s.form does not inherit from " "BaseModelForm." % cls.__name__) # filter_vertical if hasattr(cls, 'filter_vertical'): check_isseq(cls, 'filter_vertical', cls.filter_vertical) for idx, field in enumerate(cls.filter_vertical): f = get_field(cls, model, opts, 'filter_vertical', field) if not isinstance(f, models.ManyToManyField): raise ImproperlyConfigured("'%s.filter_vertical[%d]' must be " "a ManyToManyField." % (cls.__name__, idx)) # filter_horizontal if hasattr(cls, 'filter_horizontal'): check_isseq(cls, 'filter_horizontal', cls.filter_horizontal) for idx, field in enumerate(cls.filter_horizontal): f = get_field(cls, model, opts, 'filter_horizontal', field) if not isinstance(f, models.ManyToManyField): raise ImproperlyConfigured("'%s.filter_horizontal[%d]' must be " "a ManyToManyField." % (cls.__name__, idx)) # radio_fields if hasattr(cls, 'radio_fields'): check_isdict(cls, 'radio_fields', cls.radio_fields) for field, val in cls.radio_fields.items(): f = get_field(cls, model, opts, 'radio_fields', field) if not (isinstance(f, models.ForeignKey) or f.choices): raise ImproperlyConfigured("'%s.radio_fields['%s']' " "is neither an instance of ForeignKey nor does " "have choices set." % (cls.__name__, field)) if not val in (HORIZONTAL, VERTICAL): raise ImproperlyConfigured("'%s.radio_fields['%s']' " "is neither admin.HORIZONTAL nor admin.VERTICAL." % (cls.__name__, field)) # prepopulated_fields if hasattr(cls, 'prepopulated_fields'): check_isdict(cls, 'prepopulated_fields', cls.prepopulated_fields) for field, val in cls.prepopulated_fields.items(): f = get_field(cls, model, opts, 'prepopulated_fields', field) if isinstance(f, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)): raise ImproperlyConfigured("'%s.prepopulated_fields['%s']' " "is either a DateTimeField, ForeignKey or " "ManyToManyField. This isn't allowed." % (cls.__name__, field)) check_isseq(cls, "prepopulated_fields['%s']" % field, val) for idx, f in enumerate(val): get_field(cls, model, opts, "prepopulated_fields['%s'][%d]" % (field, idx), f) def check_isseq(cls, label, obj): if not isinstance(obj, (list, tuple)): raise ImproperlyConfigured("'%s.%s' must be a list or tuple." % (cls.__name__, label)) def check_isdict(cls, label, obj): if not isinstance(obj, dict): raise ImproperlyConfigured("'%s.%s' must be a dictionary." % (cls.__name__, label)) def get_field(cls, model, opts, label, field): try: return opts.get_field(field) except models.FieldDoesNotExist: raise ImproperlyConfigured("'%s.%s' refers to field '%s' that is missing from model '%s'." % (cls.__name__, label, field, model.__name__)) def check_formfield(cls, model, opts, label, field): if getattr(cls.form, 'base_fields', None): try: cls.form.base_fields[field] except KeyError: raise ImproperlyConfigured("'%s.%s' refers to field '%s' that " "is missing from the form." % (cls.__name__, label, field)) else: fields = fields_for_model(model) try: fields[field] except KeyError: raise ImproperlyConfigured("'%s.%s' refers to field '%s' that " "is missing from the form." % (cls.__name__, label, field)) def fetch_attr(cls, model, opts, label, field): try: return opts.get_field(field) except models.FieldDoesNotExist: pass try: return getattr(model, field) except AttributeError: raise ImproperlyConfigured("'%s.%s' refers to '%s' that is neither a field, method or property of model '%s'." % (cls.__name__, label, field, model.__name__))
18,690
Python
.py
341
41.463343
149
0.571405
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,839
widgets.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/widgets.py
""" Form Widget classes specific to the Django admin site. """ import django.utils.copycompat as copy from django import forms from django.forms.widgets import RadioFieldRenderer from django.forms.util import flatatt from django.utils.html import escape from django.utils.text import truncate_words from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.utils.encoding import force_unicode from django.conf import settings from django.core.urlresolvers import reverse, NoReverseMatch class FilteredSelectMultiple(forms.SelectMultiple): """ A SelectMultiple with a JavaScript filter interface. Note that the resulting JavaScript assumes that the jsi18n catalog has been loaded in the page """ class Media: js = (settings.ADMIN_MEDIA_PREFIX + "js/core.js", settings.ADMIN_MEDIA_PREFIX + "js/SelectBox.js", settings.ADMIN_MEDIA_PREFIX + "js/SelectFilter2.js") def __init__(self, verbose_name, is_stacked, attrs=None, choices=()): self.verbose_name = verbose_name self.is_stacked = is_stacked super(FilteredSelectMultiple, self).__init__(attrs, choices) def render(self, name, value, attrs=None, choices=()): if attrs is None: attrs = {} attrs['class'] = 'selectfilter' if self.is_stacked: attrs['class'] += 'stacked' output = [super(FilteredSelectMultiple, self).render(name, value, attrs, choices)] output.append(u'<script type="text/javascript">addEvent(window, "load", function(e) {') # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. output.append(u'SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n' % \ (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), settings.ADMIN_MEDIA_PREFIX)) return mark_safe(u''.join(output)) class AdminDateWidget(forms.DateInput): class Media: js = (settings.ADMIN_MEDIA_PREFIX + "js/calendar.js", settings.ADMIN_MEDIA_PREFIX + "js/admin/DateTimeShortcuts.js") def __init__(self, attrs={}, format=None): super(AdminDateWidget, self).__init__(attrs={'class': 'vDateField', 'size': '10'}, format=format) class AdminTimeWidget(forms.TimeInput): class Media: js = (settings.ADMIN_MEDIA_PREFIX + "js/calendar.js", settings.ADMIN_MEDIA_PREFIX + "js/admin/DateTimeShortcuts.js") def __init__(self, attrs={}, format=None): super(AdminTimeWidget, self).__init__(attrs={'class': 'vTimeField', 'size': '8'}, format=format) class AdminSplitDateTime(forms.SplitDateTimeWidget): """ A SplitDateTime Widget that has some admin-specific styling. """ def __init__(self, attrs=None): widgets = [AdminDateWidget, AdminTimeWidget] # Note that we're calling MultiWidget, not SplitDateTimeWidget, because # we want to define widgets. forms.MultiWidget.__init__(self, widgets, attrs) def format_output(self, rendered_widgets): return mark_safe(u'<p class="datetime">%s %s<br />%s %s</p>' % \ (_('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1])) class AdminRadioFieldRenderer(RadioFieldRenderer): def render(self): """Outputs a <ul> for this set of radio fields.""" return mark_safe(u'<ul%s>\n%s\n</ul>' % ( flatatt(self.attrs), u'\n'.join([u'<li>%s</li>' % force_unicode(w) for w in self])) ) class AdminRadioSelect(forms.RadioSelect): renderer = AdminRadioFieldRenderer class AdminFileWidget(forms.FileInput): """ A FileField Widget that shows its current value if it has one. """ def __init__(self, attrs={}): super(AdminFileWidget, self).__init__(attrs) def render(self, name, value, attrs=None): output = [] if value and hasattr(value, "url"): output.append('%s <a target="_blank" href="%s">%s</a> <br />%s ' % \ (_('Currently:'), escape(value.url), escape(value), _('Change:'))) output.append(super(AdminFileWidget, self).render(name, value, attrs)) return mark_safe(u''.join(output)) def url_params_from_lookup_dict(lookups): """ Converts the type of lookups specified in a ForeignKey limit_choices_to attribute to a dictionary of query parameters """ params = {} if lookups and hasattr(lookups, 'items'): items = [] for k, v in lookups.items(): if isinstance(v, list): v = u','.join([str(x) for x in v]) elif isinstance(v, bool): # See django.db.fields.BooleanField.get_prep_lookup v = ('0', '1')[v] else: v = unicode(v) items.append((k, v)) params.update(dict(items)) return params class ForeignKeyRawIdWidget(forms.TextInput): """ A Widget for displaying ForeignKeys in the "raw_id" interface rather than in a <select> box. """ def __init__(self, rel, attrs=None, using=None): self.rel = rel self.db = using super(ForeignKeyRawIdWidget, self).__init__(attrs) def render(self, name, value, attrs=None): if attrs is None: attrs = {} related_url = '../../../%s/%s/' % (self.rel.to._meta.app_label, self.rel.to._meta.object_name.lower()) params = self.url_parameters() if params: url = u'?' + u'&amp;'.join([u'%s=%s' % (k, v) for k, v in params.items()]) else: url = u'' if not attrs.has_key('class'): attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript looks for this hook. output = [super(ForeignKeyRawIdWidget, self).render(name, value, attrs)] # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. output.append(u'<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> ' % \ (related_url, url, name)) output.append(u'<img src="%simg/admin/selector-search.gif" width="16" height="16" alt="%s" /></a>' % (settings.ADMIN_MEDIA_PREFIX, _('Lookup'))) if value: output.append(self.label_for_value(value)) return mark_safe(u''.join(output)) def base_url_parameters(self): return url_params_from_lookup_dict(self.rel.limit_choices_to) def url_parameters(self): from django.contrib.admin.views.main import TO_FIELD_VAR params = self.base_url_parameters() params.update({TO_FIELD_VAR: self.rel.get_related_field().name}) return params def label_for_value(self, value): key = self.rel.get_related_field().name try: obj = self.rel.to._default_manager.using(self.db).get(**{key: value}) return '&nbsp;<strong>%s</strong>' % escape(truncate_words(obj, 14)) except (ValueError, self.rel.to.DoesNotExist): return '' class ManyToManyRawIdWidget(ForeignKeyRawIdWidget): """ A Widget for displaying ManyToMany ids in the "raw_id" interface rather than in a <select multiple> box. """ def render(self, name, value, attrs=None): if attrs is None: attrs = {} attrs['class'] = 'vManyToManyRawIdAdminField' if value: value = ','.join([force_unicode(v) for v in value]) else: value = '' return super(ManyToManyRawIdWidget, self).render(name, value, attrs) def url_parameters(self): return self.base_url_parameters() def label_for_value(self, value): return '' def value_from_datadict(self, data, files, name): value = data.get(name, None) if value and ',' in value: return data[name].split(',') if value: return [value] return 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 pk1, pk2 in zip(initial, data): if force_unicode(pk1) != force_unicode(pk2): return True return False class RelatedFieldWidgetWrapper(forms.Widget): """ This class is a wrapper to a given widget to add the add icon for the admin interface. """ def __init__(self, widget, rel, admin_site): self.is_hidden = widget.is_hidden self.needs_multipart_form = widget.needs_multipart_form self.attrs = widget.attrs self.choices = widget.choices self.widget = widget self.rel = rel # so we can check if the related object is registered with this AdminSite self.admin_site = admin_site def __deepcopy__(self, memo): obj = copy.copy(self) obj.widget = copy.deepcopy(self.widget, memo) obj.attrs = self.widget.attrs memo[id(self)] = obj return obj def _media(self): return self.widget.media media = property(_media) def render(self, name, value, *args, **kwargs): rel_to = self.rel.to info = (rel_to._meta.app_label, rel_to._meta.object_name.lower()) try: related_url = reverse('admin:%s_%s_add' % info, current_app=self.admin_site.name) except NoReverseMatch: info = (self.admin_site.root_path, rel_to._meta.app_label, rel_to._meta.object_name.lower()) related_url = '%s%s/%s/add/' % info self.widget.choices = self.choices output = [self.widget.render(name, value, *args, **kwargs)] if rel_to in self.admin_site._registry: # If the related object has an admin interface: # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. output.append(u'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \ (related_url, name)) output.append(u'<img src="%simg/admin/icon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (settings.ADMIN_MEDIA_PREFIX, _('Add Another'))) return mark_safe(u''.join(output)) def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) return self.attrs def value_from_datadict(self, data, files, name): return self.widget.value_from_datadict(data, files, name) def _has_changed(self, initial, data): return self.widget._has_changed(initial, data) def id_for_label(self, id_): return self.widget.id_for_label(id_) class AdminTextareaWidget(forms.Textarea): def __init__(self, attrs=None): final_attrs = {'class': 'vLargeTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminTextareaWidget, self).__init__(attrs=final_attrs) class AdminTextInputWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminTextInputWidget, self).__init__(attrs=final_attrs) class AdminURLFieldWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vURLField'} if attrs is not None: final_attrs.update(attrs) super(AdminURLFieldWidget, self).__init__(attrs=final_attrs) class AdminIntegerFieldWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vIntegerField'} if attrs is not None: final_attrs.update(attrs) super(AdminIntegerFieldWidget, self).__init__(attrs=final_attrs) class AdminCommaSeparatedIntegerFieldWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vCommaSeparatedIntegerField'} if attrs is not None: final_attrs.update(attrs) super(AdminCommaSeparatedIntegerFieldWidget, self).__init__(attrs=final_attrs)
12,235
Python
.py
263
38.403042
157
0.633255
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,840
helpers.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/helpers.py
from django import forms from django.conf import settings from django.contrib.admin.util import flatten_fieldsets, lookup_field from django.contrib.admin.util import display_for_field, label_for_field from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist from django.db.models.fields import FieldDoesNotExist from django.db.models.fields.related import ManyToManyRel from django.forms.util import flatatt from django.template.defaultfilters import capfirst from django.utils.encoding import force_unicode, smart_unicode from django.utils.html import escape, conditional_escape from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ ACTION_CHECKBOX_NAME = '_selected_action' class ActionForm(forms.Form): action = forms.ChoiceField(label=_('Action:')) select_across = forms.BooleanField(label='', required=False, initial=0, widget=forms.HiddenInput({'class': 'select-across'})) checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False) class AdminForm(object): def __init__(self, form, fieldsets, prepopulated_fields, readonly_fields=None, model_admin=None): self.form, self.fieldsets = form, normalize_fieldsets(fieldsets) self.prepopulated_fields = [{ 'field': form[field_name], 'dependencies': [form[f] for f in dependencies] } for field_name, dependencies in prepopulated_fields.items()] self.model_admin = model_admin if readonly_fields is None: readonly_fields = () self.readonly_fields = readonly_fields def __iter__(self): for name, options in self.fieldsets: yield Fieldset(self.form, name, readonly_fields=self.readonly_fields, model_admin=self.model_admin, **options ) def first_field(self): try: fieldset_name, fieldset_options = self.fieldsets[0] field_name = fieldset_options['fields'][0] if not isinstance(field_name, basestring): field_name = field_name[0] return self.form[field_name] except (KeyError, IndexError): pass try: return iter(self.form).next() except StopIteration: return None def _media(self): media = self.form.media for fs in self: media = media + fs.media return media media = property(_media) class Fieldset(object): def __init__(self, form, name=None, readonly_fields=(), fields=(), classes=(), description=None, model_admin=None): self.form = form self.name, self.fields = name, fields self.classes = u' '.join(classes) self.description = description self.model_admin = model_admin self.readonly_fields = readonly_fields def _media(self): if 'collapse' in self.classes: js = ['js/jquery.min.js', 'js/jquery.init.js', 'js/collapse.min.js'] return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js]) return forms.Media() media = property(_media) def __iter__(self): for field in self.fields: yield Fieldline(self.form, field, self.readonly_fields, model_admin=self.model_admin) class Fieldline(object): def __init__(self, form, field, readonly_fields=None, model_admin=None): self.form = form # A django.forms.Form instance if not hasattr(field, "__iter__"): self.fields = [field] else: self.fields = field self.model_admin = model_admin if readonly_fields is None: readonly_fields = () self.readonly_fields = readonly_fields def __iter__(self): for i, field in enumerate(self.fields): if field in self.readonly_fields: yield AdminReadonlyField(self.form, field, is_first=(i == 0), model_admin=self.model_admin) else: yield AdminField(self.form, field, is_first=(i == 0)) def errors(self): return mark_safe(u'\n'.join([self.form[f].errors.as_ul() for f in self.fields if f not in self.readonly_fields]).strip('\n')) class AdminField(object): def __init__(self, form, field, is_first): self.field = form[field] # A django.forms.BoundField instance self.is_first = is_first # Whether this field is first on the line self.is_checkbox = isinstance(self.field.field.widget, forms.CheckboxInput) def label_tag(self): classes = [] if self.is_checkbox: classes.append(u'vCheckboxLabel') contents = force_unicode(escape(self.field.label)) else: contents = force_unicode(escape(self.field.label)) + u':' if self.field.field.required: classes.append(u'required') if not self.is_first: classes.append(u'inline') attrs = classes and {'class': u' '.join(classes)} or {} return self.field.label_tag(contents=contents, attrs=attrs) def errors(self): return mark_safe(self.field.errors.as_ul()) class AdminReadonlyField(object): def __init__(self, form, field, is_first, model_admin=None): label = label_for_field(field, form._meta.model, model_admin) # Make self.field look a little bit like a field. This means that # {{ field.name }} must be a useful class name to identify the field. # For convenience, store other field-related data here too. if callable(field): class_name = field.__name__ != '<lambda>' and field.__name__ or '' else: class_name = field self.field = { 'name': class_name, 'label': label, 'field': field, } self.form = form self.model_admin = model_admin self.is_first = is_first self.is_checkbox = False self.is_readonly = True def label_tag(self): attrs = {} if not self.is_first: attrs["class"] = "inline" label = self.field['label'] contents = capfirst(force_unicode(escape(label))) + u":" return mark_safe('<label%(attrs)s>%(contents)s</label>' % { "attrs": flatatt(attrs), "contents": contents, }) def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: result_repr = smart_unicode(value) if getattr(attr, "allow_tags", False): result_repr = mark_safe(result_repr) else: if value is None: result_repr = EMPTY_CHANGELIST_VALUE elif isinstance(f.rel, ManyToManyRel): result_repr = ", ".join(map(unicode, value.all())) else: result_repr = display_for_field(value, f) return conditional_escape(result_repr) class InlineAdminFormSet(object): """ A wrapper around an inline formset for use in the admin system. """ def __init__(self, inline, formset, fieldsets, readonly_fields=None, model_admin=None): self.opts = inline self.formset = formset self.fieldsets = fieldsets self.model_admin = model_admin if readonly_fields is None: readonly_fields = () self.readonly_fields = readonly_fields def __iter__(self): for form, original in zip(self.formset.initial_forms, self.formset.get_queryset()): yield InlineAdminForm(self.formset, form, self.fieldsets, self.opts.prepopulated_fields, original, self.readonly_fields, model_admin=self.model_admin) for form in self.formset.extra_forms: yield InlineAdminForm(self.formset, form, self.fieldsets, self.opts.prepopulated_fields, None, self.readonly_fields, model_admin=self.model_admin) yield InlineAdminForm(self.formset, self.formset.empty_form, self.fieldsets, self.opts.prepopulated_fields, None, self.readonly_fields, model_admin=self.model_admin) def fields(self): fk = getattr(self.formset, "fk", None) for i, field in enumerate(flatten_fieldsets(self.fieldsets)): if fk and fk.name == field: continue if field in self.readonly_fields: yield { 'label': label_for_field(field, self.opts.model, self.model_admin), 'widget': { 'is_hidden': False }, 'required': False } else: yield self.formset.form.base_fields[field] def _media(self): media = self.opts.media + self.formset.media for fs in self: media = media + fs.media return media media = property(_media) class InlineAdminForm(AdminForm): """ A wrapper around an inline form for use in the admin system. """ def __init__(self, formset, form, fieldsets, prepopulated_fields, original, readonly_fields=None, model_admin=None): self.formset = formset self.model_admin = model_admin self.original = original if original is not None: self.original_content_type_id = ContentType.objects.get_for_model(original).pk self.show_url = original and hasattr(original, 'get_absolute_url') super(InlineAdminForm, self).__init__(form, fieldsets, prepopulated_fields, readonly_fields, model_admin) def __iter__(self): for name, options in self.fieldsets: yield InlineFieldset(self.formset, self.form, name, self.readonly_fields, model_admin=self.model_admin, **options) def has_auto_field(self): if self.form._meta.model._meta.has_auto_field: return True # Also search any parents for an auto field. for parent in self.form._meta.model._meta.get_parent_list(): if parent._meta.has_auto_field: return True return False def field_count(self): # tabular.html uses this function for colspan value. num_of_fields = 0 if self.has_auto_field(): num_of_fields += 1 num_of_fields += len(self.fieldsets[0][1]["fields"]) if self.formset.can_order: num_of_fields += 1 if self.formset.can_delete: num_of_fields += 1 return num_of_fields def pk_field(self): return AdminField(self.form, self.formset._pk_field.name, False) def fk_field(self): fk = getattr(self.formset, "fk", None) if fk: return AdminField(self.form, fk.name, False) else: return "" def deletion_field(self): from django.forms.formsets import DELETION_FIELD_NAME return AdminField(self.form, DELETION_FIELD_NAME, False) def ordering_field(self): from django.forms.formsets import ORDERING_FIELD_NAME return AdminField(self.form, ORDERING_FIELD_NAME, False) class InlineFieldset(Fieldset): def __init__(self, formset, *args, **kwargs): self.formset = formset super(InlineFieldset, self).__init__(*args, **kwargs) def __iter__(self): fk = getattr(self.formset, "fk", None) for field in self.fields: if fk and fk.name == field: continue yield Fieldline(self.form, field, self.readonly_fields, model_admin=self.model_admin) class AdminErrorList(forms.util.ErrorList): """ Stores all errors for the form/formsets in an add/change stage view. """ def __init__(self, form, inline_formsets): if form.is_bound: self.extend(form.errors.values()) for inline_formset in inline_formsets: self.extend(inline_formset.non_form_errors()) for errors_in_inline_form in inline_formset.errors: self.extend(errors_in_inline_form.values()) def normalize_fieldsets(fieldsets): """ Make sure the keys in fieldset dictionaries are strings. Returns the normalized data. """ result = [] for name, options in fieldsets: result.append((name, normalize_dictionary(options))) return result def normalize_dictionary(data_dict): """ Converts all the keys in "data_dict" to strings. The keys must be convertible using str(). """ for key, value in data_dict.items(): if not isinstance(key, str): del data_dict[key] data_dict[str(key)] = value return data_dict
13,378
Python
.py
307
33.882736
133
0.61938
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,841
actions.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/actions.py
""" Built-in, globally-available admin actions. """ from django import template from django.core.exceptions import PermissionDenied from django.contrib.admin import helpers from django.contrib.admin.util import get_deleted_objects, model_ngettext from django.shortcuts import render_to_response from django.utils.encoding import force_unicode from django.utils.html import escape from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext_lazy, ugettext as _ def delete_selected(modeladmin, request, queryset): """ Default action which deletes the selected objects. This action first displays a confirmation page whichs shows all the deleteable objects, or, if the user has no permission one of the related childs (foreignkeys), a "permission denied" message. Next, it delets all selected objects and redirects back to the change list. """ opts = modeladmin.model._meta app_label = opts.app_label # Check that the user has delete permission for the actual model if not modeladmin.has_delete_permission(request): raise PermissionDenied # Populate deletable_objects, a data structure of all related objects that # will also be deleted. deletable_objects, perms_needed = get_deleted_objects(queryset, opts, request.user, modeladmin.admin_site, levels_to_root=2) # The user has already confirmed the deletion. # Do the deletion and return a None to display the change list view again. if request.POST.get('post'): if perms_needed: raise PermissionDenied n = queryset.count() if n: for obj in queryset: obj_display = force_unicode(obj) modeladmin.log_deletion(request, obj, obj_display) queryset.delete() modeladmin.message_user(request, _("Successfully deleted %(count)d %(items)s.") % { "count": n, "items": model_ngettext(modeladmin.opts, n) }) # Return None to display the change list page again. return None context = { "title": _("Are you sure?"), "object_name": force_unicode(opts.verbose_name), "deletable_objects": [deletable_objects], 'queryset': queryset, "perms_lacking": perms_needed, "opts": opts, "root_path": modeladmin.admin_site.root_path, "app_label": app_label, 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME, } # Display the confirmation page return render_to_response(modeladmin.delete_selected_confirmation_template or [ "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.object_name.lower()), "admin/%s/delete_selected_confirmation.html" % app_label, "admin/delete_selected_confirmation.html" ], context, context_instance=template.RequestContext(request)) delete_selected.short_description = ugettext_lazy("Delete selected %(verbose_name_plural)s")
3,012
Python
.py
63
41.253968
128
0.708744
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,842
compress.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/media/js/compress.py
#!/usr/bin/env python import os import optparse import subprocess import sys here = os.path.dirname(__file__) def main(): usage = "usage: %prog [file1..fileN]" description = """With no file paths given this script will automatically compress all jQuery-based files of the admin app. Requires the Google Closure Compiler library and Java version 6 or later.""" parser = optparse.OptionParser(usage, description=description) parser.add_option("-c", dest="compiler", default="~/bin/compiler.jar", help="path to Closure Compiler jar file") parser.add_option("-v", "--verbose", action="store_true", dest="verbose") parser.add_option("-q", "--quiet", action="store_false", dest="verbose") (options, args) = parser.parse_args() compiler = os.path.expanduser(options.compiler) if not os.path.exists(compiler): sys.exit("Google Closure compiler jar file %s not found. Please use the -c option to specify the path." % compiler) if not args: if options.verbose: sys.stdout.write("No filenames given; defaulting to admin scripts\n") args = [os.path.join(here, f) for f in [ "actions.js", "collapse.js", "inlines.js", "prepopulate.js"]] for arg in args: if not arg.endswith(".js"): arg = arg + ".js" to_compress = os.path.expanduser(arg) if os.path.exists(to_compress): to_compress_min = "%s.min.js" % "".join(arg.rsplit(".js")) cmd = "java -jar %s --js %s --js_output_file %s" % (compiler, to_compress, to_compress_min) if options.verbose: sys.stdout.write("Running: %s\n" % cmd) subprocess.call(cmd.split()) else: sys.stdout.write("File %s not found. Sure it exists?\n" % to_compress) if __name__ == '__main__': main()
1,896
Python
.py
41
38.219512
123
0.617631
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,843
admin_list.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/templatetags/admin_list.py
import datetime from django.conf import settings from django.contrib.admin.util import lookup_field, display_for_field, label_for_field from django.contrib.admin.views.main import ALL_VAR, EMPTY_CHANGELIST_VALUE from django.contrib.admin.views.main import ORDER_VAR, ORDER_TYPE_VAR, PAGE_VAR, SEARCH_VAR from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.forms.forms import pretty_name from django.utils import formats from django.utils.html import escape, conditional_escape from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext as _ from django.utils.encoding import smart_unicode, force_unicode from django.template import Library register = Library() DOT = '.' def paginator_number(cl,i): """ Generates an individual page index link in a paginated list. """ if i == DOT: return u'... ' elif i == cl.page_num: return mark_safe(u'<span class="this-page">%d</span> ' % (i+1)) else: return mark_safe(u'<a href="%s"%s>%d</a> ' % (escape(cl.get_query_string({PAGE_VAR: i})), (i == cl.paginator.num_pages-1 and ' class="end"' or ''), i+1)) paginator_number = register.simple_tag(paginator_number) def pagination(cl): """ Generates the series of links to the pages in a paginated list. """ paginator, page_num = cl.paginator, cl.page_num pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page if not pagination_required: page_range = [] else: ON_EACH_SIDE = 3 ON_ENDS = 2 # If there are 10 or fewer pages, display links to every page. # Otherwise, do some fancy if paginator.num_pages <= 10: page_range = range(paginator.num_pages) else: # Insert "smart" pagination links, so that there are always ON_ENDS # links at either end of the list of pages, and there are always # ON_EACH_SIDE links at either end of the "current page" link. page_range = [] if page_num > (ON_EACH_SIDE + ON_ENDS): page_range.extend(range(0, ON_EACH_SIDE - 1)) page_range.append(DOT) page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1)) else: page_range.extend(range(0, page_num + 1)) if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1): page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1)) page_range.append(DOT) page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages)) else: page_range.extend(range(page_num + 1, paginator.num_pages)) need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page return { 'cl': cl, 'pagination_required': pagination_required, 'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}), 'page_range': page_range, 'ALL_VAR': ALL_VAR, '1': 1, } pagination = register.inclusion_tag('admin/pagination.html')(pagination) def result_headers(cl): """ Generates the list column headers. """ lookup_opts = cl.lookup_opts for i, field_name in enumerate(cl.list_display): header, attr = label_for_field(field_name, cl.model, model_admin = cl.model_admin, return_attr = True ) if attr: # if the field is the action checkbox: no sorting and special class if field_name == 'action_checkbox': yield { "text": header, "class_attrib": mark_safe(' class="action-checkbox-column"') } continue # It is a non-field, but perhaps one that is sortable admin_order_field = getattr(attr, "admin_order_field", None) if not admin_order_field: yield {"text": header} continue # So this _is_ a sortable non-field. Go to the yield # after the else clause. else: admin_order_field = None th_classes = [] new_order_type = 'asc' if field_name == cl.order_field or admin_order_field == cl.order_field: th_classes.append('sorted %sending' % cl.order_type.lower()) new_order_type = {'asc': 'desc', 'desc': 'asc'}[cl.order_type.lower()] yield { "text": header, "sortable": True, "url": cl.get_query_string({ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type}), "class_attrib": mark_safe(th_classes and ' class="%s"' % ' '.join(th_classes) or '') } def _boolean_icon(field_val): BOOLEAN_MAPPING = {True: 'yes', False: 'no', None: 'unknown'} return mark_safe(u'<img src="%simg/admin/icon-%s.gif" alt="%s" />' % (settings.ADMIN_MEDIA_PREFIX, BOOLEAN_MAPPING[field_val], field_val)) def items_for_result(cl, result, form): """ Generates the actual list of data. """ first = True pk = cl.lookup_opts.pk.attname for field_name in cl.list_display: row_class = '' try: f, attr, value = lookup_field(field_name, result, cl.model_admin) except (AttributeError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True result_repr = _boolean_icon(value) else: result_repr = smart_unicode(value) # Strip HTML tags in the resulting text, except if the # function has an "allow_tags" attribute set to True. if not allow_tags: result_repr = escape(result_repr) else: result_repr = mark_safe(result_repr) else: if value is None: result_repr = EMPTY_CHANGELIST_VALUE if isinstance(f.rel, models.ManyToOneRel): field_val = getattr(result, f.name) if field_val is None: result_repr = EMPTY_CHANGELIST_VALUE else: result_repr = escape(field_val) else: result_repr = display_for_field(value, f) if isinstance(f, models.DateField) or isinstance(f, models.TimeField): row_class = ' class="nowrap"' if force_unicode(result_repr) == '': result_repr = mark_safe('&nbsp;') # If list_display_links not defined, add the link tag to the first field if (first and not cl.list_display_links) or field_name in cl.list_display_links: table_tag = {True:'th', False:'td'}[first] first = False url = cl.url_for_result(result) # Convert the pk to something that can be used in Javascript. # Problem cases are long ints (23L) and non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) result_id = repr(force_unicode(value))[1:] yield mark_safe(u'<%s%s><a href="%s"%s>%s</a></%s>' % \ (table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) else: # By default the fields come from ModelAdmin.list_editable, but if we pull # the fields out of the form instead of list_editable custom admins # can provide fields on a per request basis if form and field_name in form.fields: bf = form[field_name] result_repr = mark_safe(force_unicode(bf.errors) + force_unicode(bf)) else: result_repr = conditional_escape(result_repr) yield mark_safe(u'<td%s>%s</td>' % (row_class, result_repr)) if form and not form[cl.model._meta.pk.name].is_hidden: yield mark_safe(u'<td>%s</td>' % force_unicode(form[cl.model._meta.pk.name])) def results(cl): if cl.formset: for res, form in zip(cl.result_list, cl.formset.forms): yield list(items_for_result(cl, res, form)) else: for res in cl.result_list: yield list(items_for_result(cl, res, None)) def result_hidden_fields(cl): if cl.formset: for res, form in zip(cl.result_list, cl.formset.forms): if form[cl.model._meta.pk.name].is_hidden: yield mark_safe(force_unicode(form[cl.model._meta.pk.name])) def result_list(cl): """ Displays the headers and data list together """ return {'cl': cl, 'result_hidden_fields': list(result_hidden_fields(cl)), 'result_headers': list(result_headers(cl)), 'results': list(results(cl))} result_list = register.inclusion_tag("admin/change_list_results.html")(result_list) def date_hierarchy(cl): """ Displays the date hierarchy for date drill-down functionality. """ if cl.date_hierarchy: field_name = cl.date_hierarchy year_field = '%s__year' % field_name month_field = '%s__month' % field_name day_field = '%s__day' % field_name field_generic = '%s__' % field_name year_lookup = cl.params.get(year_field) month_lookup = cl.params.get(month_field) day_lookup = cl.params.get(day_field) link = lambda d: cl.get_query_string(d, [field_generic]) if year_lookup and month_lookup and day_lookup: day = datetime.date(int(year_lookup), int(month_lookup), int(day_lookup)) return { 'show': True, 'back': { 'link': link({year_field: year_lookup, month_field: month_lookup}), 'title': capfirst(formats.date_format(day, 'YEAR_MONTH_FORMAT')) }, 'choices': [{'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))}] } elif year_lookup and month_lookup: days = cl.query_set.filter(**{year_field: year_lookup, month_field: month_lookup}).dates(field_name, 'day') return { 'show': True, 'back': { 'link': link({year_field: year_lookup}), 'title': str(year_lookup) }, 'choices': [{ 'link': link({year_field: year_lookup, month_field: month_lookup, day_field: day.day}), 'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT')) } for day in days] } elif year_lookup: months = cl.query_set.filter(**{year_field: year_lookup}).dates(field_name, 'month') return { 'show' : True, 'back': { 'link' : link({}), 'title': _('All dates') }, 'choices': [{ 'link': link({year_field: year_lookup, month_field: month.month}), 'title': capfirst(formats.date_format(month, 'YEAR_MONTH_FORMAT')) } for month in months] } else: years = cl.query_set.dates(field_name, 'year') return { 'show': True, 'choices': [{ 'link': link({year_field: str(year.year)}), 'title': str(year.year), } for year in years] } date_hierarchy = register.inclusion_tag('admin/date_hierarchy.html')(date_hierarchy) def search_form(cl): """ Displays a search form for searching the list. """ return { 'cl': cl, 'show_result_count': cl.result_count != cl.full_result_count, 'search_var': SEARCH_VAR } search_form = register.inclusion_tag('admin/search_form.html')(search_form) def admin_list_filter(cl, spec): return {'title': spec.title(), 'choices' : list(spec.choices(cl))} admin_list_filter = register.inclusion_tag('admin/filter.html')(admin_list_filter) def admin_actions(context): """ Track the number of times the action field has been rendered on the page, so we know which value to use. """ context['action_index'] = context.get('action_index', -1) + 1 return context admin_actions = register.inclusion_tag("admin/actions.html", takes_context=True)(admin_actions)
12,835
Python
.py
282
34.719858
198
0.578191
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,844
admin_modify.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/templatetags/admin_modify.py
from django import template register = template.Library() def prepopulated_fields_js(context): """ Creates a list of prepopulated_fields that should render Javascript for the prepopulated fields for both the admin form and inlines. """ prepopulated_fields = [] if context['add'] and 'adminform' in context: prepopulated_fields.extend(context['adminform'].prepopulated_fields) if 'inline_admin_formsets' in context: for inline_admin_formset in context['inline_admin_formsets']: for inline_admin_form in inline_admin_formset: if inline_admin_form.original is None: prepopulated_fields.extend(inline_admin_form.prepopulated_fields) context.update({'prepopulated_fields': prepopulated_fields}) return context prepopulated_fields_js = register.inclusion_tag('admin/prepopulated_fields_js.html', takes_context=True)(prepopulated_fields_js) def submit_row(context): """ Displays the row of buttons for delete and save. """ opts = context['opts'] change = context['change'] is_popup = context['is_popup'] save_as = context['save_as'] return { 'onclick_attrib': (opts.get_ordered_objects() and change and 'onclick="submitOrderForm();"' or ''), 'show_delete_link': (not is_popup and context['has_delete_permission'] and (change or context['show_delete'])), 'show_save_as_new': not is_popup and change and save_as, 'show_save_and_add_another': context['has_add_permission'] and not is_popup and (not save_as or context['add']), 'show_save_and_continue': not is_popup and context['has_change_permission'], 'is_popup': is_popup, 'show_save': True } submit_row = register.inclusion_tag('admin/submit_line.html', takes_context=True)(submit_row)
1,913
Python
.py
39
40.794872
128
0.661144
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,845
adminmedia.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/templatetags/adminmedia.py
from django.template import Library from django.utils.encoding import iri_to_uri register = Library() def admin_media_prefix(): """ Returns the string contained in the setting ADMIN_MEDIA_PREFIX. """ try: from django.conf import settings except ImportError: return '' return iri_to_uri(settings.ADMIN_MEDIA_PREFIX) admin_media_prefix = register.simple_tag(admin_media_prefix)
418
Python
.py
13
27.923077
67
0.734491
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,846
log.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/templatetags/log.py
from django import template from django.contrib.admin.models import LogEntry register = template.Library() class AdminLogNode(template.Node): def __init__(self, limit, varname, user): self.limit, self.varname, self.user = limit, varname, user def __repr__(self): return "<GetAdminLog Node>" def render(self, context): if self.user is None: context[self.varname] = LogEntry.objects.all().select_related('content_type', 'user')[:self.limit] else: user_id = self.user if not user_id.isdigit(): user_id = context[self.user].id context[self.varname] = LogEntry.objects.filter(user__id__exact=user_id).select_related('content_type', 'user')[:self.limit] return '' class DoGetAdminLog: """ Populates a template variable with the admin log for the given criteria. Usage:: {% get_admin_log [limit] as [varname] for_user [context_var_containing_user_obj] %} Examples:: {% get_admin_log 10 as admin_log for_user 23 %} {% get_admin_log 10 as admin_log for_user user %} {% get_admin_log 10 as admin_log %} Note that ``context_var_containing_user_obj`` can be a hard-coded integer (user ID) or the name of a template context variable containing the user object whose ID you want. """ def __init__(self, tag_name): self.tag_name = tag_name def __call__(self, parser, token): tokens = token.contents.split() if len(tokens) < 4: raise template.TemplateSyntaxError("'%s' statements require two arguments" % self.tag_name) if not tokens[1].isdigit(): raise template.TemplateSyntaxError("First argument in '%s' must be an integer" % self.tag_name) if tokens[2] != 'as': raise template.TemplateSyntaxError("Second argument in '%s' must be 'as'" % self.tag_name) if len(tokens) > 4: if tokens[4] != 'for_user': raise template.TemplateSyntaxError("Fourth argument in '%s' must be 'for_user'" % self.tag_name) return AdminLogNode(limit=tokens[1], varname=tokens[3], user=(len(tokens) > 5 and tokens[5] or None)) register.tag('get_admin_log', DoGetAdminLog('get_admin_log'))
2,270
Python
.py
45
42.333333
136
0.642567
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,847
main.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/views/main.py
from django.contrib.admin.filterspecs import FilterSpec from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.admin.util import quote from django.core.exceptions import SuspiciousOperation from django.core.paginator import Paginator, InvalidPage from django.db import models from django.db.models.query import QuerySet from django.utils.encoding import force_unicode, smart_str from django.utils.translation import ugettext from django.utils.http import urlencode import operator # The system will display a "Show all" link on the change list only if the # total result count is less than or equal to this setting. MAX_SHOW_ALL_ALLOWED = 200 # Changelist settings ALL_VAR = 'all' ORDER_VAR = 'o' ORDER_TYPE_VAR = 'ot' PAGE_VAR = 'p' SEARCH_VAR = 'q' TO_FIELD_VAR = 't' IS_POPUP_VAR = 'pop' ERROR_FLAG = 'e' # Text to display within change-list table cells if the value is blank. EMPTY_CHANGELIST_VALUE = '(None)' class ChangeList(object): def __init__(self, request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_editable, model_admin): self.model = model self.opts = model._meta self.lookup_opts = self.opts self.root_query_set = model_admin.queryset(request) self.list_display = list_display self.list_display_links = list_display_links self.list_filter = list_filter self.date_hierarchy = date_hierarchy self.search_fields = search_fields self.list_select_related = list_select_related self.list_per_page = list_per_page self.list_editable = list_editable self.model_admin = model_admin # Get search parameters from the query string. try: self.page_num = int(request.GET.get(PAGE_VAR, 0)) except ValueError: self.page_num = 0 self.show_all = ALL_VAR in request.GET self.is_popup = IS_POPUP_VAR in request.GET self.to_field = request.GET.get(TO_FIELD_VAR) self.params = dict(request.GET.items()) if PAGE_VAR in self.params: del self.params[PAGE_VAR] if TO_FIELD_VAR in self.params: del self.params[TO_FIELD_VAR] if ERROR_FLAG in self.params: del self.params[ERROR_FLAG] self.order_field, self.order_type = self.get_ordering() self.query = request.GET.get(SEARCH_VAR, '') self.query_set = self.get_query_set() self.get_results(request) self.title = (self.is_popup and ugettext('Select %s') % force_unicode(self.opts.verbose_name) or ugettext('Select %s to change') % force_unicode(self.opts.verbose_name)) self.filter_specs, self.has_filters = self.get_filters(request) self.pk_attname = self.lookup_opts.pk.attname def get_filters(self, request): filter_specs = [] if self.list_filter: filter_fields = [self.lookup_opts.get_field(field_name) for field_name in self.list_filter] for f in filter_fields: spec = FilterSpec.create(f, request, self.params, self.model, self.model_admin) if spec and spec.has_output(): filter_specs.append(spec) return filter_specs, bool(filter_specs) def get_query_string(self, new_params=None, remove=None): if new_params is None: new_params = {} if remove is None: remove = [] p = self.params.copy() for r in remove: for k in p.keys(): if k.startswith(r): del p[k] for k, v in new_params.items(): if v is None: if k in p: del p[k] else: p[k] = v return '?%s' % urlencode(p) def get_results(self, request): paginator = Paginator(self.query_set, self.list_per_page) # Get the number of objects, with admin filters applied. result_count = paginator.count # Get the total number of objects, with no admin filters applied. # Perform a slight optimization: Check to see whether any filters were # given. If not, use paginator.hits to calculate the number of objects, # because we've already done paginator.hits and the value is cached. if not self.query_set.query.where: full_result_count = result_count else: full_result_count = self.root_query_set.count() can_show_all = result_count <= MAX_SHOW_ALL_ALLOWED multi_page = result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and can_show_all) or not multi_page: result_list = self.query_set._clone() else: try: result_list = paginator.page(self.page_num+1).object_list except InvalidPage: raise IncorrectLookupParameters self.result_count = result_count self.full_result_count = full_result_count self.result_list = result_list self.can_show_all = can_show_all self.multi_page = multi_page self.paginator = paginator def get_ordering(self): lookup_opts, params = self.lookup_opts, self.params # For ordering, first check the "ordering" parameter in the admin # options, then check the object's default ordering. If neither of # those exist, order descending by ID by default. Finally, look for # manually-specified ordering from the query string. ordering = self.model_admin.ordering or lookup_opts.ordering or ['-' + lookup_opts.pk.name] if ordering[0].startswith('-'): order_field, order_type = ordering[0][1:], 'desc' else: order_field, order_type = ordering[0], 'asc' if ORDER_VAR in params: try: field_name = self.list_display[int(params[ORDER_VAR])] try: f = lookup_opts.get_field(field_name) except models.FieldDoesNotExist: # See whether field_name is a name of a non-field # that allows sorting. try: if callable(field_name): attr = field_name elif hasattr(self.model_admin, field_name): attr = getattr(self.model_admin, field_name) else: attr = getattr(self.model, field_name) order_field = attr.admin_order_field except AttributeError: pass else: order_field = f.name except (IndexError, ValueError): pass # Invalid ordering specified. Just use the default. if ORDER_TYPE_VAR in params and params[ORDER_TYPE_VAR] in ('asc', 'desc'): order_type = params[ORDER_TYPE_VAR] return order_field, order_type def get_query_set(self): qs = self.root_query_set lookup_params = self.params.copy() # a dictionary of the query string for i in (ALL_VAR, ORDER_VAR, ORDER_TYPE_VAR, SEARCH_VAR, IS_POPUP_VAR): if i in lookup_params: del lookup_params[i] for key, value in lookup_params.items(): if not isinstance(key, str): # 'key' will be used as a keyword argument later, so Python # requires it to be a string. del lookup_params[key] lookup_params[smart_str(key)] = value # if key ends with __in, split parameter into separate values if key.endswith('__in'): value = value.split(',') lookup_params[key] = value # if key ends with __isnull, special case '' and false if key.endswith('__isnull'): if value.lower() in ('', 'false'): value = False else: value = True lookup_params[key] = value if not self.model_admin.lookup_allowed(key, value): raise SuspiciousOperation( "Filtering by %s not allowed" % key ) # Apply lookup parameters from the query string. try: qs = qs.filter(**lookup_params) # Naked except! Because we don't have any other way of validating "params". # They might be invalid if the keyword arguments are incorrect, or if the # values are not in the correct type, so we might get FieldError, ValueError, # ValicationError, or ? from a custom field that raises yet something else # when handed impossible data. except: raise IncorrectLookupParameters # Use select_related() if one of the list_display options is a field # with a relationship and the provided queryset doesn't already have # select_related defined. if not qs.query.select_related: if self.list_select_related: qs = qs.select_related() else: for field_name in self.list_display: try: f = self.lookup_opts.get_field(field_name) except models.FieldDoesNotExist: pass else: if isinstance(f.rel, models.ManyToOneRel): qs = qs.select_related() break # Set ordering. if self.order_field: qs = qs.order_by('%s%s' % ((self.order_type == 'desc' and '-' or ''), self.order_field)) # Apply keyword searches. def construct_search(field_name): if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__search" % field_name[1:] else: return "%s__icontains" % field_name if self.search_fields and self.query: for bit in self.query.split(): or_queries = [models.Q(**{construct_search(str(field_name)): bit}) for field_name in self.search_fields] qs = qs.filter(reduce(operator.or_, or_queries)) for field_name in self.search_fields: if '__' in field_name: qs = qs.distinct() break return qs def url_for_result(self, result): return "%s/" % quote(getattr(result, self.pk_attname))
10,766
Python
.py
227
35.61674
181
0.592124
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,848
decorators.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/admin/views/decorators.py
import base64 try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.4 fallback. from django import http, template from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import render_to_response from django.utils.translation import ugettext_lazy, ugettext as _ ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.") LOGIN_FORM_KEY = 'this_is_the_login_form' def _display_login_form(request, error_message=''): request.session.set_test_cookie() return render_to_response('admin/login.html', { 'title': _('Log in'), 'app_path': request.get_full_path(), 'error_message': error_message }, context_instance=template.RequestContext(request)) def staff_member_required(view_func): """ Decorator for views that checks that the user is logged in and is a staff member, displaying the login page if necessary. """ def _checklogin(request, *args, **kwargs): if request.user.is_active and request.user.is_staff: # The user is valid. Continue to the admin page. return view_func(request, *args, **kwargs) assert hasattr(request, 'session'), "The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'." # If this isn't already the login page, display it. if LOGIN_FORM_KEY not in request.POST: if request.POST: message = _("Please log in again, because your session has expired.") else: message = "" return _display_login_form(request, message) # Check that the user accepts cookies. if not request.session.test_cookie_worked(): message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.") return _display_login_form(request, message) else: request.session.delete_test_cookie() # Check the password. username = request.POST.get('username', None) password = request.POST.get('password', None) user = authenticate(username=username, password=password) if user is None: message = ERROR_MESSAGE if '@' in username: # Mistakenly entered e-mail address instead of username? Look it up. users = list(User.objects.filter(email=username)) if len(users) == 1 and users[0].check_password(password): message = _("Your e-mail address is not your username. Try '%s' instead.") % users[0].username return _display_login_form(request, message) # The user data is correct; log in the user in and continue. else: if user.is_active and user.is_staff: login(request, user) return http.HttpResponseRedirect(request.get_full_path()) else: return _display_login_form(request, ERROR_MESSAGE) return wraps(view_func)(_checklogin)
3,276
Python
.py
63
43.15873
210
0.66906
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,849
constants.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/constants.py
DEBUG = 10 INFO = 20 SUCCESS = 25 WARNING = 30 ERROR = 40 DEFAULT_TAGS = { DEBUG: 'debug', INFO: 'info', SUCCESS: 'success', WARNING: 'warning', ERROR: 'error', }
184
Python
.py
12
12.583333
23
0.614035
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,850
api.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/api.py
from django.contrib.messages import constants from django.contrib.messages.storage import default_storage from django.utils.functional import lazy, memoize __all__ = ( 'add_message', 'get_messages', 'get_level', 'set_level', 'debug', 'info', 'success', 'warning', 'error', ) class MessageFailure(Exception): pass def add_message(request, level, message, extra_tags='', fail_silently=False): """ Attempts to add a message to the request using the 'messages' app, falling back to the user's message_set if MessageMiddleware hasn't been enabled. """ if hasattr(request, '_messages'): return request._messages.add(level, message, extra_tags) if hasattr(request, 'user') and request.user.is_authenticated(): return request.user.message_set.create(message=message) if not fail_silently: raise MessageFailure('Without the django.contrib.messages ' 'middleware, messages can only be added to ' 'authenticated users.') def get_messages(request): """ Returns the message storage on the request if it exists, otherwise returns user.message_set.all() as the old auth context processor did. """ if hasattr(request, '_messages'): return request._messages def get_user(): if hasattr(request, 'user'): return request.user else: from django.contrib.auth.models import AnonymousUser return AnonymousUser() return lazy(memoize(get_user().get_and_delete_messages, {}, 0), list)() def get_level(request): """ Returns the minimum level of messages to be recorded. The default level is the ``MESSAGE_LEVEL`` setting. If this is not found, the ``INFO`` level is used. """ if hasattr(request, '_messages'): storage = request._messages else: storage = default_storage(request) return storage.level def set_level(request, level): """ Sets the minimum level of messages to be recorded, returning ``True`` if the level was recorded successfully. If set to ``None``, the default level will be used (see the ``get_level`` method). """ if not hasattr(request, '_messages'): return False request._messages.level = level return True def debug(request, message, extra_tags='', fail_silently=False): """ Adds a message with the ``DEBUG`` level. """ add_message(request, constants.DEBUG, message, extra_tags=extra_tags, fail_silently=fail_silently) def info(request, message, extra_tags='', fail_silently=False): """ Adds a message with the ``INFO`` level. """ add_message(request, constants.INFO, message, extra_tags=extra_tags, fail_silently=fail_silently) def success(request, message, extra_tags='', fail_silently=False): """ Adds a message with the ``SUCCESS`` level. """ add_message(request, constants.SUCCESS, message, extra_tags=extra_tags, fail_silently=fail_silently) def warning(request, message, extra_tags='', fail_silently=False): """ Adds a message with the ``WARNING`` level. """ add_message(request, constants.WARNING, message, extra_tags=extra_tags, fail_silently=fail_silently) def error(request, message, extra_tags='', fail_silently=False): """ Adds a message with the ``ERROR`` level. """ add_message(request, constants.ERROR, message, extra_tags=extra_tags, fail_silently=fail_silently)
3,570
Python
.py
89
33.52809
78
0.66522
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,851
context_processors.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/context_processors.py
from django.contrib.messages.api import get_messages def messages(request): """ Returns a lazy 'messages' context variable. """ return {'messages': get_messages(request)}
189
Python
.py
6
27.5
52
0.718232
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,852
utils.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/utils.py
from django.conf import settings from django.contrib.messages import constants def get_level_tags(): """ Returns the message level tags. """ level_tags = constants.DEFAULT_TAGS.copy() level_tags.update(getattr(settings, 'MESSAGE_TAGS', {})) return level_tags
285
Python
.py
9
27.777778
60
0.722628
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,853
middleware.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/middleware.py
from django.conf import settings from django.contrib.messages.storage import default_storage class MessageMiddleware(object): """ Middleware that handles temporary messages. """ def process_request(self, request): request._messages = default_storage(request) def process_response(self, request, response): """ Updates the storage backend (i.e., saves the messages). If not all messages could not be stored and ``DEBUG`` is ``True``, a ``ValueError`` is raised. """ # A higher middleware layer may return a request which does not contain # messages storage, so make no assumption that it will be there. if hasattr(request, '_messages'): unstored_messages = request._messages.update(response) if unstored_messages and settings.DEBUG: raise ValueError('Not all temporary messages could be stored.') return response
957
Python
.py
21
37.666667
79
0.676692
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,854
user_messages.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/storage/user_messages.py
""" Storages used to assist in the deprecation of contrib.auth User messages. """ from django.contrib.messages import constants from django.contrib.messages.storage.base import BaseStorage, Message from django.contrib.auth.models import User from django.contrib.messages.storage.fallback import FallbackStorage class UserMessagesStorage(BaseStorage): """ Retrieves messages from the User, using the legacy user.message_set API. This storage is "read-only" insofar as it can only retrieve and delete messages, not store them. """ session_key = '_messages' def _get_messages_queryset(self): """ Returns the QuerySet containing all user messages (or ``None`` if request.user is not a contrib.auth User). """ user = getattr(self.request, 'user', None) if isinstance(user, User): return user._message_set.all() def add(self, *args, **kwargs): raise NotImplementedError('This message storage is read-only.') def _get(self, *args, **kwargs): """ Retrieves a list of messages assigned to the User. This backend never stores anything, so all_retrieved is assumed to be False. """ queryset = self._get_messages_queryset() if queryset is None: # This is a read-only and optional storage, so to ensure other # storages will also be read if used with FallbackStorage an empty # list is returned rather than None. return [], False messages = [] for user_message in queryset: messages.append(Message(constants.INFO, user_message.message)) return messages, False def _store(self, messages, *args, **kwargs): """ Removes any messages assigned to the User and returns the list of messages (since no messages are stored in this read-only storage). """ queryset = self._get_messages_queryset() if queryset is not None: queryset.delete() return messages class LegacyFallbackStorage(FallbackStorage): """ Works like ``FallbackStorage`` but also handles retrieving (and clearing) contrib.auth User messages. """ storage_classes = (UserMessagesStorage,) + FallbackStorage.storage_classes
2,303
Python
.py
54
35.388889
78
0.676641
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,855
fallback.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/storage/fallback.py
from django.contrib.messages.storage.base import BaseStorage from django.contrib.messages.storage.cookie import CookieStorage from django.contrib.messages.storage.session import SessionStorage class FallbackStorage(BaseStorage): """ Tries to store all messages in the first backend, storing any unstored messages in each subsequent backend backend. """ storage_classes = (CookieStorage, SessionStorage) def __init__(self, *args, **kwargs): super(FallbackStorage, self).__init__(*args, **kwargs) self.storages = [storage_class(*args, **kwargs) for storage_class in self.storage_classes] self._used_storages = set() def _get(self, *args, **kwargs): """ Gets a single list of messages from all storage backends. """ all_messages = [] for storage in self.storages: messages, all_retrieved = storage._get() # If the backend hasn't been used, no more retrieval is necessary. if messages is None: break if messages: self._used_storages.add(storage) all_messages.extend(messages) # If this storage class contained all the messages, no further # retrieval is necessary if all_retrieved: break return all_messages, all_retrieved def _store(self, messages, response, *args, **kwargs): """ Stores the messages, returning any unstored messages after trying all backends. For each storage backend, any messages not stored are passed on to the next backend. """ for storage in self.storages: if messages: messages = storage._store(messages, response, remove_oldest=False) # Even if there are no more messages, continue iterating to ensure # storages which contained messages are flushed. elif storage in self._used_storages: storage._store([], response) self._used_storages.remove(storage) return messages
2,171
Python
.py
49
33.510204
78
0.619745
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,856
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/storage/__init__.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_storage(import_path): """ Imports the message storage class described by import_path, where import_path is the full Python path to the class. """ try: dot = import_path.rindex('.') except ValueError: raise ImproperlyConfigured("%s isn't a Python path." % import_path) module, classname = import_path[:dot], import_path[dot + 1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error importing module %s: "%s"' % (module, e)) try: return getattr(mod, classname) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a "%s" ' 'class.' % (module, classname)) # Callable with the same interface as the storage classes i.e. accepts a # 'request' object. It is wrapped in a lambda to stop 'settings' being used at # the module level default_storage = lambda request: get_storage(settings.MESSAGE_STORAGE)(request)
1,183
Python
.py
27
36.666667
80
0.671875
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,857
base.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/storage/base.py
from django.conf import settings from django.utils.encoding import force_unicode, StrAndUnicode from django.contrib.messages import constants, utils LEVEL_TAGS = utils.get_level_tags() class Message(StrAndUnicode): """ Represents an actual message that can be stored in any of the supported storage classes (typically session- or cookie-based) and rendered in a view or template. """ def __init__(self, level, message, extra_tags=None): self.level = int(level) self.message = message self.extra_tags = extra_tags def _prepare(self): """ Prepares the message for serialization by forcing the ``message`` and ``extra_tags`` to unicode in case they are lazy translations. Known "safe" types (None, int, etc.) are not converted (see Django's ``force_unicode`` implementation for details). """ self.message = force_unicode(self.message, strings_only=True) self.extra_tags = force_unicode(self.extra_tags, strings_only=True) def __eq__(self, other): return isinstance(other, Message) and self.level == other.level and \ self.message == other.message def __unicode__(self): return force_unicode(self.message) def _get_tags(self): label_tag = force_unicode(LEVEL_TAGS.get(self.level, ''), strings_only=True) extra_tags = force_unicode(self.extra_tags, strings_only=True) if extra_tags and label_tag: return u' '.join([extra_tags, label_tag]) elif extra_tags: return extra_tags elif label_tag: return label_tag return '' tags = property(_get_tags) class BaseStorage(object): """ This is the base backend for temporary message storage. This is not a complete class; to be a usable storage backend, it must be subclassed and the two methods ``_get`` and ``_store`` overridden. """ def __init__(self, request, *args, **kwargs): self.request = request self._queued_messages = [] self.used = False self.added_new = False super(BaseStorage, self).__init__(*args, **kwargs) def __len__(self): return len(self._loaded_messages) + len(self._queued_messages) def __iter__(self): self.used = True if self._queued_messages: self._loaded_messages.extend(self._queued_messages) self._queued_messages = [] return iter(self._loaded_messages) def __contains__(self, item): return item in self._loaded_messages or item in self._queued_messages @property def _loaded_messages(self): """ Returns a list of loaded messages, retrieving them first if they have not been loaded yet. """ if not hasattr(self, '_loaded_data'): messages, all_retrieved = self._get() self._loaded_data = messages or [] return self._loaded_data def _get(self, *args, **kwargs): """ Retrieves a list of stored messages. Returns a tuple of the messages and a flag indicating whether or not all the messages originally intended to be stored in this storage were, in fact, stored and retrieved; e.g., ``(messages, all_retrieved)``. **This method must be implemented by a subclass.** If it is possible to tell if the backend was not used (as opposed to just containing no messages) then ``None`` should be returned in place of ``messages``. """ raise NotImplementedError() def _store(self, messages, response, *args, **kwargs): """ Stores a list of messages, returning a list of any messages which could not be stored. One type of object must be able to be stored, ``Message``. **This method must be implemented by a subclass.** """ raise NotImplementedError() def _prepare_messages(self, messages): """ Prepares a list of messages for storage. """ for message in messages: message._prepare() def update(self, response): """ Stores all unread messages. If the backend has yet to be iterated, previously stored messages will be stored again. Otherwise, only messages added after the last iteration will be stored. """ self._prepare_messages(self._queued_messages) if self.used: return self._store(self._queued_messages, response) elif self.added_new: messages = self._loaded_messages + self._queued_messages return self._store(messages, response) def add(self, level, message, extra_tags=''): """ Queues a message to be stored. The message is only queued if it contained something and its level is not less than the recording level (``self.level``). """ if not message: return # Check that the message level is not less than the recording level. level = int(level) if level < self.level: return # Add the message. self.added_new = True message = Message(level, message, extra_tags=extra_tags) self._queued_messages.append(message) def _get_level(self): """ Returns the minimum recorded level. The default level is the ``MESSAGE_LEVEL`` setting. If this is not found, the ``INFO`` level is used. """ if not hasattr(self, '_level'): self._level = getattr(settings, 'MESSAGE_LEVEL', constants.INFO) return self._level def _set_level(self, value=None): """ Sets a custom minimum recorded level. If set to ``None``, the default level will be used (see the ``_get_level`` method). """ if value is None and hasattr(self, '_level'): del self._level else: self._level = int(value) level = property(_get_level, _set_level, _set_level)
6,134
Python
.py
147
32.768707
79
0.617504
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,858
cookie.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/storage/cookie.py
import hmac from django.conf import settings from django.contrib.messages import constants from django.contrib.messages.storage.base import BaseStorage, Message from django.http import CompatCookie from django.utils import simplejson as json from django.utils.hashcompat import sha_hmac class MessageEncoder(json.JSONEncoder): """ Compactly serializes instances of the ``Message`` class as JSON. """ message_key = '__json_message' def default(self, obj): if isinstance(obj, Message): message = [self.message_key, obj.level, obj.message] if obj.extra_tags: message.append(obj.extra_tags) return message return super(MessageEncoder, self).default(obj) class MessageDecoder(json.JSONDecoder): """ Decodes JSON that includes serialized ``Message`` instances. """ def process_messages(self, obj): if isinstance(obj, list) and obj: if obj[0] == MessageEncoder.message_key: return Message(*obj[1:]) return [self.process_messages(item) for item in obj] if isinstance(obj, dict): return dict([(key, self.process_messages(value)) for key, value in obj.iteritems()]) return obj def decode(self, s, **kwargs): decoded = super(MessageDecoder, self).decode(s, **kwargs) return self.process_messages(decoded) class CookieStorage(BaseStorage): """ Stores messages in a cookie. """ cookie_name = 'messages' # We should be able to store 4K in a cookie, but Internet Explorer # imposes 4K as the *total* limit for a domain. To allow other # cookies, we go for 3/4 of 4K. max_cookie_size = 3072 not_finished = '__messagesnotfinished__' def _get(self, *args, **kwargs): """ Retrieves a list of messages from the messages cookie. If the not_finished sentinel value is found at the end of the message list, remove it and return a result indicating that not all messages were retrieved by this storage. """ data = self.request.COOKIES.get(self.cookie_name) messages = self._decode(data) all_retrieved = not (messages and messages[-1] == self.not_finished) if messages and not all_retrieved: # remove the sentinel value messages.pop() return messages, all_retrieved def _update_cookie(self, encoded_data, response): """ Either sets the cookie with the encoded data if there is any data to store, or deletes the cookie. """ if encoded_data: response.set_cookie(self.cookie_name, encoded_data) else: response.delete_cookie(self.cookie_name) def _store(self, messages, response, remove_oldest=True, *args, **kwargs): """ Stores the messages to a cookie, returning a list of any messages which could not be stored. If the encoded data is larger than ``max_cookie_size``, removes messages until the data fits (these are the messages which are returned), and add the not_finished sentinel value to indicate as much. """ unstored_messages = [] encoded_data = self._encode(messages) if self.max_cookie_size: # data is going to be stored eventually by CompatCookie, which # adds it's own overhead, which we must account for. cookie = CompatCookie() # create outside the loop def stored_length(val): return len(cookie.value_encode(val)[1]) while encoded_data and stored_length(encoded_data) > self.max_cookie_size: if remove_oldest: unstored_messages.append(messages.pop(0)) else: unstored_messages.insert(0, messages.pop()) encoded_data = self._encode(messages + [self.not_finished], encode_empty=unstored_messages) self._update_cookie(encoded_data, response) return unstored_messages def _hash(self, value): """ Creates an HMAC/SHA1 hash based on the value and the project setting's SECRET_KEY, modified to make it unique for the present purpose. """ key = 'django.contrib.messages' + settings.SECRET_KEY return hmac.new(key, value, sha_hmac).hexdigest() def _encode(self, messages, encode_empty=False): """ Returns an encoded version of the messages list which can be stored as plain text. Since the data will be retrieved from the client-side, the encoded data also contains a hash to ensure that the data was not tampered with. """ if messages or encode_empty: encoder = MessageEncoder(separators=(',', ':')) value = encoder.encode(messages) return '%s$%s' % (self._hash(value), value) def _decode(self, data): """ Safely decodes a encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, ``None`` is returned. """ if not data: return None bits = data.split('$', 1) if len(bits) == 2: hash, value = bits if hash == self._hash(value): try: # If we get here (and the JSON decode works), everything is # good. In any other case, drop back and return None. return json.loads(value, cls=MessageDecoder) except ValueError: pass # Mark the data as used (so it gets removed) since something was wrong # with the data. self.used = True return None
5,862
Python
.py
133
34.233083
86
0.621016
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,859
session.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/storage/session.py
from django.contrib.messages.storage.base import BaseStorage class SessionStorage(BaseStorage): """ Stores messages in the session (that is, django.contrib.sessions). """ session_key = '_messages' def __init__(self, request, *args, **kwargs): assert hasattr(request, 'session'), "The session-based temporary "\ "message storage requires session middleware to be installed, "\ "and come before the message middleware in the "\ "MIDDLEWARE_CLASSES list." super(SessionStorage, self).__init__(request, *args, **kwargs) def _get(self, *args, **kwargs): """ Retrieves a list of messages from the request's session. This storage always stores everything it is given, so return True for the all_retrieved flag. """ return self.request.session.get(self.session_key), True def _store(self, messages, response, *args, **kwargs): """ Stores a list of messages to the request's session. """ if messages: self.request.session[self.session_key] = messages else: self.request.session.pop(self.session_key, None) return []
1,213
Python
.py
28
35
78
0.638136
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,860
user_messages.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/tests/user_messages.py
from django import http from django.contrib.auth.models import User from django.contrib.messages.storage.user_messages import UserMessagesStorage,\ LegacyFallbackStorage from django.contrib.messages.tests.cookie import set_cookie_data from django.contrib.messages.tests.fallback import FallbackTest from django.test import TestCase class UserMessagesTest(TestCase): def setUp(self): self.user = User.objects.create(username='tester') def test_add(self): storage = UserMessagesStorage(http.HttpRequest()) self.assertRaises(NotImplementedError, storage.add, 'Test message 1') def test_get_anonymous(self): # Ensure that the storage still works if no user is attached to the # request. storage = UserMessagesStorage(http.HttpRequest()) self.assertEqual(len(storage), 0) def test_get(self): storage = UserMessagesStorage(http.HttpRequest()) storage.request.user = self.user self.user.message_set.create(message='test message') self.assertEqual(len(storage), 1) self.assertEqual(list(storage)[0].message, 'test message') class LegacyFallbackTest(FallbackTest, TestCase): storage_class = LegacyFallbackStorage def setUp(self): super(LegacyFallbackTest, self).setUp() self.user = User.objects.create(username='tester') def get_request(self, *args, **kwargs): request = super(LegacyFallbackTest, self).get_request(*args, **kwargs) request.user = self.user return request def test_get_legacy_only(self): request = self.get_request() storage = self.storage_class(request) self.user.message_set.create(message='user message') # Test that the message actually contains what we expect. self.assertEqual(len(storage), 1) self.assertEqual(list(storage)[0].message, 'user message') def test_get_legacy(self): request = self.get_request() storage = self.storage_class(request) cookie_storage = self.get_cookie_storage(storage) self.user.message_set.create(message='user message') set_cookie_data(cookie_storage, ['cookie']) # Test that the message actually contains what we expect. self.assertEqual(len(storage), 2) self.assertEqual(list(storage)[0].message, 'user message') self.assertEqual(list(storage)[1], 'cookie')
2,414
Python
.py
50
41.06
79
0.707961
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,861
fallback.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/tests/fallback.py
from django.contrib.messages import constants from django.contrib.messages.storage.fallback import FallbackStorage, \ CookieStorage from django.contrib.messages.tests.base import BaseTest from django.contrib.messages.tests.cookie import set_cookie_data, \ stored_cookie_messages_count from django.contrib.messages.tests.session import set_session_data, \ stored_session_messages_count class FallbackTest(BaseTest): storage_class = FallbackStorage def get_request(self): self.session = {} request = super(FallbackTest, self).get_request() request.session = self.session return request def get_cookie_storage(self, storage): return storage.storages[-2] def get_session_storage(self, storage): return storage.storages[-1] def stored_cookie_messages_count(self, storage, response): return stored_cookie_messages_count(self.get_cookie_storage(storage), response) def stored_session_messages_count(self, storage, response): return stored_session_messages_count(self.get_session_storage(storage)) def stored_messages_count(self, storage, response): """ Return the storage totals from both cookie and session backends. """ total = (self.stored_cookie_messages_count(storage, response) + self.stored_session_messages_count(storage, response)) return total def test_get(self): request = self.get_request() storage = self.storage_class(request) cookie_storage = self.get_cookie_storage(storage) # Set initial cookie data. example_messages = [str(i) for i in range(5)] set_cookie_data(cookie_storage, example_messages) # Overwrite the _get method of the fallback storage to prove it is not # used (it would cause a TypeError: 'NoneType' object is not callable). self.get_session_storage(storage)._get = None # Test that the message actually contains what we expect. self.assertEqual(list(storage), example_messages) def test_get_empty(self): request = self.get_request() storage = self.storage_class(request) # Overwrite the _get method of the fallback storage to prove it is not # used (it would cause a TypeError: 'NoneType' object is not callable). self.get_session_storage(storage)._get = None # Test that the message actually contains what we expect. self.assertEqual(list(storage), []) def test_get_fallback(self): request = self.get_request() storage = self.storage_class(request) cookie_storage = self.get_cookie_storage(storage) session_storage = self.get_session_storage(storage) # Set initial cookie and session data. example_messages = [str(i) for i in range(5)] set_cookie_data(cookie_storage, example_messages[:4] + [CookieStorage.not_finished]) set_session_data(session_storage, example_messages[4:]) # Test that the message actually contains what we expect. self.assertEqual(list(storage), example_messages) def test_get_fallback_only(self): request = self.get_request() storage = self.storage_class(request) cookie_storage = self.get_cookie_storage(storage) session_storage = self.get_session_storage(storage) # Set initial cookie and session data. example_messages = [str(i) for i in range(5)] set_cookie_data(cookie_storage, [CookieStorage.not_finished], encode_empty=True) set_session_data(session_storage, example_messages) # Test that the message actually contains what we expect. self.assertEqual(list(storage), example_messages) def test_flush_used_backends(self): request = self.get_request() storage = self.storage_class(request) cookie_storage = self.get_cookie_storage(storage) session_storage = self.get_session_storage(storage) # Set initial cookie and session data. set_cookie_data(cookie_storage, ['cookie', CookieStorage.not_finished]) set_session_data(session_storage, ['session']) # When updating, previously used but no longer needed backends are # flushed. response = self.get_response() list(storage) storage.update(response) session_storing = self.stored_session_messages_count(storage, response) self.assertEqual(session_storing, 0) def test_no_fallback(self): """ Confirms that: (1) A short number of messages whose data size doesn't exceed what is allowed in a cookie will all be stored in the CookieBackend. (2) If the CookieBackend can store all messages, the SessionBackend won't be written to at all. """ storage = self.get_storage() response = self.get_response() # Overwrite the _store method of the fallback storage to prove it isn't # used (it would cause a TypeError: 'NoneType' object is not callable). self.get_session_storage(storage)._store = None for i in range(5): storage.add(constants.INFO, str(i) * 100) storage.update(response) cookie_storing = self.stored_cookie_messages_count(storage, response) self.assertEqual(cookie_storing, 5) session_storing = self.stored_session_messages_count(storage, response) self.assertEqual(session_storing, 0) def test_session_fallback(self): """ Confirms that, if the data exceeds what is allowed in a cookie, messages which did not fit are stored in the SessionBackend. """ storage = self.get_storage() response = self.get_response() # see comment in CookieText.test_cookie_max_length msg_size = int((CookieStorage.max_cookie_size - 54) / 4.5 - 37) for i in range(5): storage.add(constants.INFO, str(i) * msg_size) storage.update(response) cookie_storing = self.stored_cookie_messages_count(storage, response) self.assertEqual(cookie_storing, 4) session_storing = self.stored_session_messages_count(storage, response) self.assertEqual(session_storing, 1) def test_session_fallback_only(self): """ Confirms that large messages, none of which fit in a cookie, are stored in the SessionBackend (and nothing is stored in the CookieBackend). """ storage = self.get_storage() response = self.get_response() storage.add(constants.INFO, 'x' * 5000) storage.update(response) cookie_storing = self.stored_cookie_messages_count(storage, response) self.assertEqual(cookie_storing, 0) session_storing = self.stored_session_messages_count(storage, response) self.assertEqual(session_storing, 1)
6,978
Python
.py
139
41.194245
79
0.672938
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,862
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/tests/urls.py
from django.conf.urls.defaults import * from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext, Template def add(request, message_type): # don't default to False here, because we want to test that it defaults # to False if unspecified fail_silently = request.POST.get('fail_silently', None) for msg in request.POST.getlist('messages'): if fail_silently is not None: getattr(messages, message_type)(request, msg, fail_silently=fail_silently) else: getattr(messages, message_type)(request, msg) show_url = reverse('django.contrib.messages.tests.urls.show') return HttpResponseRedirect(show_url) def show(request): t = Template("""{% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}> {{ message }} </li> {% endfor %} </ul> {% endif %}""") return HttpResponse(t.render(RequestContext(request))) urlpatterns = patterns('', ('^add/(debug|info|success|warning|error)/$', add), ('^show/$', show), )
1,302
Python
.py
33
33.787879
75
0.675376
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,863
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/tests/__init__.py
from django.contrib.messages.tests.cookie import CookieTest from django.contrib.messages.tests.fallback import FallbackTest from django.contrib.messages.tests.middleware import MiddlewareTest from django.contrib.messages.tests.session import SessionTest from django.contrib.messages.tests.user_messages import \ UserMessagesTest, LegacyFallbackTest
392
Python
.py
6
57.166667
79
0.787565
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,864
base.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/tests/base.py
from django import http from django.test import TestCase from django.conf import settings from django.utils.translation import ugettext_lazy from django.contrib.messages import constants, utils, get_level, set_level from django.contrib.messages.api import MessageFailure from django.contrib.messages.storage import default_storage, base from django.contrib.messages.storage.base import Message from django.core.urlresolvers import reverse from django.contrib.auth.models import User def add_level_messages(storage): """ Adds 6 messages from different levels (including a custom one) to a storage instance. """ storage.add(constants.INFO, 'A generic info message') storage.add(29, 'Some custom level') storage.add(constants.DEBUG, 'A debugging message', extra_tags='extra-tag') storage.add(constants.WARNING, 'A warning') storage.add(constants.ERROR, 'An error') storage.add(constants.SUCCESS, 'This was a triumph.') class BaseTest(TestCase): storage_class = default_storage restore_settings = ['MESSAGE_LEVEL', 'MESSAGE_TAGS'] urls = 'django.contrib.messages.tests.urls' levels = { 'debug': constants.DEBUG, 'info': constants.INFO, 'success': constants.SUCCESS, 'warning': constants.WARNING, 'error': constants.ERROR, } def setUp(self): self._remembered_settings = {} for setting in self.restore_settings: if hasattr(settings, setting): self._remembered_settings[setting] = getattr(settings, setting) delattr(settings._wrapped, setting) # Backup these manually because we do not want them deleted. self._middleware_classes = settings.MIDDLEWARE_CLASSES self._template_context_processors = \ settings.TEMPLATE_CONTEXT_PROCESSORS self._installed_apps = settings.INSTALLED_APPS self._message_storage = settings.MESSAGE_STORAGE settings.MESSAGE_STORAGE = '%s.%s' % (self.storage_class.__module__, self.storage_class.__name__) self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS settings.TEMPLATE_DIRS = () def tearDown(self): for setting in self.restore_settings: self.restore_setting(setting) # Restore these manually (see above). settings.MIDDLEWARE_CLASSES = self._middleware_classes settings.TEMPLATE_CONTEXT_PROCESSORS = \ self._template_context_processors settings.INSTALLED_APPS = self._installed_apps settings.MESSAGE_STORAGE = self._message_storage settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS def restore_setting(self, setting): if setting in self._remembered_settings: value = self._remembered_settings.pop(setting) setattr(settings, setting, value) elif hasattr(settings, setting): delattr(settings._wrapped, setting) def get_request(self): return http.HttpRequest() def get_response(self): return http.HttpResponse() def get_storage(self, data=None): """ Returns the storage backend, setting its loaded data to the ``data`` argument. This method avoids the storage ``_get`` method from getting called so that other parts of the storage backend can be tested independent of the message retrieval logic. """ storage = self.storage_class(self.get_request()) storage._loaded_data = data or [] return storage def test_add(self): storage = self.get_storage() self.assertFalse(storage.added_new) storage.add(constants.INFO, 'Test message 1') self.assert_(storage.added_new) storage.add(constants.INFO, 'Test message 2', extra_tags='tag') self.assertEqual(len(storage), 2) def test_add_lazy_translation(self): storage = self.get_storage() response = self.get_response() storage.add(constants.INFO, ugettext_lazy('lazy message')) storage.update(response) storing = self.stored_messages_count(storage, response) self.assertEqual(storing, 1) def test_no_update(self): storage = self.get_storage() response = self.get_response() storage.update(response) storing = self.stored_messages_count(storage, response) self.assertEqual(storing, 0) def test_add_update(self): storage = self.get_storage() response = self.get_response() storage.add(constants.INFO, 'Test message 1') storage.add(constants.INFO, 'Test message 1', extra_tags='tag') storage.update(response) storing = self.stored_messages_count(storage, response) self.assertEqual(storing, 2) def test_existing_add_read_update(self): storage = self.get_existing_storage() response = self.get_response() storage.add(constants.INFO, 'Test message 3') list(storage) # Simulates a read storage.update(response) storing = self.stored_messages_count(storage, response) self.assertEqual(storing, 0) def test_existing_read_add_update(self): storage = self.get_existing_storage() response = self.get_response() list(storage) # Simulates a read storage.add(constants.INFO, 'Test message 3') storage.update(response) storing = self.stored_messages_count(storage, response) self.assertEqual(storing, 1) def test_full_request_response_cycle(self): """ With the message middleware enabled, tests that messages are properly stored and then retrieved across the full request/redirect/response cycle. """ settings.MESSAGE_LEVEL = constants.DEBUG data = { 'messages': ['Test message %d' % x for x in xrange(10)], } show_url = reverse('django.contrib.messages.tests.urls.show') for level in ('debug', 'info', 'success', 'warning', 'error'): add_url = reverse('django.contrib.messages.tests.urls.add', args=(level,)) response = self.client.post(add_url, data, follow=True) self.assertRedirects(response, show_url) self.assertTrue('messages' in response.context) messages = [Message(self.levels[level], msg) for msg in data['messages']] self.assertEqual(list(response.context['messages']), messages) for msg in data['messages']: self.assertContains(response, msg) def test_multiple_posts(self): """ Tests that messages persist properly when multiple POSTs are made before a GET. """ settings.MESSAGE_LEVEL = constants.DEBUG data = { 'messages': ['Test message %d' % x for x in xrange(10)], } show_url = reverse('django.contrib.messages.tests.urls.show') messages = [] for level in ('debug', 'info', 'success', 'warning', 'error'): messages.extend([Message(self.levels[level], msg) for msg in data['messages']]) add_url = reverse('django.contrib.messages.tests.urls.add', args=(level,)) self.client.post(add_url, data) response = self.client.get(show_url) self.assertTrue('messages' in response.context) self.assertEqual(list(response.context['messages']), messages) for msg in data['messages']: self.assertContains(response, msg) def test_middleware_disabled_auth_user(self): """ Tests that the messages API successfully falls back to using user.message_set to store messages directly when the middleware is disabled. """ settings.MESSAGE_LEVEL = constants.DEBUG user = User.objects.create_user('test', '[email protected]', 'test') self.client.login(username='test', password='test') settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) settings.INSTALLED_APPS.remove( 'django.contrib.messages', ) settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) settings.MIDDLEWARE_CLASSES.remove( 'django.contrib.messages.middleware.MessageMiddleware', ) settings.TEMPLATE_CONTEXT_PROCESSORS = \ list(settings.TEMPLATE_CONTEXT_PROCESSORS) settings.TEMPLATE_CONTEXT_PROCESSORS.remove( 'django.contrib.messages.context_processors.messages', ) data = { 'messages': ['Test message %d' % x for x in xrange(10)], } show_url = reverse('django.contrib.messages.tests.urls.show') for level in ('debug', 'info', 'success', 'warning', 'error'): add_url = reverse('django.contrib.messages.tests.urls.add', args=(level,)) response = self.client.post(add_url, data, follow=True) self.assertRedirects(response, show_url) self.assertTrue('messages' in response.context) context_messages = list(response.context['messages']) for msg in data['messages']: self.assertTrue(msg in context_messages) self.assertContains(response, msg) def test_middleware_disabled_anon_user(self): """ Tests that, when the middleware is disabled and a user is not logged in, an exception is raised when one attempts to store a message. """ settings.MESSAGE_LEVEL = constants.DEBUG settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) settings.INSTALLED_APPS.remove( 'django.contrib.messages', ) settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) settings.MIDDLEWARE_CLASSES.remove( 'django.contrib.messages.middleware.MessageMiddleware', ) settings.TEMPLATE_CONTEXT_PROCESSORS = \ list(settings.TEMPLATE_CONTEXT_PROCESSORS) settings.TEMPLATE_CONTEXT_PROCESSORS.remove( 'django.contrib.messages.context_processors.messages', ) data = { 'messages': ['Test message %d' % x for x in xrange(10)], } show_url = reverse('django.contrib.messages.tests.urls.show') for level in ('debug', 'info', 'success', 'warning', 'error'): add_url = reverse('django.contrib.messages.tests.urls.add', args=(level,)) self.assertRaises(MessageFailure, self.client.post, add_url, data, follow=True) def test_middleware_disabled_anon_user_fail_silently(self): """ Tests that, when the middleware is disabled and a user is not logged in, an exception is not raised if 'fail_silently' = True """ settings.MESSAGE_LEVEL = constants.DEBUG settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) settings.INSTALLED_APPS.remove( 'django.contrib.messages', ) settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) settings.MIDDLEWARE_CLASSES.remove( 'django.contrib.messages.middleware.MessageMiddleware', ) settings.TEMPLATE_CONTEXT_PROCESSORS = \ list(settings.TEMPLATE_CONTEXT_PROCESSORS) settings.TEMPLATE_CONTEXT_PROCESSORS.remove( 'django.contrib.messages.context_processors.messages', ) data = { 'messages': ['Test message %d' % x for x in xrange(10)], 'fail_silently': True, } show_url = reverse('django.contrib.messages.tests.urls.show') for level in ('debug', 'info', 'success', 'warning', 'error'): add_url = reverse('django.contrib.messages.tests.urls.add', args=(level,)) response = self.client.post(add_url, data, follow=True) self.assertRedirects(response, show_url) self.assertTrue('messages' in response.context) self.assertEqual(list(response.context['messages']), []) def stored_messages_count(self, storage, response): """ Returns the number of messages being stored after a ``storage.update()`` call. """ raise NotImplementedError('This method must be set by a subclass.') def test_get(self): raise NotImplementedError('This method must be set by a subclass.') def get_existing_storage(self): return self.get_storage([Message(constants.INFO, 'Test message 1'), Message(constants.INFO, 'Test message 2', extra_tags='tag')]) def test_existing_read(self): """ Tests that reading the existing storage doesn't cause the data to be lost. """ storage = self.get_existing_storage() self.assertFalse(storage.used) # After iterating the storage engine directly, the used flag is set. data = list(storage) self.assert_(storage.used) # The data does not disappear because it has been iterated. self.assertEqual(data, list(storage)) def test_existing_add(self): storage = self.get_existing_storage() self.assertFalse(storage.added_new) storage.add(constants.INFO, 'Test message 3') self.assert_(storage.added_new) def test_default_level(self): # get_level works even with no storage on the request. request = self.get_request() self.assertEqual(get_level(request), constants.INFO) # get_level returns the default level if it hasn't been set. storage = self.get_storage() request._messages = storage self.assertEqual(get_level(request), constants.INFO) # Only messages of sufficient level get recorded. add_level_messages(storage) self.assertEqual(len(storage), 5) def test_low_level(self): request = self.get_request() storage = self.storage_class(request) request._messages = storage self.assert_(set_level(request, 5)) self.assertEqual(get_level(request), 5) add_level_messages(storage) self.assertEqual(len(storage), 6) def test_high_level(self): request = self.get_request() storage = self.storage_class(request) request._messages = storage self.assert_(set_level(request, 30)) self.assertEqual(get_level(request), 30) add_level_messages(storage) self.assertEqual(len(storage), 2) def test_settings_level(self): request = self.get_request() storage = self.storage_class(request) settings.MESSAGE_LEVEL = 29 self.assertEqual(get_level(request), 29) add_level_messages(storage) self.assertEqual(len(storage), 3) def test_tags(self): storage = self.get_storage() storage.level = 0 add_level_messages(storage) tags = [msg.tags for msg in storage] self.assertEqual(tags, ['info', '', 'extra-tag debug', 'warning', 'error', 'success']) def test_custom_tags(self): settings.MESSAGE_TAGS = { constants.INFO: 'info', constants.DEBUG: '', constants.WARNING: '', constants.ERROR: 'bad', 29: 'custom', } # LEVEL_TAGS is a constant defined in the # django.contrib.messages.storage.base module, so after changing # settings.MESSAGE_TAGS, we need to update that constant too. base.LEVEL_TAGS = utils.get_level_tags() try: storage = self.get_storage() storage.level = 0 add_level_messages(storage) tags = [msg.tags for msg in storage] self.assertEqual(tags, ['info', 'custom', 'extra-tag', '', 'bad', 'success']) finally: # Ensure the level tags constant is put back like we found it. self.restore_setting('MESSAGE_TAGS') base.LEVEL_TAGS = utils.get_level_tags()
16,343
Python
.py
356
35.648876
79
0.628059
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,865
middleware.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/tests/middleware.py
import unittest from django import http from django.contrib.messages.middleware import MessageMiddleware class MiddlewareTest(unittest.TestCase): def setUp(self): self.middleware = MessageMiddleware() def test_response_without_messages(self): """ Makes sure that the response middleware is tolerant of messages not existing on request. """ request = http.HttpRequest() response = http.HttpResponse() self.middleware.process_response(request, response)
528
Python
.py
14
31.285714
75
0.721569
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,866
cookie.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/tests/cookie.py
from django.contrib.messages import constants from django.contrib.messages.tests.base import BaseTest from django.contrib.messages.storage.cookie import CookieStorage, \ MessageEncoder, MessageDecoder from django.contrib.messages.storage.base import Message from django.utils import simplejson as json def set_cookie_data(storage, messages, invalid=False, encode_empty=False): """ Sets ``request.COOKIES`` with the encoded data and removes the storage backend's loaded data cache. """ encoded_data = storage._encode(messages, encode_empty=encode_empty) if invalid: # Truncate the first character so that the hash is invalid. encoded_data = encoded_data[1:] storage.request.COOKIES = {CookieStorage.cookie_name: encoded_data} if hasattr(storage, '_loaded_data'): del storage._loaded_data def stored_cookie_messages_count(storage, response): """ Returns an integer containing the number of messages stored. """ # Get a list of cookies, excluding ones with a max-age of 0 (because # they have been marked for deletion). cookie = response.cookies.get(storage.cookie_name) if not cookie or cookie['max-age'] == 0: return 0 data = storage._decode(cookie.value) if not data: return 0 if data[-1] == CookieStorage.not_finished: data.pop() return len(data) class CookieTest(BaseTest): storage_class = CookieStorage def stored_messages_count(self, storage, response): return stored_cookie_messages_count(storage, response) def test_get(self): storage = self.storage_class(self.get_request()) # Set initial data. example_messages = ['test', 'me'] set_cookie_data(storage, example_messages) # Test that the message actually contains what we expect. self.assertEqual(list(storage), example_messages) def test_get_bad_cookie(self): request = self.get_request() storage = self.storage_class(request) # Set initial (invalid) data. example_messages = ['test', 'me'] set_cookie_data(storage, example_messages, invalid=True) # Test that the message actually contains what we expect. self.assertEqual(list(storage), []) def test_max_cookie_length(self): """ Tests that, if the data exceeds what is allowed in a cookie, older messages are removed before saving (and returned by the ``update`` method). """ storage = self.get_storage() response = self.get_response() # When storing as a cookie, the cookie has constant overhead of approx # 54 chars, and each message has a constant overhead of about 37 chars # and a variable overhead of zero in the best case. We aim for a message # size which will fit 4 messages into the cookie, but not 5. # See also FallbackTest.test_session_fallback msg_size = int((CookieStorage.max_cookie_size - 54) / 4.5 - 37) for i in range(5): storage.add(constants.INFO, str(i) * msg_size) unstored_messages = storage.update(response) cookie_storing = self.stored_messages_count(storage, response) self.assertEqual(cookie_storing, 4) self.assertEqual(len(unstored_messages), 1) self.assert_(unstored_messages[0].message == '0' * msg_size) def test_json_encoder_decoder(self): """ Tests that a complex nested data structure containing Message instances is properly encoded/decoded by the custom JSON encoder/decoder classes. """ messages = [ { 'message': Message(constants.INFO, 'Test message'), 'message_list': [Message(constants.INFO, 'message %s') \ for x in xrange(5)] + [{'another-message': \ Message(constants.ERROR, 'error')}], }, Message(constants.INFO, 'message %s'), ] encoder = MessageEncoder(separators=(',', ':')) value = encoder.encode(messages) decoded_messages = json.loads(value, cls=MessageDecoder) self.assertEqual(messages, decoded_messages)
4,272
Python
.py
92
37.782609
80
0.652904
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,867
session.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/messages/tests/session.py
from django.contrib.messages.tests.base import BaseTest from django.contrib.messages.storage.session import SessionStorage def set_session_data(storage, messages): """ Sets the messages into the backend request's session and remove the backend's loaded data cache. """ storage.request.session[storage.session_key] = messages if hasattr(storage, '_loaded_data'): del storage._loaded_data def stored_session_messages_count(storage): data = storage.request.session.get(storage.session_key, []) return len(data) class SessionTest(BaseTest): storage_class = SessionStorage def get_request(self): self.session = {} request = super(SessionTest, self).get_request() request.session = self.session return request def stored_messages_count(self, storage, response): return stored_session_messages_count(storage) def test_get(self): storage = self.storage_class(self.get_request()) # Set initial data. example_messages = ['test', 'me'] set_session_data(storage, example_messages) # Test that the message actually contains what we expect. self.assertEqual(list(storage), example_messages)
1,230
Python
.py
29
36.137931
71
0.709732
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,868
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/flatpages/models.py
from django.db import models from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ class FlatPage(models.Model): url = models.CharField(_('URL'), max_length=100, db_index=True) title = models.CharField(_('title'), max_length=200) content = models.TextField(_('content'), blank=True) enable_comments = models.BooleanField(_('enable comments')) template_name = models.CharField(_('template name'), max_length=70, blank=True, help_text=_("Example: 'flatpages/contact_page.html'. If this isn't provided, the system will use 'flatpages/default.html'.")) registration_required = models.BooleanField(_('registration required'), help_text=_("If this is checked, only logged-in users will be able to view the page.")) sites = models.ManyToManyField(Site) class Meta: db_table = 'django_flatpage' verbose_name = _('flat page') verbose_name_plural = _('flat pages') ordering = ('url',) def __unicode__(self): return u"%s -- %s" % (self.url, self.title) def get_absolute_url(self): return self.url
1,134
Python
.py
21
48.190476
163
0.685018
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,869
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/flatpages/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('django.contrib.flatpages.views', (r'^(?P<url>.*)$', 'flatpage'), )
136
Python
.py
4
31.75
56
0.694656
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,870
admin.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/flatpages/admin.py
from django import forms from django.contrib import admin from django.contrib.flatpages.models import FlatPage from django.utils.translation import ugettext_lazy as _ class FlatpageForm(forms.ModelForm): url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/]+$', help_text = _("Example: '/about/contact/'. Make sure to have leading" " and trailing slashes."), error_message = _("This value must contain only letters, numbers," " underscores, dashes or slashes.")) class Meta: model = FlatPage class FlatPageAdmin(admin.ModelAdmin): form = FlatpageForm fieldsets = ( (None, {'fields': ('url', 'title', 'content', 'sites')}), (_('Advanced options'), {'classes': ('collapse',), 'fields': ('enable_comments', 'registration_required', 'template_name')}), ) list_display = ('url', 'title') list_filter = ('sites', 'enable_comments', 'registration_required') search_fields = ('url', 'title') admin.site.register(FlatPage, FlatPageAdmin)
1,072
Python
.py
22
42
133
0.648467
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,871
middleware.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/flatpages/middleware.py
from django.contrib.flatpages.views import flatpage from django.http import Http404 from django.conf import settings class FlatpageFallbackMiddleware(object): def process_response(self, request, response): if response.status_code != 404: return response # No need to check for a flatpage for non-404 responses. try: return flatpage(request, request.path_info) # Return the original response if any errors happened. Because this # is a middleware, we can't assume the errors will be caught elsewhere. except Http404: return response except: if settings.DEBUG: raise return response
710
Python
.py
17
33.176471
84
0.679191
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,872
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/flatpages/views.py
from django.contrib.flatpages.models import FlatPage from django.template import loader, RequestContext from django.shortcuts import get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from django.core.xheaders import populate_xheaders from django.utils.safestring import mark_safe from django.views.decorators.csrf import csrf_protect DEFAULT_TEMPLATE = 'flatpages/default.html' # This view is called from FlatpageFallbackMiddleware.process_response # when a 404 is raised, which often means CsrfViewMiddleware.process_view # has not been called even if CsrfViewMiddleware is installed. So we need # to use @csrf_protect, in case the template needs {% csrf_token %}. # However, we can't just wrap this view; if no matching flatpage exists, # or a redirect is required for authentication, the 404 needs to be returned # without any CSRF checks. Therefore, we only # CSRF protect the internal implementation. def flatpage(request, url): """ Public interface to the flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or `flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.endswith('/') and settings.APPEND_SLASH: return HttpResponseRedirect("%s/" % request.path) if not url.startswith('/'): url = "/" + url f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID) return render_flatpage(request, f) @csrf_protect def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) c = RequestContext(request, { 'flatpage': f, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, FlatPage, f.id) return response
2,613
Python
.py
58
40.568966
86
0.735975
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,873
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/flatpages/tests/urls.py
from django.conf.urls.defaults import * # special urls for flatpage test cases urlpatterns = patterns('', (r'^flatpage_root', include('django.contrib.flatpages.urls')), (r'^accounts/', include('django.contrib.auth.urls')), )
235
Python
.py
6
36.5
66
0.726872
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,874
csrf.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/flatpages/tests/csrf.py
import os from django.conf import settings from django.test import TestCase, Client class FlatpageCSRFTests(TestCase): fixtures = ['sample_flatpages'] urls = 'django.contrib.flatpages.tests.urls' def setUp(self): self.client = Client(enforce_csrf_checks=True) self.old_MIDDLEWARE_CLASSES = settings.MIDDLEWARE_CLASSES flatpage_middleware_class = 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware' csrf_middleware_class = 'django.middleware.csrf.CsrfViewMiddleware' if csrf_middleware_class not in settings.MIDDLEWARE_CLASSES: settings.MIDDLEWARE_CLASSES += (csrf_middleware_class,) if flatpage_middleware_class not in settings.MIDDLEWARE_CLASSES: settings.MIDDLEWARE_CLASSES += (flatpage_middleware_class,) self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS settings.TEMPLATE_DIRS = ( os.path.join( os.path.dirname(__file__), 'templates' ), ) self.old_LOGIN_URL = settings.LOGIN_URL settings.LOGIN_URL = '/accounts/login/' def tearDown(self): settings.MIDDLEWARE_CLASSES = self.old_MIDDLEWARE_CLASSES settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS settings.LOGIN_URL = self.old_LOGIN_URL def test_view_flatpage(self): "A flatpage can be served through a view, even when the middleware is in use" response = self.client.get('/flatpage_root/flatpage/') self.assertEquals(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>") def test_view_non_existent_flatpage(self): "A non-existent flatpage raises 404 when served through a view, even when the middleware is in use" response = self.client.get('/flatpage_root/no_such_flatpage/') self.assertEquals(response.status_code, 404) def test_view_authenticated_flatpage(self): "A flatpage served through a view can require authentication" response = self.client.get('/flatpage_root/sekrit/') self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/') def test_fallback_flatpage(self): "A flatpage can be served by the fallback middlware" response = self.client.get('/flatpage/') self.assertEquals(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>") def test_fallback_non_existent_flatpage(self): "A non-existent flatpage raises a 404 when served by the fallback middlware" response = self.client.get('/no_such_flatpage/') self.assertEquals(response.status_code, 404) def test_post_view_flatpage(self): "POSTing to a flatpage served through a view will raise a CSRF error if no token is provided (Refs #14156)" response = self.client.post('/flatpage_root/flatpage/') self.assertEquals(response.status_code, 403) def test_post_fallback_flatpage(self): "POSTing to a flatpage served by the middleware will raise a CSRF error if no token is provided (Refs #14156)" response = self.client.post('/flatpage/') self.assertEquals(response.status_code, 403) def test_post_unknown_page(self): "POSTing to an unknown page isn't caught as a 403 CSRF error" response = self.client.post('/no_such_page/') self.assertEquals(response.status_code, 404)
3,425
Python
.py
62
46.83871
118
0.693616
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,875
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/flatpages/tests/__init__.py
from django.contrib.flatpages.tests.csrf import * from django.contrib.flatpages.tests.middleware import * from django.contrib.flatpages.tests.views import *
157
Python
.py
3
51.333333
55
0.844156
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,876
middleware.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/flatpages/tests/middleware.py
import os from django.conf import settings from django.test import TestCase class FlatpageMiddlewareTests(TestCase): fixtures = ['sample_flatpages'] urls = 'django.contrib.flatpages.tests.urls' def setUp(self): self.old_MIDDLEWARE_CLASSES = settings.MIDDLEWARE_CLASSES flatpage_middleware_class = 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware' if flatpage_middleware_class not in settings.MIDDLEWARE_CLASSES: settings.MIDDLEWARE_CLASSES += (flatpage_middleware_class,) self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS settings.TEMPLATE_DIRS = ( os.path.join( os.path.dirname(__file__), 'templates' ), ) self.old_LOGIN_URL = settings.LOGIN_URL settings.LOGIN_URL = '/accounts/login/' def tearDown(self): settings.MIDDLEWARE_CLASSES = self.old_MIDDLEWARE_CLASSES settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS settings.LOGIN_URL = self.old_LOGIN_URL def test_view_flatpage(self): "A flatpage can be served through a view, even when the middleware is in use" response = self.client.get('/flatpage_root/flatpage/') self.assertEquals(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>") def test_view_non_existent_flatpage(self): "A non-existent flatpage raises 404 when served through a view, even when the middleware is in use" response = self.client.get('/flatpage_root/no_such_flatpage/') self.assertEquals(response.status_code, 404) def test_view_authenticated_flatpage(self): "A flatpage served through a view can require authentication" response = self.client.get('/flatpage_root/sekrit/') self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/') def test_fallback_flatpage(self): "A flatpage can be served by the fallback middlware" response = self.client.get('/flatpage/') self.assertEquals(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>") def test_fallback_non_existent_flatpage(self): "A non-existent flatpage raises a 404 when served by the fallback middlware" response = self.client.get('/no_such_flatpage/') self.assertEquals(response.status_code, 404) def test_fallback_authenticated_flatpage(self): "A flatpage served by the middleware can require authentication" response = self.client.get('/sekrit/') self.assertRedirects(response, '/accounts/login/?next=/sekrit/')
2,646
Python
.py
50
44.62
107
0.692694
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,877
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/flatpages/tests/views.py
import os from django.conf import settings from django.test import TestCase class FlatpageViewTests(TestCase): fixtures = ['sample_flatpages'] urls = 'django.contrib.flatpages.tests.urls' def setUp(self): self.old_MIDDLEWARE_CLASSES = settings.MIDDLEWARE_CLASSES flatpage_middleware_class = 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware' if flatpage_middleware_class in settings.MIDDLEWARE_CLASSES: settings.MIDDLEWARE_CLASSES = tuple(m for m in settings.MIDDLEWARE_CLASSES if m != flatpage_middleware_class) self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS settings.TEMPLATE_DIRS = ( os.path.join( os.path.dirname(__file__), 'templates' ), ) self.old_LOGIN_URL = settings.LOGIN_URL settings.LOGIN_URL = '/accounts/login/' def tearDown(self): settings.MIDDLEWARE_CLASSES = self.old_MIDDLEWARE_CLASSES settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS settings.LOGIN_URL = self.old_LOGIN_URL def test_view_flatpage(self): "A flatpage can be served through a view" response = self.client.get('/flatpage_root/flatpage/') self.assertEquals(response.status_code, 200) self.assertContains(response, "<p>Isn't it flat!</p>") def test_view_non_existent_flatpage(self): "A non-existent flatpage raises 404 when served through a view" response = self.client.get('/flatpage_root/no_such_flatpage/') self.assertEquals(response.status_code, 404) def test_view_authenticated_flatpage(self): "A flatpage served through a view can require authentication" response = self.client.get('/flatpage_root/sekrit/') self.assertRedirects(response, '/accounts/login/?next=/flatpage_root/sekrit/') def test_fallback_flatpage(self): "A fallback flatpage won't be served if the middleware is disabled" response = self.client.get('/flatpage/') self.assertEquals(response.status_code, 404) def test_fallback_non_existent_flatpage(self): "A non-existent flatpage won't be served if the fallback middlware is disabled" response = self.client.get('/no_such_flatpage/') self.assertEquals(response.status_code, 404)
2,323
Python
.py
45
43.333333
121
0.692511
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,878
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sessions/models.py
import base64 import cPickle as pickle from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.utils.hashcompat import md5_constructor class SessionManager(models.Manager): def encode(self, session_dict): """ Returns the given session dictionary pickled and encoded as a string. """ pickled = pickle.dumps(session_dict) pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest() return base64.encodestring(pickled + pickled_md5) def save(self, session_key, session_dict, expire_date): s = self.model(session_key, self.encode(session_dict), expire_date) if session_dict: s.save() else: s.delete() # Clear sessions with no data. return s class Session(models.Model): """ Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID -- not the data itself. The Django sessions framework is entirely cookie-based. It does not fall back to putting session IDs in URLs. This is an intentional design decision. Not only does that behavior make URLs ugly, it makes your site vulnerable to session-ID theft via the "Referer" header. For complete documentation on using Sessions in your code, consult the sessions documentation that is shipped with Django (also available on the Django Web site). """ session_key = models.CharField(_('session key'), max_length=40, primary_key=True) session_data = models.TextField(_('session data')) expire_date = models.DateTimeField(_('expire date')) objects = SessionManager() class Meta: db_table = 'django_session' verbose_name = _('session') verbose_name_plural = _('sessions') def get_decoded(self): encoded_data = base64.decodestring(self.session_data) pickled, tamper_check = encoded_data[:-32], encoded_data[-32:] if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check: from django.core.exceptions import SuspiciousOperation raise SuspiciousOperation("User tampered with session cookie.") try: return pickle.loads(pickled) # Unpickling can cause a variety of exceptions. If something happens, # just return an empty dictionary (an empty session). except: return {}
2,676
Python
.py
57
39.54386
86
0.692603
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,879
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sessions/tests.py
r""" >>> from django.conf import settings >>> from django.contrib.sessions.backends.db import SessionStore as DatabaseSession >>> from django.contrib.sessions.backends.cache import SessionStore as CacheSession >>> from django.contrib.sessions.backends.cached_db import SessionStore as CacheDBSession >>> from django.contrib.sessions.backends.file import SessionStore as FileSession >>> from django.contrib.sessions.backends.base import SessionBase >>> from django.contrib.sessions.models import Session >>> db_session = DatabaseSession() >>> db_session.modified False >>> db_session.get('cat') >>> db_session['cat'] = "dog" >>> db_session.modified True >>> db_session.pop('cat') 'dog' >>> db_session.pop('some key', 'does not exist') 'does not exist' >>> db_session.save() >>> db_session.exists(db_session.session_key) True >>> db_session.delete(db_session.session_key) >>> db_session.exists(db_session.session_key) False >>> db_session['foo'] = 'bar' >>> db_session.save() >>> db_session.exists(db_session.session_key) True >>> prev_key = db_session.session_key >>> db_session.flush() >>> db_session.exists(prev_key) False >>> db_session.session_key == prev_key False >>> db_session.modified, db_session.accessed (True, True) >>> db_session['a'], db_session['b'] = 'c', 'd' >>> db_session.save() >>> prev_key = db_session.session_key >>> prev_data = db_session.items() >>> db_session.cycle_key() >>> db_session.session_key == prev_key False >>> db_session.items() == prev_data True # Submitting an invalid session key (either by guessing, or if the db has # removed the key) results in a new key being generated. >>> Session.objects.filter(pk=db_session.session_key).delete() >>> db_session = DatabaseSession(db_session.session_key) >>> db_session.save() >>> DatabaseSession('1').get('cat') # # Cached DB session tests # >>> cdb_session = CacheDBSession() >>> cdb_session.modified False >>> cdb_session['cat'] = "dog" >>> cdb_session.modified True >>> cdb_session.pop('cat') 'dog' >>> cdb_session.pop('some key', 'does not exist') 'does not exist' >>> cdb_session.save() >>> cdb_session.exists(cdb_session.session_key) True >>> cdb_session.delete(cdb_session.session_key) >>> cdb_session.exists(cdb_session.session_key) False # # File session tests. # # Do file session tests in an isolated directory, and kill it after we're done. >>> original_session_file_path = settings.SESSION_FILE_PATH >>> import tempfile >>> temp_session_store = settings.SESSION_FILE_PATH = tempfile.mkdtemp() >>> file_session = FileSession() >>> file_session.modified False >>> file_session['cat'] = "dog" >>> file_session.modified True >>> file_session.pop('cat') 'dog' >>> file_session.pop('some key', 'does not exist') 'does not exist' >>> file_session.save() >>> file_session.exists(file_session.session_key) True >>> file_session.delete(file_session.session_key) >>> file_session.exists(file_session.session_key) False >>> FileSession('1').get('cat') >>> file_session['foo'] = 'bar' >>> file_session.save() >>> file_session.exists(file_session.session_key) True >>> prev_key = file_session.session_key >>> file_session.flush() >>> file_session.exists(prev_key) False >>> file_session.session_key == prev_key False >>> file_session.modified, file_session.accessed (True, True) >>> file_session['a'], file_session['b'] = 'c', 'd' >>> file_session.save() >>> prev_key = file_session.session_key >>> prev_data = file_session.items() >>> file_session.cycle_key() >>> file_session.session_key == prev_key False >>> file_session.items() == prev_data True >>> Session.objects.filter(pk=file_session.session_key).delete() >>> file_session = FileSession(file_session.session_key) >>> file_session.save() # Ensure we don't allow directory traversal >>> FileSession("a/b/c").load() Traceback (innermost last): ... SuspiciousOperation: Invalid characters in session key >>> FileSession("a\\b\\c").load() Traceback (innermost last): ... SuspiciousOperation: Invalid characters in session key # Make sure the file backend checks for a good storage dir >>> settings.SESSION_FILE_PATH = "/if/this/directory/exists/you/have/a/weird/computer" >>> FileSession() Traceback (innermost last): ... ImproperlyConfigured: The session storage path '/if/this/directory/exists/you/have/a/weird/computer' doesn't exist. Please set your SESSION_FILE_PATH setting to an existing directory in which Django can store session data. # Clean up after the file tests >>> settings.SESSION_FILE_PATH = original_session_file_path >>> import shutil >>> shutil.rmtree(temp_session_store) # # Cache-based tests # NB: be careful to delete any sessions created; stale sessions fill up the # /tmp and eventually overwhelm it after lots of runs (think buildbots) # >>> cache_session = CacheSession() >>> cache_session.modified False >>> cache_session['cat'] = "dog" >>> cache_session.modified True >>> cache_session.pop('cat') 'dog' >>> cache_session.pop('some key', 'does not exist') 'does not exist' >>> cache_session.save() >>> cache_session.delete(cache_session.session_key) >>> cache_session.exists(cache_session.session_key) False >>> cache_session['foo'] = 'bar' >>> cache_session.save() >>> cache_session.exists(cache_session.session_key) True >>> prev_key = cache_session.session_key >>> cache_session.flush() >>> cache_session.exists(prev_key) False >>> cache_session.session_key == prev_key False >>> cache_session.modified, cache_session.accessed (True, True) >>> cache_session['a'], cache_session['b'] = 'c', 'd' >>> cache_session.save() >>> prev_key = cache_session.session_key >>> prev_data = cache_session.items() >>> cache_session.cycle_key() >>> cache_session.session_key == prev_key False >>> cache_session.items() == prev_data True >>> cache_session = CacheSession() >>> cache_session.save() >>> key = cache_session.session_key >>> cache_session.exists(key) True >>> Session.objects.filter(pk=cache_session.session_key).delete() >>> cache_session = CacheSession(cache_session.session_key) >>> cache_session.save() >>> cache_session.delete(cache_session.session_key) >>> s = SessionBase() >>> s._session['some key'] = 'exists' # Pre-populate the session with some data >>> s.accessed = False # Reset to pretend this wasn't accessed previously >>> s.accessed, s.modified (False, False) >>> s.pop('non existant key', 'does not exist') 'does not exist' >>> s.accessed, s.modified (True, False) >>> s.setdefault('foo', 'bar') 'bar' >>> s.setdefault('foo', 'baz') 'bar' >>> s.accessed = False # Reset the accessed flag >>> s.pop('some key') 'exists' >>> s.accessed, s.modified (True, True) >>> s.pop('some key', 'does not exist') 'does not exist' >>> s.get('update key', None) # test .update() >>> s.modified = s.accessed = False # Reset to pretend this wasn't accessed previously >>> s.update({'update key':1}) >>> s.accessed, s.modified (True, True) >>> s.get('update key', None) 1 # test .has_key() >>> s.modified = s.accessed = False # Reset to pretend this wasn't accessed previously >>> s.has_key('update key') True >>> s.accessed, s.modified (True, False) # test .values() >>> s = SessionBase() >>> s.values() [] >>> s.accessed True >>> s['x'] = 1 >>> s.values() [1] # test .iterkeys() >>> s.accessed = False >>> i = s.iterkeys() >>> hasattr(i,'__iter__') True >>> s.accessed True >>> list(i) ['x'] # test .itervalues() >>> s.accessed = False >>> i = s.itervalues() >>> hasattr(i,'__iter__') True >>> s.accessed True >>> list(i) [1] # test .iteritems() >>> s.accessed = False >>> i = s.iteritems() >>> hasattr(i,'__iter__') True >>> s.accessed True >>> list(i) [('x', 1)] # test .clear() >>> s.modified = s.accessed = False >>> s.items() [('x', 1)] >>> s.clear() >>> s.items() [] >>> s.accessed, s.modified (True, True) ######################### # Custom session expiry # ######################### >>> from django.conf import settings >>> from datetime import datetime, timedelta >>> td10 = timedelta(seconds=10) # A normal session has a max age equal to settings >>> s.get_expiry_age() == settings.SESSION_COOKIE_AGE True # So does a custom session with an idle expiration time of 0 (but it'll expire # at browser close) >>> s.set_expiry(0) >>> s.get_expiry_age() == settings.SESSION_COOKIE_AGE True # Custom session idle expiration time >>> s.set_expiry(10) >>> delta = s.get_expiry_date() - datetime.now() >>> delta.seconds in (9, 10) True >>> age = s.get_expiry_age() >>> age in (9, 10) True # Custom session fixed expiry date (timedelta) >>> s.set_expiry(td10) >>> delta = s.get_expiry_date() - datetime.now() >>> delta.seconds in (9, 10) True >>> age = s.get_expiry_age() >>> age in (9, 10) True # Custom session fixed expiry date (fixed datetime) >>> s.set_expiry(datetime.now() + td10) >>> delta = s.get_expiry_date() - datetime.now() >>> delta.seconds in (9, 10) True >>> age = s.get_expiry_age() >>> age in (9, 10) True # Set back to default session age >>> s.set_expiry(None) >>> s.get_expiry_age() == settings.SESSION_COOKIE_AGE True # Allow to set back to default session age even if no alternate has been set >>> s.set_expiry(None) # We're changing the setting then reverting back to the original setting at the # end of these tests. >>> original_expire_at_browser_close = settings.SESSION_EXPIRE_AT_BROWSER_CLOSE >>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Custom session age >>> s.set_expiry(10) >>> s.get_expire_at_browser_close() False # Custom expire-at-browser-close >>> s.set_expiry(0) >>> s.get_expire_at_browser_close() True # Default session age >>> s.set_expiry(None) >>> s.get_expire_at_browser_close() False >>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True # Custom session age >>> s.set_expiry(10) >>> s.get_expire_at_browser_close() False # Custom expire-at-browser-close >>> s.set_expiry(0) >>> s.get_expire_at_browser_close() True # Default session age >>> s.set_expiry(None) >>> s.get_expire_at_browser_close() True >>> settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = original_expire_at_browser_close """ if __name__ == '__main__': import doctest doctest.testmod()
10,043
Python
.py
344
27.976744
222
0.706968
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,880
middleware.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sessions/middleware.py
import time from django.conf import settings from django.utils.cache import patch_vary_headers from django.utils.http import cookie_date from django.utils.importlib import import_module class SessionMiddleware(object): def process_request(self, request): engine = import_module(settings.SESSION_ENGINE) session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None) request.session = engine.SessionStore(session_key) def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie. """ try: accessed = request.session.accessed modified = request.session.modified except AttributeError: pass else: if accessed: patch_vary_headers(response, ('Cookie',)) if modified or settings.SESSION_SAVE_EVERY_REQUEST: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = cookie_date(expires_time) # Save the session data and refresh the client cookie. request.session.save() response.set_cookie(settings.SESSION_COOKIE_NAME, request.session.session_key, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH, secure=settings.SESSION_COOKIE_SECURE or None) return response
1,813
Python
.py
39
33.923077
79
0.613213
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,881
db.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sessions/backends/db.py
import datetime from django.conf import settings from django.contrib.sessions.models import Session from django.contrib.sessions.backends.base import SessionBase, CreateError from django.core.exceptions import SuspiciousOperation from django.db import IntegrityError, transaction, router from django.utils.encoding import force_unicode class SessionStore(SessionBase): """ Implements database session store. """ def __init__(self, session_key=None): super(SessionStore, self).__init__(session_key) def load(self): try: s = Session.objects.get( session_key = self.session_key, expire_date__gt=datetime.datetime.now() ) return self.decode(force_unicode(s.session_data)) except (Session.DoesNotExist, SuspiciousOperation): self.create() return {} def exists(self, session_key): try: Session.objects.get(session_key=session_key) except Session.DoesNotExist: return False return True def create(self): while True: self.session_key = self._get_new_session_key() try: # Save immediately to ensure we have a unique entry in the # database. self.save(must_create=True) except CreateError: # Key wasn't unique. Try again. continue self.modified = True self._session_cache = {} return def save(self, must_create=False): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ obj = Session( session_key = self.session_key, session_data = self.encode(self._get_session(no_load=must_create)), expire_date = self.get_expiry_date() ) using = router.db_for_write(Session, instance=obj) sid = transaction.savepoint(using=using) try: obj.save(force_insert=must_create, using=using) except IntegrityError: if must_create: transaction.savepoint_rollback(sid, using=using) raise CreateError raise def delete(self, session_key=None): if session_key is None: if self._session_key is None: return session_key = self._session_key try: Session.objects.get(session_key=session_key).delete() except Session.DoesNotExist: pass
2,716
Python
.py
72
27.638889
79
0.609174
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,882
cached_db.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sessions/backends/cached_db.py
""" Cached, database-backed sessions. """ from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DBStore from django.core.cache import cache class SessionStore(DBStore): """ Implements cached, database backed sessions. """ def __init__(self, session_key=None): super(SessionStore, self).__init__(session_key) def load(self): data = cache.get(self.session_key, None) if data is None: data = super(SessionStore, self).load() cache.set(self.session_key, data, settings.SESSION_COOKIE_AGE) return data def exists(self, session_key): return super(SessionStore, self).exists(session_key) def save(self, must_create=False): super(SessionStore, self).save(must_create) cache.set(self.session_key, self._session, settings.SESSION_COOKIE_AGE) def delete(self, session_key=None): super(SessionStore, self).delete(session_key) cache.delete(session_key or self.session_key) def flush(self): """ Removes the current session data from the database and regenerates the key. """ self.clear() self.delete(self.session_key) self.create()
1,256
Python
.py
34
30.205882
79
0.670782
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,883
file.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sessions/backends/file.py
import errno import os import tempfile from django.conf import settings from django.contrib.sessions.backends.base import SessionBase, CreateError from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured class SessionStore(SessionBase): """ Implements a file based session store. """ def __init__(self, session_key=None): self.storage_path = getattr(settings, "SESSION_FILE_PATH", None) if not self.storage_path: self.storage_path = tempfile.gettempdir() # Make sure the storage path is valid. if not os.path.isdir(self.storage_path): raise ImproperlyConfigured( "The session storage path %r doesn't exist. Please set your" " SESSION_FILE_PATH setting to an existing directory in which" " Django can store session data." % self.storage_path) self.file_prefix = settings.SESSION_COOKIE_NAME super(SessionStore, self).__init__(session_key) VALID_KEY_CHARS = set("abcdef0123456789") def _key_to_file(self, session_key=None): """ Get the file associated with this session key. """ if session_key is None: session_key = self.session_key # Make sure we're not vulnerable to directory traversal. Session keys # should always be md5s, so they should never contain directory # components. if not set(session_key).issubset(self.VALID_KEY_CHARS): raise SuspiciousOperation( "Invalid characters in session key") return os.path.join(self.storage_path, self.file_prefix + session_key) def load(self): session_data = {} try: session_file = open(self._key_to_file(), "rb") try: file_data = session_file.read() # Don't fail if there is no data in the session file. # We may have opened the empty placeholder file. if file_data: try: session_data = self.decode(file_data) except (EOFError, SuspiciousOperation): self.create() finally: session_file.close() except IOError: pass return session_data def create(self): while True: self._session_key = self._get_new_session_key() try: self.save(must_create=True) except CreateError: continue self.modified = True self._session_cache = {} return def save(self, must_create=False): # Get the session data now, before we start messing # with the file it is stored within. session_data = self._get_session(no_load=must_create) session_file_name = self._key_to_file() try: # Make sure the file exists. If it does not already exist, an # empty placeholder file is created. flags = os.O_WRONLY | os.O_CREAT | getattr(os, 'O_BINARY', 0) if must_create: flags |= os.O_EXCL fd = os.open(session_file_name, flags) os.close(fd) except OSError, e: if must_create and e.errno == errno.EEXIST: raise CreateError raise # Write the session file without interfering with other threads # or processes. By writing to an atomically generated temporary # file and then using the atomic os.rename() to make the complete # file visible, we avoid having to lock the session file, while # still maintaining its integrity. # # Note: Locking the session file was explored, but rejected in part # because in order to be atomic and cross-platform, it required a # long-lived lock file for each session, doubling the number of # files in the session storage directory at any given time. This # rename solution is cleaner and avoids any additional overhead # when reading the session data, which is the more common case # unless SESSION_SAVE_EVERY_REQUEST = True. # # See ticket #8616. dir, prefix = os.path.split(session_file_name) try: output_file_fd, output_file_name = tempfile.mkstemp(dir=dir, prefix=prefix + '_out_') renamed = False try: try: os.write(output_file_fd, self.encode(session_data)) finally: os.close(output_file_fd) os.rename(output_file_name, session_file_name) renamed = True finally: if not renamed: os.unlink(output_file_name) except (OSError, IOError, EOFError): pass def exists(self, session_key): if os.path.exists(self._key_to_file(session_key)): return True return False def delete(self, session_key=None): if session_key is None: if self._session_key is None: return session_key = self._session_key try: os.unlink(self._key_to_file(session_key)) except OSError: pass def clean(self): pass
5,358
Python
.py
128
30.539063
78
0.58994
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,884
cache.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sessions/backends/cache.py
from django.contrib.sessions.backends.base import SessionBase, CreateError from django.core.cache import cache class SessionStore(SessionBase): """ A cache-based session store. """ def __init__(self, session_key=None): self._cache = cache super(SessionStore, self).__init__(session_key) def load(self): session_data = self._cache.get(self.session_key) if session_data is not None: return session_data self.create() return {} def create(self): # Because a cache can fail silently (e.g. memcache), we don't know if # we are failing to create a new session because of a key collision or # because the cache is missing. So we try for a (large) number of times # and then raise an exception. That's the risk you shoulder if using # cache backing. for i in xrange(10000): self.session_key = self._get_new_session_key() try: self.save(must_create=True) except CreateError: continue self.modified = True return raise RuntimeError("Unable to create a new session key.") def save(self, must_create=False): if must_create: func = self._cache.add else: func = self._cache.set result = func(self.session_key, self._get_session(no_load=must_create), self.get_expiry_age()) if must_create and not result: raise CreateError def exists(self, session_key): if self._cache.has_key(session_key): return True return False def delete(self, session_key=None): if session_key is None: if self._session_key is None: return session_key = self._session_key self._cache.delete(session_key)
1,881
Python
.py
49
28.836735
79
0.604932
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,885
base.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sessions/backends/base.py
import base64 import os import random import sys import time from datetime import datetime, timedelta try: import cPickle as pickle except ImportError: import pickle from django.conf import settings from django.core.exceptions import SuspiciousOperation from django.utils.hashcompat import md5_constructor # Use the system (hardware-based) random number generator if it exists. if hasattr(random, 'SystemRandom'): randrange = random.SystemRandom().randrange else: randrange = random.randrange MAX_SESSION_KEY = 18446744073709551616L # 2 << 63 class CreateError(Exception): """ Used internally as a consistent exception type to catch from save (see the docstring for SessionBase.save() for details). """ pass class SessionBase(object): """ Base class for all Session classes. """ TEST_COOKIE_NAME = 'testcookie' TEST_COOKIE_VALUE = 'worked' def __init__(self, session_key=None): self._session_key = session_key self.accessed = False self.modified = False def __contains__(self, key): return key in self._session def __getitem__(self, key): return self._session[key] def __setitem__(self, key, value): self._session[key] = value self.modified = True def __delitem__(self, key): del self._session[key] self.modified = True def keys(self): return self._session.keys() def items(self): return self._session.items() def get(self, key, default=None): return self._session.get(key, default) def pop(self, key, *args): self.modified = self.modified or key in self._session return self._session.pop(key, *args) def setdefault(self, key, value): if key in self._session: return self._session[key] else: self.modified = True self._session[key] = value return value def set_test_cookie(self): self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE def test_cookie_worked(self): return self.get(self.TEST_COOKIE_NAME) == self.TEST_COOKIE_VALUE def delete_test_cookie(self): del self[self.TEST_COOKIE_NAME] def encode(self, session_dict): "Returns the given session dictionary pickled and encoded as a string." pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest() return base64.encodestring(pickled + pickled_md5) def decode(self, session_data): encoded_data = base64.decodestring(session_data) pickled, tamper_check = encoded_data[:-32], encoded_data[-32:] if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check: raise SuspiciousOperation("User tampered with session cookie.") try: return pickle.loads(pickled) # Unpickling can cause a variety of exceptions. If something happens, # just return an empty dictionary (an empty session). except: return {} def update(self, dict_): self._session.update(dict_) self.modified = True def has_key(self, key): return self._session.has_key(key) def values(self): return self._session.values() def iterkeys(self): return self._session.iterkeys() def itervalues(self): return self._session.itervalues() def iteritems(self): return self._session.iteritems() def clear(self): # To avoid unnecessary persistent storage accesses, we set up the # internals directly (loading data wastes time, since we are going to # set it to an empty dict anyway). self._session_cache = {} self.accessed = True self.modified = True def _get_new_session_key(self): "Returns session key that isn't being used." # The random module is seeded when this Apache child is created. # Use settings.SECRET_KEY as added salt. try: pid = os.getpid() except AttributeError: # No getpid() in Jython, for example pid = 1 while 1: session_key = md5_constructor("%s%s%s%s" % (randrange(0, MAX_SESSION_KEY), pid, time.time(), settings.SECRET_KEY)).hexdigest() if not self.exists(session_key): break return session_key def _get_session_key(self): if self._session_key: return self._session_key else: self._session_key = self._get_new_session_key() return self._session_key def _set_session_key(self, session_key): self._session_key = session_key session_key = property(_get_session_key, _set_session_key) def _get_session(self, no_load=False): """ Lazily loads session from storage (unless "no_load" is True, when only an empty dict is stored) and stores it in the current instance. """ self.accessed = True try: return self._session_cache except AttributeError: if self._session_key is None or no_load: self._session_cache = {} else: self._session_cache = self.load() return self._session_cache _session = property(_get_session) def get_expiry_age(self): """Get the number of seconds until the session expires.""" expiry = self.get('_session_expiry') if not expiry: # Checks both None and 0 cases return settings.SESSION_COOKIE_AGE if not isinstance(expiry, datetime): return expiry delta = expiry - datetime.now() return delta.days * 86400 + delta.seconds def get_expiry_date(self): """Get session the expiry date (as a datetime object).""" expiry = self.get('_session_expiry') if isinstance(expiry, datetime): return expiry if not expiry: # Checks both None and 0 cases expiry = settings.SESSION_COOKIE_AGE return datetime.now() + timedelta(seconds=expiry) def set_expiry(self, value): """ Sets a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the session will expire on browser close. If ``value`` is a ``datetime`` or ``timedelta`` object, the session will expire at that specific future time. If ``value`` is ``None``, the session uses the global session expiry policy. """ if value is None: # Remove any custom expiration for this session. try: del self['_session_expiry'] except KeyError: pass return if isinstance(value, timedelta): value = datetime.now() + value self['_session_expiry'] = value def get_expire_at_browser_close(self): """ Returns ``True`` if the session is set to expire when the browser closes, and ``False`` if there's an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one. """ if self.get('_session_expiry') is None: return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE return self.get('_session_expiry') == 0 def flush(self): """ Removes the current session data from the database and regenerates the key. """ self.clear() self.delete() self.create() def cycle_key(self): """ Creates a new session key, whilst retaining the current session data. """ data = self._session_cache key = self.session_key self.create() self._session_cache = data self.delete(key) # Methods that child classes must implement. def exists(self, session_key): """ Returns True if the given session_key already exists. """ raise NotImplementedError def create(self): """ Creates a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns. """ raise NotImplementedError def save(self, must_create=False): """ Saves the session data. If 'must_create' is True, a new session object is created (otherwise a CreateError exception is raised). Otherwise, save() can update an existing object with the same key. """ raise NotImplementedError def delete(self, session_key=None): """ Deletes the session data under this key. If the key is None, the current session key value is used. """ raise NotImplementedError def load(self): """ Loads the session data and returns a dictionary. """ raise NotImplementedError
9,240
Python
.py
240
30.025
86
0.623925
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,886
middleware.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/csrf/middleware.py
from django.middleware.csrf import CsrfMiddleware, CsrfViewMiddleware, CsrfResponseMiddleware from django.views.decorators.csrf import csrf_exempt, csrf_view_exempt, csrf_response_exempt import warnings warnings.warn("This import for CSRF functionality is deprecated. Please use django.middleware.csrf for the middleware and django.views.decorators.csrf for decorators.", PendingDeprecationWarning )
430
Python
.py
6
65.833333
169
0.803783
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,887
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sitemaps/__init__.py
from django.contrib.sites.models import Site, get_current_site from django.core import urlresolvers, paginator from django.core.exceptions import ImproperlyConfigured import urllib PING_URL = "http://www.google.com/webmasters/tools/ping" class SitemapNotFound(Exception): pass def ping_google(sitemap_url=None, ping_url=PING_URL): """ Alerts Google that the sitemap for the current site has been updated. If sitemap_url is provided, it should be an absolute path to the sitemap for this site -- e.g., '/sitemap.xml'. If sitemap_url is not provided, this function will attempt to deduce it by using urlresolvers.reverse(). """ if sitemap_url is None: try: # First, try to get the "index" sitemap URL. sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.index') except urlresolvers.NoReverseMatch: try: # Next, try for the "global" sitemap URL. sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap') except urlresolvers.NoReverseMatch: pass if sitemap_url is None: raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.") from django.contrib.sites.models import Site current_site = Site.objects.get_current() url = "http://%s%s" % (current_site.domain, sitemap_url) params = urllib.urlencode({'sitemap':url}) urllib.urlopen("%s?%s" % (ping_url, params)) class Sitemap(object): # This limit is defined by Google. See the index documentation at # http://sitemaps.org/protocol.php#index. limit = 50000 def __get(self, name, obj, default=None): try: attr = getattr(self, name) except AttributeError: return default if callable(attr): return attr(obj) return attr def items(self): return [] def location(self, obj): return obj.get_absolute_url() def _get_paginator(self): if not hasattr(self, "_paginator"): self._paginator = paginator.Paginator(self.items(), self.limit) return self._paginator paginator = property(_get_paginator) def get_urls(self, page=1, site=None): if site is None: if Site._meta.installed: try: site = Site.objects.get_current() except Site.DoesNotExist: pass if site is None: raise ImproperlyConfigured("In order to use Sitemaps you must either use the sites framework or pass in a Site or RequestSite object in your view code.") urls = [] for item in self.paginator.page(page).object_list: loc = "http://%s%s" % (site.domain, self.__get('location', item)) priority = self.__get('priority', item, None) url_info = { 'location': loc, 'lastmod': self.__get('lastmod', item, None), 'changefreq': self.__get('changefreq', item, None), 'priority': str(priority is not None and priority or '') } urls.append(url_info) return urls class FlatPageSitemap(Sitemap): def items(self): current_site = Site.objects.get_current() return current_site.flatpage_set.filter(registration_required=False) class GenericSitemap(Sitemap): priority = None changefreq = None def __init__(self, info_dict, priority=None, changefreq=None): self.queryset = info_dict['queryset'] self.date_field = info_dict.get('date_field', None) self.priority = priority self.changefreq = changefreq def items(self): # Make sure to return a clone; we don't want premature evaluation. return self.queryset.filter() def lastmod(self, item): if self.date_field is not None: return getattr(item, self.date_field) return None
4,010
Python
.py
92
34.706522
169
0.635734
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,888
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sitemaps/views.py
from django.http import HttpResponse, Http404 from django.template import loader from django.contrib.sites.models import get_current_site from django.core import urlresolvers from django.utils.encoding import smart_str from django.core.paginator import EmptyPage, PageNotAnInteger def index(request, sitemaps): current_site = get_current_site(request) sites = [] protocol = request.is_secure() and 'https' or 'http' for section, site in sitemaps.items(): site.request = request if callable(site): pages = site().paginator.num_pages else: pages = site.paginator.num_pages sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap', kwargs={'section': section}) sites.append('%s://%s%s' % (protocol, current_site.domain, sitemap_url)) if pages > 1: for page in range(2, pages+1): sites.append('%s://%s%s?p=%s' % (protocol, current_site.domain, sitemap_url, page)) xml = loader.render_to_string('sitemap_index.xml', {'sitemaps': sites}) return HttpResponse(xml, mimetype='application/xml') def sitemap(request, sitemaps, section=None): maps, urls = [], [] if section is not None: if section not in sitemaps: raise Http404("No sitemap available for section: %r" % section) maps.append(sitemaps[section]) else: maps = sitemaps.values() page = request.GET.get("p", 1) current_site = get_current_site(request) for site in maps: try: if callable(site): urls.extend(site().get_urls(page=page, site=current_site)) else: urls.extend(site.get_urls(page=page, site=current_site)) except EmptyPage: raise Http404("Page %s empty" % page) except PageNotAnInteger: raise Http404("No page '%s'" % page) xml = smart_str(loader.render_to_string('sitemap.xml', {'urlset': urls})) return HttpResponse(xml, mimetype='application/xml')
2,026
Python
.py
45
37.4
112
0.654371
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,889
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sitemaps/tests/urls.py
from datetime import datetime from django.conf.urls.defaults import * from django.contrib.sitemaps import Sitemap, GenericSitemap, FlatPageSitemap from django.contrib.auth.models import User class SimpleSitemap(Sitemap): changefreq = "never" priority = 0.5 location = '/location/' lastmod = datetime.now() def items(self): return [object()] simple_sitemaps = { 'simple': SimpleSitemap, } generic_sitemaps = { 'generic': GenericSitemap({ 'queryset': User.objects.all() }), } flatpage_sitemaps = { 'flatpages': FlatPageSitemap, } urlpatterns = patterns('django.contrib.sitemaps.views', (r'^simple/sitemap\.xml$', 'sitemap', {'sitemaps': simple_sitemaps}), (r'^generic/sitemap\.xml$', 'sitemap', {'sitemaps': generic_sitemaps}), (r'^flatpages/sitemap\.xml$', 'sitemap', {'sitemaps': flatpage_sitemaps}), )
873
Python
.py
27
28.740741
78
0.703571
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,890
basic.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sitemaps/tests/basic.py
from datetime import date from django.conf import settings from django.contrib.auth.models import User from django.contrib.sitemaps import Sitemap from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from django.utils.formats import localize from django.utils.translation import activate, deactivate class SitemapTests(TestCase): urls = 'django.contrib.sitemaps.tests.urls' def setUp(self): if Site._meta.installed: self.base_url = 'http://example.com' else: self.base_url = 'http://testserver' self.old_USE_L10N = settings.USE_L10N self.old_Site_meta_installed = Site._meta.installed # Create a user that will double as sitemap content User.objects.create_user('testuser', '[email protected]', 's3krit') def tearDown(self): settings.USE_L10N = self.old_USE_L10N Site._meta.installed = self.old_Site_meta_installed def test_simple_sitemap(self): "A simple sitemap can be rendered" # Retrieve the sitemap. response = self.client.get('/simple/sitemap.xml') # Check for all the important bits: self.assertEquals(response.content, """<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url> </urlset> """ % (self.base_url, date.today().strftime('%Y-%m-%d'))) if settings.USE_I18N: def test_localized_priority(self): "The priority value should not be localized (Refs #14164)" # Localization should be active settings.USE_L10N = True activate('fr') self.assertEqual(u'0,3', localize(0.3)) # Retrieve the sitemap. Check that priorities # haven't been rendered in localized format response = self.client.get('/simple/sitemap.xml') self.assertContains(response, '<priority>0.5</priority>') self.assertContains(response, '<lastmod>%s</lastmod>' % date.today().strftime('%Y-%m-%d')) deactivate() def test_generic_sitemap(self): "A minimal generic sitemap can be rendered" # Retrieve the sitemap. response = self.client.get('/generic/sitemap.xml') expected = '' for username in User.objects.values_list("username", flat=True): expected += "<url><loc>%s/users/%s/</loc></url>" % (self.base_url, username) # Check for all the important bits: self.assertEquals(response.content, """<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> %s </urlset> """ % expected) if "django.contrib.flatpages" in settings.INSTALLED_APPS: def test_flatpage_sitemap(self): "Basic FlatPage sitemap test" # Import FlatPage inside the test so that when django.contrib.flatpages # is not installed we don't get problems trying to delete Site # objects (FlatPage has an M2M to Site, Site.delete() tries to # delete related objects, but the M2M table doesn't exist. from django.contrib.flatpages.models import FlatPage public = FlatPage.objects.create( url=u'/public/', title=u'Public Page', enable_comments=True, registration_required=False, ) public.sites.add(settings.SITE_ID) private = FlatPage.objects.create( url=u'/private/', title=u'Private Page', enable_comments=True, registration_required=True ) private.sites.add(settings.SITE_ID) response = self.client.get('/flatpages/sitemap.xml') # Public flatpage should be in the sitemap self.assertContains(response, '<loc>%s%s</loc>' % (self.base_url, public.url)) # Private flatpage should not be in the sitemap self.assertNotContains(response, '<loc>%s%s</loc>' % (self.base_url, private.url)) def test_requestsite_sitemap(self): # Make sure hitting the flatpages sitemap without the sites framework # installed doesn't raise an exception Site._meta.installed = False # Retrieve the sitemap. response = self.client.get('/simple/sitemap.xml') # Check for all the important bits: self.assertEquals(response.content, """<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url><loc>http://testserver/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url> </urlset> """ % date.today().strftime('%Y-%m-%d')) if "django.contrib.sites" in settings.INSTALLED_APPS: def test_sitemap_get_urls_no_site_1(self): """ Check we get ImproperlyConfigured if we don't pass a site object to Sitemap.get_urls and no Site objects exist """ Site.objects.all().delete() self.assertRaises(ImproperlyConfigured, Sitemap().get_urls) def test_sitemap_get_urls_no_site_2(self): """ Check we get ImproperlyConfigured when we don't pass a site object to Sitemap.get_urls if Site objects exists, but the sites framework is not actually installed. """ Site._meta.installed = False self.assertRaises(ImproperlyConfigured, Sitemap().get_urls)
5,618
Python
.py
114
40.184211
124
0.647112
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,891
ping_google.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/contrib/sitemaps/management/commands/ping_google.py
from django.core.management.base import BaseCommand from django.contrib.sitemaps import ping_google class Command(BaseCommand): help = "Ping Google with an updated sitemap, pass optional url of sitemap" def execute(self, *args, **options): if len(args) == 1: sitemap_url = args[0] else: sitemap_url = None ping_google(sitemap_url=sitemap_url)
403
Python
.py
10
33.3
78
0.681234
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,892
signals.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/core/signals.py
from django.dispatch import Signal request_started = Signal() request_finished = Signal() got_request_exception = Signal(providing_args=["request"])
150
Python
.py
4
36.25
58
0.8
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,893
urlresolvers.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/core/urlresolvers.py
""" This module converts requested URLs to callback view functions. RegexURLResolver is the main class here. Its resolve() method takes a URL (as a string) and returns a tuple in this format: (view_function, function_args, function_kwargs) """ import re from django.http import Http404 from django.conf import settings from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.utils.datastructures import MultiValueDict from django.utils.encoding import iri_to_uri, force_unicode, smart_str from django.utils.functional import memoize from django.utils.importlib import import_module from django.utils.regex_helper import normalize from django.utils.thread_support import currentThread _resolver_cache = {} # Maps URLconf modules to RegexURLResolver instances. _callable_cache = {} # Maps view and url pattern names to their view functions. # SCRIPT_NAME prefixes for each thread are stored here. If there's no entry for # the current thread (which is the only one we ever access), it is assumed to # be empty. _prefixes = {} # Overridden URLconfs for each thread are stored here. _urlconfs = {} class Resolver404(Http404): pass class NoReverseMatch(Exception): # Don't make this raise an error when used in a template. silent_variable_failure = True def get_callable(lookup_view, can_fail=False): """ Convert a string version of a function name to the callable object. If the lookup_view is not an import path, it is assumed to be a URL pattern label and the original string is returned. If can_fail is True, lookup_view might be a URL pattern label, so errors during the import fail and the string is returned. """ if not callable(lookup_view): try: # Bail early for non-ASCII strings (they can't be functions). lookup_view = lookup_view.encode('ascii') mod_name, func_name = get_mod_func(lookup_view) if func_name != '': lookup_view = getattr(import_module(mod_name), func_name) if not callable(lookup_view): raise AttributeError("'%s.%s' is not a callable." % (mod_name, func_name)) except (ImportError, AttributeError): if not can_fail: raise except UnicodeEncodeError: pass return lookup_view get_callable = memoize(get_callable, _callable_cache, 1) def get_resolver(urlconf): if urlconf is None: from django.conf import settings urlconf = settings.ROOT_URLCONF return RegexURLResolver(r'^/', urlconf) get_resolver = memoize(get_resolver, _resolver_cache, 1) def get_mod_func(callback): # Converts 'django.views.news.stories.story_detail' to # ['django.views.news.stories', 'story_detail'] try: dot = callback.rindex('.') except ValueError: return callback, '' return callback[:dot], callback[dot+1:] class RegexURLPattern(object): def __init__(self, regex, callback, default_args=None, name=None): # regex is a string representing a regular expression. # callback is either a string like 'foo.views.news.stories.story_detail' # which represents the path to a module and a view function name, or a # callable object (view). self.regex = re.compile(regex, re.UNICODE) if callable(callback): self._callback = callback else: self._callback = None self._callback_str = callback self.default_args = default_args or {} self.name = name def __repr__(self): return '<%s %s %s>' % (self.__class__.__name__, self.name, self.regex.pattern) def add_prefix(self, prefix): """ Adds the prefix string to a string-based callback. """ if not prefix or not hasattr(self, '_callback_str'): return self._callback_str = prefix + '.' + self._callback_str def resolve(self, path): match = self.regex.search(path) if match: # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as # positional arguments. kwargs = match.groupdict() if kwargs: args = () else: args = match.groups() # In both cases, pass any extra_kwargs as **kwargs. kwargs.update(self.default_args) return self.callback, args, kwargs def _get_callback(self): if self._callback is not None: return self._callback try: self._callback = get_callable(self._callback_str) except ImportError, e: mod_name, _ = get_mod_func(self._callback_str) raise ViewDoesNotExist("Could not import %s. Error was: %s" % (mod_name, str(e))) except AttributeError, e: mod_name, func_name = get_mod_func(self._callback_str) raise ViewDoesNotExist("Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e))) return self._callback callback = property(_get_callback) class RegexURLResolver(object): def __init__(self, regex, urlconf_name, default_kwargs=None, app_name=None, namespace=None): # regex is a string representing a regular expression. # urlconf_name is a string representing the module containing URLconfs. self.regex = re.compile(regex, re.UNICODE) self.urlconf_name = urlconf_name if not isinstance(urlconf_name, basestring): self._urlconf_module = self.urlconf_name self.callback = None self.default_kwargs = default_kwargs or {} self.namespace = namespace self.app_name = app_name self._reverse_dict = None self._namespace_dict = None self._app_dict = None def __repr__(self): return '<%s %s (%s:%s) %s>' % (self.__class__.__name__, self.urlconf_name, self.app_name, self.namespace, self.regex.pattern) def _populate(self): lookups = MultiValueDict() namespaces = {} apps = {} for pattern in reversed(self.url_patterns): p_pattern = pattern.regex.pattern if p_pattern.startswith('^'): p_pattern = p_pattern[1:] if isinstance(pattern, RegexURLResolver): if pattern.namespace: namespaces[pattern.namespace] = (p_pattern, pattern) if pattern.app_name: apps.setdefault(pattern.app_name, []).append(pattern.namespace) else: parent = normalize(pattern.regex.pattern) for name in pattern.reverse_dict: for matches, pat in pattern.reverse_dict.getlist(name): new_matches = [] for piece, p_args in parent: new_matches.extend([(piece + suffix, p_args + args) for (suffix, args) in matches]) lookups.appendlist(name, (new_matches, p_pattern + pat)) for namespace, (prefix, sub_pattern) in pattern.namespace_dict.items(): namespaces[namespace] = (p_pattern + prefix, sub_pattern) for app_name, namespace_list in pattern.app_dict.items(): apps.setdefault(app_name, []).extend(namespace_list) else: bits = normalize(p_pattern) lookups.appendlist(pattern.callback, (bits, p_pattern)) if pattern.name is not None: lookups.appendlist(pattern.name, (bits, p_pattern)) self._reverse_dict = lookups self._namespace_dict = namespaces self._app_dict = apps def _get_reverse_dict(self): if self._reverse_dict is None: self._populate() return self._reverse_dict reverse_dict = property(_get_reverse_dict) def _get_namespace_dict(self): if self._namespace_dict is None: self._populate() return self._namespace_dict namespace_dict = property(_get_namespace_dict) def _get_app_dict(self): if self._app_dict is None: self._populate() return self._app_dict app_dict = property(_get_app_dict) def resolve(self, path): tried = [] match = self.regex.search(path) if match: new_path = path[match.end():] for pattern in self.url_patterns: try: sub_match = pattern.resolve(new_path) except Resolver404, e: sub_tried = e.args[0].get('tried') if sub_tried is not None: tried.extend([(pattern.regex.pattern + ' ' + t) for t in sub_tried]) else: tried.append(pattern.regex.pattern) else: if sub_match: sub_match_dict = dict([(smart_str(k), v) for k, v in match.groupdict().items()]) sub_match_dict.update(self.default_kwargs) for k, v in sub_match[2].iteritems(): sub_match_dict[smart_str(k)] = v return sub_match[0], sub_match[1], sub_match_dict tried.append(pattern.regex.pattern) raise Resolver404({'tried': tried, 'path': new_path}) raise Resolver404({'path' : path}) def _get_urlconf_module(self): try: return self._urlconf_module except AttributeError: self._urlconf_module = import_module(self.urlconf_name) return self._urlconf_module urlconf_module = property(_get_urlconf_module) def _get_url_patterns(self): patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) try: iter(patterns) except TypeError: raise ImproperlyConfigured("The included urlconf %s doesn't have any patterns in it" % self.urlconf_name) return patterns url_patterns = property(_get_url_patterns) def _resolve_special(self, view_type): callback = getattr(self.urlconf_module, 'handler%s' % view_type) try: return get_callable(callback), {} except (ImportError, AttributeError), e: raise ViewDoesNotExist("Tried %s. Error was: %s" % (callback, str(e))) def resolve404(self): return self._resolve_special('404') def resolve500(self): return self._resolve_special('500') def reverse(self, lookup_view, *args, **kwargs): if args and kwargs: raise ValueError("Don't mix *args and **kwargs in call to reverse()!") try: lookup_view = get_callable(lookup_view, True) except (ImportError, AttributeError), e: raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e)) possibilities = self.reverse_dict.getlist(lookup_view) for possibility, pattern in possibilities: for result, params in possibility: if args: if len(args) != len(params): continue unicode_args = [force_unicode(val) for val in args] candidate = result % dict(zip(params, unicode_args)) else: if set(kwargs.keys()) != set(params): continue unicode_kwargs = dict([(k, force_unicode(v)) for (k, v) in kwargs.items()]) candidate = result % unicode_kwargs if re.search(u'^%s' % pattern, candidate, re.UNICODE): return candidate # lookup_view can be URL label, or dotted path, or callable, Any of # these can be passed in at the top, but callables are not friendly in # error messages. m = getattr(lookup_view, '__module__', None) n = getattr(lookup_view, '__name__', None) if m is not None and n is not None: lookup_view_s = "%s.%s" % (m, n) else: lookup_view_s = lookup_view raise NoReverseMatch("Reverse for '%s' with arguments '%s' and keyword " "arguments '%s' not found." % (lookup_view_s, args, kwargs)) def resolve(path, urlconf=None): if urlconf is None: urlconf = get_urlconf() return get_resolver(urlconf).resolve(path) def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): if urlconf is None: urlconf = get_urlconf() resolver = get_resolver(urlconf) args = args or [] kwargs = kwargs or {} if prefix is None: prefix = get_script_prefix() if not isinstance(viewname, basestring): view = viewname else: parts = viewname.split(':') parts.reverse() view = parts[0] path = parts[1:] resolved_path = [] while path: ns = path.pop() # Lookup the name to see if it could be an app identifier try: app_list = resolver.app_dict[ns] # Yes! Path part matches an app in the current Resolver if current_app and current_app in app_list: # If we are reversing for a particular app, use that namespace ns = current_app elif ns not in app_list: # The name isn't shared by one of the instances (i.e., the default) # so just pick the first instance as the default. ns = app_list[0] except KeyError: pass try: extra, resolver = resolver.namespace_dict[ns] resolved_path.append(ns) prefix = prefix + extra except KeyError, key: if resolved_path: raise NoReverseMatch("%s is not a registered namespace inside '%s'" % (key, ':'.join(resolved_path))) else: raise NoReverseMatch("%s is not a registered namespace" % key) return iri_to_uri(u'%s%s' % (prefix, resolver.reverse(view, *args, **kwargs))) def clear_url_caches(): global _resolver_cache global _callable_cache _resolver_cache.clear() _callable_cache.clear() def set_script_prefix(prefix): """ Sets the script prefix for the current thread. """ if not prefix.endswith('/'): prefix += '/' _prefixes[currentThread()] = prefix def get_script_prefix(): """ Returns the currently active script prefix. Useful for client code that wishes to construct their own URLs manually (although accessing the request instance is normally going to be a lot cleaner). """ return _prefixes.get(currentThread(), u'/') def set_urlconf(urlconf_name): """ Sets the URLconf for the current thread (overriding the default one in settings). Set to None to revert back to the default. """ thread = currentThread() if urlconf_name: _urlconfs[thread] = urlconf_name else: # faster than wrapping in a try/except if thread in _urlconfs: del _urlconfs[thread] def get_urlconf(default=None): """ Returns the root URLconf to use for the current thread if it has been changed from the default one. """ thread = currentThread() if thread in _urlconfs: return _urlconfs[thread] return default
15,598
Python
.py
350
34.177143
133
0.602223
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,894
paginator.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/core/paginator.py
from math import ceil class InvalidPage(Exception): pass class PageNotAnInteger(InvalidPage): pass class EmptyPage(InvalidPage): pass class Paginator(object): def __init__(self, object_list, per_page, orphans=0, allow_empty_first_page=True): self.object_list = object_list self.per_page = per_page self.orphans = orphans self.allow_empty_first_page = allow_empty_first_page self._num_pages = self._count = None def validate_number(self, number): "Validates the given 1-based page number." try: number = int(number) except ValueError: raise PageNotAnInteger('That page number is not an integer') if number < 1: raise EmptyPage('That page number is less than 1') if number > self.num_pages: if number == 1 and self.allow_empty_first_page: pass else: raise EmptyPage('That page contains no results') return number def page(self, number): "Returns a Page object for the given 1-based page number." number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count return Page(self.object_list[bottom:top], number, self) def _get_count(self): "Returns the total number of objects, across all pages." if self._count is None: try: self._count = self.object_list.count() except (AttributeError, TypeError): # AttributeError if object_list has no count() method. # TypeError if object_list.count() requires arguments # (i.e. is of type list). self._count = len(self.object_list) return self._count count = property(_get_count) def _get_num_pages(self): "Returns the total number of pages." if self._num_pages is None: if self.count == 0 and not self.allow_empty_first_page: self._num_pages = 0 else: hits = max(1, self.count - self.orphans) self._num_pages = int(ceil(hits / float(self.per_page))) return self._num_pages num_pages = property(_get_num_pages) def _get_page_range(self): """ Returns a 1-based range of pages for iterating through within a template for loop. """ return range(1, self.num_pages + 1) page_range = property(_get_page_range) QuerySetPaginator = Paginator # For backwards-compatibility. class Page(object): def __init__(self, object_list, number, paginator): self.object_list = object_list self.number = number self.paginator = paginator def __repr__(self): return '<Page %s of %s>' % (self.number, self.paginator.num_pages) def has_next(self): return self.number < self.paginator.num_pages def has_previous(self): return self.number > 1 def has_other_pages(self): return self.has_previous() or self.has_next() def next_page_number(self): return self.number + 1 def previous_page_number(self): return self.number - 1 def start_index(self): """ Returns the 1-based index of the first object on this page, relative to total objects in the paginator. """ # Special case, return zero if no items. if self.paginator.count == 0: return 0 return (self.paginator.per_page * (self.number - 1)) + 1 def end_index(self): """ Returns the 1-based index of the last object on this page, relative to total objects found (hits). """ # Special case for the last page because there can be orphans. if self.number == self.paginator.num_pages: return self.paginator.count return self.number * self.paginator.per_page
4,021
Python
.py
101
30.742574
86
0.610613
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,895
xheaders.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/core/xheaders.py
""" Pages in Django can are served up with custom HTTP headers containing useful information about those pages -- namely, the content type and object ID. This module contains utility functions for retrieving and doing interesting things with these special "X-Headers" (so called because the HTTP spec demands that custom headers are prefixed with "X-"). Next time you're at slashdot.org, watch out for X-Fry and X-Bender. :) """ def populate_xheaders(request, response, model, object_id): """ Adds the "X-Object-Type" and "X-Object-Id" headers to the given HttpResponse according to the given model and object_id -- but only if the given HttpRequest object has an IP address within the INTERNAL_IPS setting or if the request is from a logged in staff member. """ from django.conf import settings if (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or (hasattr(request, 'user') and request.user.is_active and request.user.is_staff)): response['X-Object-Type'] = "%s.%s" % (model._meta.app_label, model._meta.object_name.lower()) response['X-Object-Id'] = str(object_id)
1,157
Python
.py
21
50.333333
102
0.721977
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,896
context_processors.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/core/context_processors.py
""" A set of request processors that return dictionaries to be merged into a template context. Each function takes the request object as its only parameter and returns a dictionary to add to the context. These are referenced from the setting TEMPLATE_CONTEXT_PROCESSORS and used by RequestContext. """ from django.conf import settings from django.middleware.csrf import get_token from django.utils.functional import lazy def auth(request): """ DEPRECATED. This context processor is the old location, and has been moved to `django.contrib.auth.context_processors`. This function still exists for backwards-compatibility; it will be removed in Django 1.4. """ import warnings warnings.warn( "The context processor at `django.core.context_processors.auth` is " \ "deprecated; use the path `django.contrib.auth.context_processors.auth` " \ "instead.", PendingDeprecationWarning ) from django.contrib.auth.context_processors import auth as auth_context_processor return auth_context_processor(request) def csrf(request): """ Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware """ def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return 'NOTPROVIDED' else: return token _get_val = lazy(_get_val, str) return {'csrf_token': _get_val() } def debug(request): "Returns context variables helpful for debugging." context_extras = {} if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS: context_extras['debug'] = True from django.db import connection context_extras['sql_queries'] = connection.queries return context_extras def i18n(request): from django.utils import translation context_extras = {} context_extras['LANGUAGES'] = settings.LANGUAGES context_extras['LANGUAGE_CODE'] = translation.get_language() context_extras['LANGUAGE_BIDI'] = translation.get_language_bidi() return context_extras def media(request): """ Adds media-related context variables to the context. """ return {'MEDIA_URL': settings.MEDIA_URL} def request(request): return {'request': request} # PermWrapper and PermLookupDict proxy the permissions system into objects that # the template system can understand. class PermLookupDict(object): def __init__(self, user, module_name): self.user, self.module_name = user, module_name def __repr__(self): return str(self.user.get_all_permissions()) def __getitem__(self, perm_name): return self.user.has_perm("%s.%s" % (self.module_name, perm_name)) def __nonzero__(self): return self.user.has_module_perms(self.module_name) class PermWrapper(object): def __init__(self, user): self.user = user def __getitem__(self, module_name): return PermLookupDict(self.user, module_name) def __iter__(self): # I am large, I contain multitudes. raise TypeError("PermWrapper is not iterable.")
3,353
Python
.py
83
34.759036
85
0.70237
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,897
template_loader.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/core/template_loader.py
# This module is DEPRECATED! # # You should no longer be using django.template_loader. # # Use django.template.loader instead. from django.template.loader import *
165
Python
.py
6
26.333333
55
0.797468
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,898
validators.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/core/validators.py
import re import urlparse from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode # These values, if given to validate(), will trigger the self.required check. EMPTY_VALUES = (None, '', [], (), {}) try: from django.conf import settings URL_VALIDATOR_USER_AGENT = settings.URL_VALIDATOR_USER_AGENT except ImportError: # It's OK if Django settings aren't configured. URL_VALIDATOR_USER_AGENT = 'Django (http://www.djangoproject.com/)' class RegexValidator(object): regex = '' message = _(u'Enter a valid value.') code = 'invalid' def __init__(self, regex=None, message=None, code=None): if regex is not None: self.regex = regex if message is not None: self.message = message if code is not None: self.code = code if isinstance(self.regex, basestring): self.regex = re.compile(regex) def __call__(self, value): """ Validates that the input matches the regular expression. """ if not self.regex.search(smart_unicode(value)): raise ValidationError(self.message, code=self.code) class URLValidator(RegexValidator): regex = re.compile( r'^https?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' #domain... r'localhost|' #localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(?::\d+)?' # optional port r'(?:/?|[/?]\S+)$', re.IGNORECASE) def __init__(self, verify_exists=False, validator_user_agent=URL_VALIDATOR_USER_AGENT): super(URLValidator, self).__init__() self.verify_exists = verify_exists self.user_agent = validator_user_agent def __call__(self, value): try: super(URLValidator, self).__call__(value) except ValidationError, e: # Trivial case failed. Try for possible IDN domain if value: value = smart_unicode(value) scheme, netloc, path, query, fragment = urlparse.urlsplit(value) try: netloc = netloc.encode('idna') # IDN -> ACE except UnicodeError: # invalid domain part raise e url = urlparse.urlunsplit((scheme, netloc, path, query, fragment)) super(URLValidator, self).__call__(url) else: raise else: url = value if self.verify_exists: import urllib2 headers = { "Accept": "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5", "Accept-Language": "en-us,en;q=0.5", "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7", "Connection": "close", "User-Agent": self.user_agent, } try: req = urllib2.Request(url, None, headers) u = urllib2.urlopen(req) except ValueError: raise ValidationError(_(u'Enter a valid URL.'), code='invalid') except: # urllib2.URLError, httplib.InvalidURL, etc. raise ValidationError(_(u'This URL appears to be a broken link.'), code='invalid_link') def validate_integer(value): try: int(value) except (ValueError, TypeError), e: raise ValidationError('') class EmailValidator(RegexValidator): def __call__(self, value): try: super(EmailValidator, self).__call__(value) except ValidationError, e: # Trivial case failed. Try for possible IDN domain-part if value and u'@' in value: parts = value.split(u'@') domain_part = parts[-1] try: parts[-1] = parts[-1].encode('idna') except UnicodeError: raise e super(EmailValidator, self).__call__(u'@'.join(parts)) else: raise email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain validate_email = EmailValidator(email_re, _(u'Enter a valid e-mail address.'), 'invalid') slug_re = re.compile(r'^[-\w]+$') validate_slug = RegexValidator(slug_re, _(u"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."), 'invalid') ipv4_re = re.compile(r'^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$') validate_ipv4_address = RegexValidator(ipv4_re, _(u'Enter a valid IPv4 address.'), 'invalid') comma_separated_int_list_re = re.compile('^[\d,]+$') validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _(u'Enter only digits separated by commas.'), 'invalid') class BaseValidator(object): compare = lambda self, a, b: a is not b clean = lambda self, x: x message = _(u'Ensure this value is %(limit_value)s (it is %(show_value)s).') code = 'limit_value' def __init__(self, limit_value): self.limit_value = limit_value def __call__(self, value): cleaned = self.clean(value) params = {'limit_value': self.limit_value, 'show_value': cleaned} if self.compare(cleaned, self.limit_value): raise ValidationError( self.message % params, code=self.code, params=params, ) class MaxValueValidator(BaseValidator): compare = lambda self, a, b: a > b message = _(u'Ensure this value is less than or equal to %(limit_value)s.') code = 'max_value' class MinValueValidator(BaseValidator): compare = lambda self, a, b: a < b message = _(u'Ensure this value is greater than or equal to %(limit_value)s.') code = 'min_value' class MinLengthValidator(BaseValidator): compare = lambda self, a, b: a < b clean = lambda self, x: len(x) message = _(u'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).') code = 'min_length' class MaxLengthValidator(BaseValidator): compare = lambda self, a, b: a > b clean = lambda self, x: len(x) message = _(u'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).') code = 'max_length'
6,583
Python
.py
144
36.6875
140
0.584776
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,899
exceptions.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/core/exceptions.py
""" Global Django exception and warning classes. """ class DjangoRuntimeWarning(RuntimeWarning): pass class ObjectDoesNotExist(Exception): "The requested object does not exist" silent_variable_failure = True class MultipleObjectsReturned(Exception): "The query returned multiple objects when only one was expected." pass class SuspiciousOperation(Exception): "The user did something suspicious" pass class PermissionDenied(Exception): "The user did not have permission to do that" pass class ViewDoesNotExist(Exception): "The requested view does not exist" pass class MiddlewareNotUsed(Exception): "This middleware is not used in this server configuration" pass class ImproperlyConfigured(Exception): "Django is somehow improperly configured" pass class FieldError(Exception): """Some kind of problem with a model field.""" pass NON_FIELD_ERRORS = '__all__' class ValidationError(Exception): """An error while validating data.""" def __init__(self, message, code=None, params=None): import operator from django.utils.encoding import force_unicode """ ValidationError can be passed any object that can be printed (usually a string), a list of objects or a dictionary. """ if isinstance(message, dict): self.message_dict = message # Reduce each list of messages into a single list. message = reduce(operator.add, message.values()) if isinstance(message, list): self.messages = [force_unicode(msg) for msg in message] else: self.code = code self.params = params message = force_unicode(message) self.messages = [message] def __str__(self): # This is needed because, without a __str__(), printing an exception # instance would result in this: # AttributeError: ValidationError instance has no attribute 'args' # See http://www.python.org/doc/current/tut/node10.html#handling if hasattr(self, 'message_dict'): return repr(self.message_dict) return repr(self.messages) def __repr__(self): if hasattr(self, 'message_dict'): return 'ValidationError(%s)' % repr(self.message_dict) return 'ValidationError(%s)' % repr(self.messages) def update_error_dict(self, error_dict): if hasattr(self, 'message_dict'): if error_dict: for k, v in self.message_dict.items(): error_dict.setdefault(k, []).extend(v) else: error_dict = self.message_dict else: error_dict[NON_FIELD_ERRORS] = self.messages return error_dict
2,767
Python
.py
72
30.902778
77
0.660075
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)