Here are the examples of the python api django.core.urlresolvers.reverse taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
174 Examples
0
Example 151
def init_with_context(self, context):
user = context['request'].user
if user.is_superuser:
self.children += [
items.MenuItem(_('Dashboard'), reverse('admin:index')),
items.Bookmarks(),
items.MenuItem(_('Companies'),
children=[
items.MenuItem(_('Companies'), '/extranet/pyfreebill/company/',
children=[
items.MenuItem(_('List'), '/extranet/pyfreebill/company/',
children=[
items.MenuItem(_('All'), '/extranet/pyfreebill/company/'),
items.MenuItem(_('Customers'), '/extranet/pyfreebill/company/?customer_enabled__exact=1',
children=[
items.MenuItem(_('All'), '/extranet/pyfreebill/company/?customer_enabled__exact=1'),
items.MenuItem(_('Prepaid Account'), '/extranet/pyfreebill/company/?customer_enabled__exact=1&prepaid__exact=1'),
items.MenuItem(_('Postpaid account'), '/extranet/pyfreebill/company/?customer_enabled__exact=1&prepaid__exact=0'),
]
),
items.MenuItem(_('Providers'), '/extranet/pyfreebill/company/?supplier_enabled__exact=1'),
items.MenuItem(_('Add new company'), '/extranet/pyfreebill/company/add/'),
]
),
items.MenuItem(_('Balance history'), '/extranet/pyfreebill/companybalancehistory/'),
items.MenuItem(_('Add payment'), '/extranet/pyfreebill/companybalancehistory/add/'),
items.MenuItem(_('customer management'),
children=[
items.MenuItem(_('Customer SIP accounts'), '/extranet/pyfreebill/customerdirectory/'),
items.MenuItem(_('Destination number normalization rules'), '/extranet/pyfreebill/customernormalizationrules/'),
items.MenuItem(_('CallerID Normalization Rules'), '/extranet/pyfreebill/customercidnormalizationrules/'),
]
),
items.MenuItem(_('provider management'),
children=[
items.MenuItem(_('Provider gateways'), '/extranet/pyfreebill/sofiagateway/'),
items.MenuItem(_('CallerID Normalization Rules'), '/extranet/pyfreebill/carriercidnormalizationrules/'),
]
),
]
),
items.MenuItem(_('Contacts'), '/extranet/pyfreebill/person/',
children=[
items.MenuItem(_('List'), '/extranet/pyfreebill/person/'),
items.MenuItem(_('Add'), '/extranet/pyfreebill/person/add/'),
]
),
items.MenuItem(_('Groups'), '/extranet/pyfreebill/group/',
children=[
items.MenuItem(_('List'), '/extranet/pyfreebill/group/'),
items.MenuItem(_('Add'), '/extranet/pyfreebill/group/add/'),
]
),
]
),
items.MenuItem(_('Rates'),
children=[
items.MenuItem(_('Sell rates'),
children=[
items.MenuItem(_('Ratecards'), '/extranet/pyfreebill/ratecard/'),
items.MenuItem(_('Customer ratecards'), '/extranet/pyfreebill/customerratecards/'),
items.MenuItem(_('Rates'), '/extranet/pyfreebill/customerrates/'),
]
),
items.MenuItem(_('LCRs'), '/extranet/pyfreebill/lcrgroup/'),
items.MenuItem(_('Provider rates'),
children=[
items.MenuItem(_('Provider tariffs'), '/extranet/pyfreebill/providertariff/'),
items.MenuItem(_('Provider rates'), '/extranet/pyfreebill/providerrates/'),
]
),
]
),
items.MenuItem(_('Reports'),
children=[
items.MenuItem(_('CDRs'), '/extranet/pyfreebill/cdr/',
children=[
items.MenuItem(_('CDRs view'), '/extranet/pyfreebill/cdr/'),
items.MenuItem(_('Successfull CDRs'), '/extranet/pyfreebill/cdr/?effective_duration__gt=0'),
items.MenuItem(_('Failed CDRs'), '/extranet/pyfreebill/cdr/?effective_duration__exact=0'),
items.MenuItem(_('Hangup Cause'), '/extranet/pyfreebill/hangupcause/'),
]
),
items.MenuItem(_('Reports'), '/extranet/report/'),
]
),
items.MenuItem(_('Admin'),
children=[
items.MenuItem(_('Users'), '/extranet/auth/',
children=[
items.MenuItem(_('Groups'), '/extranet/auth/group/'),
items.MenuItem(_('Users'), '/extranet/auth/user/'),
items.MenuItem(_('Rates'), '/extranet/pyfreebill/customerrates/'),
]
),
items.MenuItem(_('VoIP switches'),
children=[
items.MenuItem(_('VoIP switches'), '/extranet/pyfreebill/voipswitch/'),
items.MenuItem(_('SIP profiles'), '/extranet/pyfreebill/sipprofile/'),
items.MenuItem(_('Destination Number Normalization Rules'), '/extranet/pyfreebill/destinationnumberrules/'),
items.MenuItem(_('ACL'), '/extranet/pyfreebill/acllists/'),
]
),
items.MenuItem(_('Logs'),
children=[
items.MenuItem(_('Access logs'), '/extranet/axes/accesslog/'),
items.MenuItem(_('Access attemps'), '/extranet/axes/accessattempt/'),
items.MenuItem(_('Honeypot access attemps'), '/extranet/admin_honeypot/loginattempt/'),
items.MenuItem(_('Recurring tasks logs'), '/extranet/chroniker/log/'),
]
),
items.MenuItem(_('Databases'),
children=[
items.MenuItem(_('Database size'), '/extranet/database_size/table/'),
]
),
items.MenuItem(_('Status'), '/extranet/status/'),
]
),
]
else:
self.children += [
items.MenuItem(_('Dashboard'), reverse('admin:index')),
items.MenuItem(_('My Account'), '/extranet/pyfreebill/company/'),
items.MenuItem(_('My CDR'), '/extranet/pyfreebill/cdr/'),
]
# self.children += [
# ReturnToSiteItem()
# ]
return super(CustomMenu, self).init_with_context(context)
0
Example 152
Project: yournextrepresentative Source File: constituencies.py
def get_context_data(self, **kwargs):
from ..election_specific import shorten_post_label
context = super(ConstituencyDetailView, self).get_context_data(**kwargs)
context['post_id'] = post_id = kwargs['post_id']
mp_post = get_object_or_404(
Post.objects.select_related('extra'),
extra__slug=post_id
)
docuements_by_type = {}
# Make sure that every available docuement type has a key in
# the dictionary, even if there are no such docuements.
doc_lookup = {t[0]: (t[1], t[2]) for t in OfficialDocuement.DOCUMENT_TYPES}
for t in doc_lookup.values():
docuements_by_type[t] = []
docuements_for_post = OfficialDocuement.objects.filter(post_id=mp_post.id)
for od in docuements_for_post:
docuements_by_type[doc_lookup[od.docuement_type]].append(od)
context['official_docuements'] = docuements_by_type.items()
context['some_official_docuements'] = docuements_for_post.count()
context['post_label'] = mp_post.label
context['post_label_shorter'] = shorten_post_label(context['post_label'])
context['redirect_after_login'] = \
urlquote(reverse('constituency', kwargs={
'election': self.election,
'post_id': post_id,
'ignored_slug': slugify(context['post_label_shorter'])
}))
context['post_data'] = {
'id': mp_post.extra.slug,
'label': mp_post.label
}
context['candidates_locked'] = False
if hasattr(mp_post, 'extra'):
context['candidates_locked'] = mp_post.extra.candidates_locked
context['lock_form'] = ToggleLockForm(
initial={
'post_id': post_id,
'lock': not context['candidates_locked'],
},
)
context['candidate_list_edits_allowed'] = \
get_edits_allowed(self.request.user, context['candidates_locked'])
extra_qs = MembershipExtra.objects.select_related('election')
current_candidacies, past_candidacies = \
split_candidacies(
self.election_data,
mp_post.memberships.prefetch_related(
Prefetch('extra', queryset=extra_qs)
).select_related(
'person', 'person__extra', 'on_behalf_of',
'on_behalf_of__extra', 'organization'
).all()
)
current_candidates = set(c.person for c in current_candidacies)
past_candidates = set(c.person for c in past_candidacies)
other_candidates = past_candidates - current_candidates
elected, unelected = split_by_elected(
self.election_data,
current_candidacies,
)
# Now split those candidates into those that we know aren't
# standing again, and those that we just don't know about.
not_standing_candidates = set(
p for p in other_candidates
if self.election_data in p.extra.not_standing.all()
)
might_stand_candidates = set(
p for p in other_candidates
if self.election_data not in p.extra.not_standing.all()
)
not_standing_candidacies = [c for c in past_candidacies
if c.person in not_standing_candidates]
might_stand_candidacies = [c for c in past_candidacies
if c.person in might_stand_candidates]
context['candidacies_not_standing_again'] = \
group_candidates_by_party(
self.election_data,
not_standing_candidacies,
party_list=self.election_data.party_lists_in_use,
max_people=self.election_data.default_party_list_members_to_show
)
context['candidacies_might_stand_again'] = \
group_candidates_by_party(
self.election_data,
might_stand_candidacies,
party_list=self.election_data.party_lists_in_use,
max_people=self.election_data.default_party_list_members_to_show
)
context['elected'] = group_candidates_by_party(
self.election_data,
elected,
party_list=self.election_data.party_lists_in_use,
max_people=None
)
context['unelected'] = group_candidates_by_party(
self.election_data,
unelected,
party_list=self.election_data.party_lists_in_use,
max_people=self.election_data.default_party_list_members_to_show
)
context['has_elected'] = \
len(context['elected']['parties_and_people']) > 0
context['show_retract_result'] = False
number_of_winners = 0
for c in current_candidacies:
if c.extra.elected:
number_of_winners += 1
if c.extra.elected is not None:
context['show_retract_result'] = True
max_winners = get_max_winners(mp_post, self.election_data)
context['show_confirm_result'] = (max_winners < 0) \
or number_of_winners < max_winners
context['add_candidate_form'] = NewPersonForm(
election=self.election,
initial={
('constituency_' + self.election): post_id,
('standing_' + self.election): 'standing',
},
hidden_post_widget=True,
)
context = get_person_form_fields(
context,
context['add_candidate_form']
)
return context
0
Example 153
Project: yournextrepresentative Source File: views.py
def form_valid(self, form):
decision = form.cleaned_data['decision']
person = Person.objects.get(
id=self.queued_image.person.id
)
person_extra = person.extra
candidate_path = person_extra.get_absolute_url()
candidate_name = person.name
candidate_link = '<a href="{url}">{name}</a>'.format(
url=candidate_path,
name=candidate_name,
)
photo_review_url = self.request.build_absolute_uri(
self.queued_image.get_absolute_url()
)
site_name = Site.objects.get_current().name
def flash(level, message):
messages.add_message(
self.request,
level,
message,
extra_tags='safe photo-review'
)
if decision == 'approved':
# Crop the image...
crop_fields = ('x_min', 'y_min', 'x_max', 'y_max')
self.crop_and_upload_image_to_popit(
self.queued_image.image.path,
[form.cleaned_data[e] for e in crop_fields],
form.cleaned_data['moderator_why_allowed'],
form.cleaned_data['make_primary'],
)
self.queued_image.decision = 'approved'
for i, field in enumerate(crop_fields):
setattr(
self.queued_image,
'crop_' + field,
form.cleaned_data[field]
)
self.queued_image.save()
update_message = _('Approved a photo upload from '
'{uploading_user} who provided the message: '
'"{message}"').format(
uploading_user=self.queued_image.user.username,
message=self.queued_image.justification_for_use,
)
change_metadata = get_change_metadata(
self.request,
update_message
)
person_extra.record_version(change_metadata)
person_extra.save()
person.save()
LoggedAction.objects.create(
user=self.request.user,
action_type='photo-approve',
ip_address=get_client_ip(self.request),
popit_person_new_version=change_metadata['version_id'],
person=person,
source=update_message,
)
candidate_full_url = person_extra.get_absolute_url(self.request)
self.send_mail(
_('{site_name} image upload approved').format(
site_name=site_name
),
render_to_string(
'moderation_queue/photo_approved_email.txt',
{
'site_name': site_name,
'candidate_page_url': candidate_full_url,
'intro': _(
"Thank-you for submitting a photo to "
"{site_name}; that's been uploaded now for "
"the candidate page here:"
).format(site_name=site_name),
'signoff': _(
"Many thanks from the {site_name} volunteers"
).format(site_name=site_name),
}
),
)
flash(
messages.SUCCESS,
_('You approved a photo upload for %s') % candidate_link
)
elif decision == 'rejected':
self.queued_image.decision = 'rejected'
self.queued_image.save()
update_message = _('Rejected a photo upload from '
'{uploading_user}').format(
uploading_user=self.queued_image.user.username,
)
LoggedAction.objects.create(
user=self.request.user,
action_type='photo-reject',
ip_address=get_client_ip(self.request),
popit_person_new_version='',
person=person,
source=update_message,
note=form.cleaned_data['rejection_reason'],
)
retry_upload_link = self.request.build_absolute_uri(
reverse(
'photo-upload',
kwargs={'person_id': self.queued_image.person.id}
)
)
self.send_mail(
_('{site_name} image moderation results').format(
site_name=Site.objects.get_current().name
),
render_to_string(
'moderation_queue/photo_rejected_email.txt',
{
'reason': form.cleaned_data['rejection_reason'],
'retry_upload_link': retry_upload_link,
'photo_review_url': photo_review_url,
'intro': _(
"Thank-you for uploading a photo of "
"{candidate_name} to {site_name}, but "
"unfortunately we can't use that image because:"
).format(
candidate_name=candidate_name,
site_name=site_name
),
'possible_actions': _(
'You can just reply to this email if you want to '
'discuss that further, or you can try uploading a '
'photo with a different reason or justification '
'for its use using this link:'
),
'signoff': _(
"Many thanks from the {site_name} volunteers"
).format(site_name=site_name),
},
),
email_support_too=True,
)
flash(
messages.INFO,
_('You rejected a photo upload for %s') % candidate_link
)
elif decision == 'undecided':
# If it's left as undecided, just redirect back to the
# photo review queue...
flash(
messages.INFO,
_('You left a photo upload for {0} in the queue').format(
candidate_link
)
)
elif decision == 'ignore':
self.queued_image.decision = 'ignore'
self.queued_image.save()
update_message = _('Ignored a photo upload from '
'{uploading_user} (This usually means it was a duplicate)').format(
uploading_user=self.queued_image.user.username)
LoggedAction.objects.create(
user=self.request.user,
action_type='photo-ignore',
ip_address=get_client_ip(self.request),
popit_person_new_version='',
person=person,
source=update_message,
)
flash(
messages.INFO,
_('You indicated a photo upload for {0} should be ignored').format(
candidate_link
)
)
else:
raise Exception("BUG: unexpected decision {0}".format(decision))
return HttpResponseRedirect(reverse('photo-review-list'))
0
Example 154
Project: djangocms-blog Source File: test_models.py
def test_model_attributes(self):
self.get_pages()
self.app_config_1.app_data.config.gplus_author = 'RandomJoe'
self.app_config_1.save()
post = self._get_post(self._post_data[0]['en'])
post = self._get_post(self._post_data[0]['it'], post, 'it')
post.main_image = self.create_filer_image_object()
post.publish = True
post.save()
post.set_current_language('en')
meta_en = post.as_meta()
self.assertEqual(meta_en.og_type, get_setting('FB_TYPE'))
self.assertEqual(meta_en.title, post.title)
self.assertTrue(meta_en.url.endswith(post.get_absolute_url()))
self.assertEqual(meta_en.description, post.meta_description)
self.assertEqual(meta_en.keywords, post.meta_keywords.split(','))
self.assertEqual(meta_en.published_time, post.date_published)
self.assertEqual(meta_en.locale, 'en')
self.assertEqual(meta_en.twitter_site, '')
self.assertEqual(meta_en.twitter_author, '')
self.assertEqual(meta_en.twitter_type, 'summary')
self.assertEqual(meta_en.gplus_author, 'RandomJoe')
self.assertEqual(meta_en.gplus_type, 'Blog')
self.assertEqual(meta_en.og_type, 'Article')
self.assertEqual(meta_en.facebook_app_id, None)
post.set_current_language('it')
meta_it = post.as_meta()
self.assertEqual(meta_it.title, post.title)
self.assertTrue(meta_it.url.endswith(post.get_absolute_url()))
self.assertNotEqual(meta_it.title, meta_en.title)
self.assertEqual(meta_it.description, post.meta_description)
with override('en'):
post.set_current_language(get_language())
kwargs = {'year': post.date_published.year,
'month': '%02d' % post.date_published.month,
'day': '%02d' % post.date_published.day,
'slug': post.safe_translation_getter('slug', any_language=get_language())}
url_en = reverse(
'%s:post-detail' % self.app_config_1.namespace,
kwargs=kwargs,
current_app=self.app_config_1.namespace
)
self.assertEqual(url_en, post.get_absolute_url())
with override('it'):
post.set_current_language(get_language())
kwargs = {'year': post.date_published.year,
'month': '%02d' % post.date_published.month,
'day': '%02d' % post.date_published.day,
'slug': post.safe_translation_getter('slug', any_language=get_language())}
url_it = reverse(
'%s:post-detail' % self.app_config_1.namespace,
kwargs=kwargs,
current_app=self.app_config_1.namespace
)
self.assertEqual(url_it, post.get_absolute_url())
self.assertNotEqual(url_it, url_en)
self.assertEqual(post.get_full_url(), 'http://example.com%s' % url_it)
self.assertEqual(post.get_image_full_url(), 'http://example.com%s' % post.main_image.url)
self.assertEqual(post.thumbnail_options(), get_setting('IMAGE_THUMBNAIL_SIZE'))
self.assertEqual(post.full_image_options(), get_setting('IMAGE_FULL_SIZE'))
post.main_image_thumbnail = self.thumb_1
post.main_image_full = self.thumb_2
self.assertEqual(post.thumbnail_options(), {
'size': (100, 100),
'width': 100, 'height': 100,
'crop': True,
'upscale': False
})
self.assertEqual(post.full_image_options(), {
'size': (200, 200),
'width': 200, 'height': 200,
'crop': False,
'upscale': False
})
post.set_current_language('en')
post.meta_title = 'meta title'
self.assertEqual(post.get_title(), 'meta title')
# Assess is_published property
post.publish = False
post.save()
self.assertFalse(post.is_published)
post.publish = True
post.date_published = now() + timedelta(days=1)
post.date_published_end = None
post.save()
self.assertFalse(post.is_published)
post.publish = True
post.date_published = now() - timedelta(days=1)
post.date_published_end = now() - timedelta(minutes=1)
post.save()
self.assertFalse(post.is_published)
post.publish = True
post.date_published = now() - timedelta(days=1)
post.date_published_end = None
post.save()
self.assertTrue(post.is_published)
post.publish = True
post.date_published = now() - timedelta(days=1)
post.date_published_end = now() + timedelta(minutes=1)
post.save()
self.assertTrue(post.is_published)
post.publish = False
post.date_published = now() - timedelta(days=1)
post.date_published_end = None
post.save()
self.assertFalse(post.is_published)
post.publish = False
post.date_published = now() - timedelta(days=1)
post.date_published_end = now() + timedelta(minutes=1)
post.save()
self.assertFalse(post.is_published)
0
Example 155
Project: archivematica Source File: views.py
def rights_edit(request, uuid, id=None, section='ingest'):
jobs = models.Job.objects.filter(sipuuid=uuid, subjobof='')
name = utils.get_directory_name_from_job(jobs[0])
# flag indicating what kind of new content, if any, has been created
new_content_type_created = None
max_notes = 1
if id:
viewRights = models.RightsStatement.objects.get(pk=id)
agentId = None
if request.method == 'POST':
postData = request.POST.copy()
"""
agentId = rights_parse_agent_id(postData.get('rightsholder'))
if agentId == 0 and postData.get('rightsholder') != '0' and postData.get('rightsholder') != '':
agent = models.RightsStatementLinkingAgentIdentifier()
agent.rightsstatement = viewRights
agent.linkingagentidentifiervalue = postData.get('rightsholder')
agent.save()
agentId = agent.id
postData.__setitem__('rightsholder', agentId)
"""
form = forms.RightsForm(postData, instance=viewRights)
form.cleaned_data = postData
viewRights = form.save()
else:
form = forms.RightsForm(instance=viewRights)
form.cleaned_data = viewRights
form.save()
# determine how many empty forms should be shown for children
extra_copyright_forms = max_notes - models.RightsStatementCopyright.objects.filter(rightsstatement=viewRights).count()
extra_statute_forms = max_notes - models.RightsStatementStatuteInformation.objects.filter(rightsstatement=viewRights).count()
extra_license_forms = max_notes - models.RightsStatementLicense.objects.filter(rightsstatement=viewRights).count()
extra_other_forms = max_notes - models.RightsStatementOtherRightsInformation.objects.filter(rightsstatement=viewRights).count()
else:
if request.method == 'POST':
postData = request.POST.copy()
agentId = rights_parse_agent_id(postData.get('rightsholder'))
postData.__setitem__('rightsholder', agentId)
form = forms.RightsForm(postData)
else:
form = forms.RightsForm()
viewRights = models.RightsStatement()
extra_copyright_forms = max_notes
extra_statute_forms = max_notes
extra_license_forms = max_notes
extra_license_notes = max_notes
extra_other_forms = max_notes
# create inline formsets for child elements
CopyrightFormSet = inlineformset_factory(
models.RightsStatement,
models.RightsStatementCopyright,
extra=extra_copyright_forms,
can_delete=False,
form=forms.RightsCopyrightForm
)
StatuteFormSet = inlineformset_factory(
models.RightsStatement,
models.RightsStatementStatuteInformation,
extra=extra_statute_forms,
can_delete=False,
form=forms.RightsStatuteForm
)
LicenseFormSet = inlineformset_factory(
models.RightsStatement,
models.RightsStatementLicense,
extra=extra_license_forms,
can_delete=False,
form=forms.RightsLicenseForm
)
OtherFormSet = inlineformset_factory(
models.RightsStatement,
models.RightsStatementOtherRightsInformation,
extra=extra_other_forms,
can_delete=False,
form=forms.RightsOtherRightsForm
)
copyrightFormset = CopyrightFormSet()
statuteFormset = StatuteFormSet()
licenseFormset = LicenseFormSet()
otherFormset = OtherFormSet()
# handle form creation/saving
if request.method == 'POST':
if id:
createdRights = viewRights
else:
sectionTypeID = {'transfer': 'Transfer', 'ingest': 'SIP'}
type_id = helpers.get_metadata_type_id_by_description(sectionTypeID[section])
newRights = models.RightsStatement(metadataappliestotype=type_id, metadataappliestoidentifier=uuid)
form = forms.RightsForm(request.POST, instance=newRights)
createdRights = form.save()
copyrightFormset = CopyrightFormSet(request.POST, instance=createdRights)
if not copyrightFormset.is_valid():
return render(request, 'rights/rights_edit.html', locals())
createdCopyrightSet = copyrightFormset.save()
# establish whether or not there is a copyright information instance to use as a parent
if len(createdCopyrightSet) == 1:
createdCopyright = createdCopyrightSet[0]
else:
createdCopyright = False
# handle creation of new copyright notes, creating parent if necessary
if request.POST.get('copyright_note', '') != '':
# make new copyright record if it doesn't exist
if not createdCopyright:
try:
createdCopyright = models.RightsStatementCopyright.objects.get(rightsstatement=createdRights)
except:
createdCopyright = models.RightsStatementCopyright(rightsstatement=createdRights)
createdCopyright.save()
copyrightNote = models.RightsStatementCopyrightNote(rightscopyright=createdCopyright)
copyrightNote.copyrightnote = request.POST.get('copyright_note', '')
copyrightNote.save()
new_content_type_created = 'copyright'
# handle creation of new docuementation identifiers
if request.POST.get('copyright_docuementation_identifier_type', '') != '' or request.POST.get('copyright_docuementation_identifier_value', '') != '' or request.POST.get('copyright_docuementation_identifier_role', ''):
# make new copyright record if it doesn't exist
if not createdCopyright:
try:
createdCopyright = models.RightsStatementCopyright.objects.get(rightsstatement=createdRights)
except:
createdCopyright = models.RightsStatementCopyright(rightsstatement=createdRights)
createdCopyright.save()
copyrightDocIdentifier = models.RightsStatementCopyrightDocuementationIdentifier(rightscopyright=createdCopyright)
copyrightDocIdentifier.copyrightdocuementationidentifiertype = request.POST.get('copyright_docuementation_identifier_type', '')
copyrightDocIdentifier.copyrightdocuementationidentifiervalue = request.POST.get('copyright_docuementation_identifier_value', '')
copyrightDocIdentifier.copyrightdocuementationidentifierrole = request.POST.get('copyright_docuementation_identifier_role', '')
copyrightDocIdentifier.save()
new_content_type_created = 'copyright'
licenseFormset = LicenseFormSet(request.POST, instance=createdRights)
if not licenseFormset.is_valid():
return render(request, 'rights/rights_edit.html', locals())
createdLicenseSet = licenseFormset.save()
# establish whether or not there is a license instance to use as a parent
if len(createdLicenseSet) == 1:
createdLicense = createdLicenseSet[0]
else:
createdLicense = False
# handle creation of new copyright notes, creating parent if necessary
if request.POST.get('license_note', '') != '':
# make new copyright record if it doesn't exist
if not createdLicense:
try:
createdLicense = models.RightsStatementLicense.objects.get(rightsstatement=createdRights)
except:
createdLicense = models.RightsStatementLicense(rightsstatement=createdRights)
createdLicense.save()
licenseNote = models.RightsStatementLicenseNote(rightsstatementlicense=createdLicense)
licenseNote.licensenote = request.POST.get('license_note', '')
licenseNote.save()
new_content_type_created = 'license'
# handle creation of new docuementation identifiers
if request.POST.get('license_docuementation_identifier_type', '') != '' or request.POST.get('license_docuementation_identifier_value', '') != '' or request.POST.get('license_docuementation_identifier_role', ''):
# make new license record if it doesn't exist
if not createdLicense:
try:
createdLicense = models.RightsStatementLicense.objects.get(rightsstatement=createdRights)
except:
createdLicense = models.RightsStatementLicense(rightsstatement=createdRights)
createdLicense.save()
licenseDocIdentifier = models.RightsStatementLicenseDocuementationIdentifier(rightsstatementlicense=createdLicense)
licenseDocIdentifier.licensedocuementationidentifiertype = request.POST.get('license_docuementation_identifier_type', '')
licenseDocIdentifier.licensedocuementationidentifiervalue = request.POST.get('license_docuementation_identifier_value', '')
licenseDocIdentifier.licensedocuementationidentifierrole = request.POST.get('license_docuementation_identifier_role', '')
licenseDocIdentifier.save()
new_content_type_created = 'license'
statuteFormset = StatuteFormSet(request.POST, instance=createdRights)
if not statuteFormset.is_valid():
return render(request, 'rights/rights_edit.html', locals())
createdStatuteSet = statuteFormset.save()
if request.POST.get('statute_previous_pk', '') == 'None' and len(createdStatuteSet) == 1:
new_content_type_created = 'statute'
noteCreated = False
for form in statuteFormset.forms:
statuteCreated = False
# handle docuementation identifier creation for a parent that's a blank statute
if (request.POST.get('statute_docuementation_identifier_type_None', '') != '' or request.POST.get('statute_docuementation_identifier_value_None', '') != '' or request.POST.get('statute_docuementation_identifier_role_None', '') != ''):
if form.instance.pk:
statuteCreated = form.instance
else:
statuteCreated = models.RightsStatementStatuteInformation(rightsstatement=createdRights)
statuteCreated.save()
statuteDocIdentifier = models.RightsStatementStatuteDocuementationIdentifier(rightsstatementstatute=statuteCreated)
statuteDocIdentifier.statutedocuementationidentifiertype = request.POST.get('statute_docuementation_identifier_type_None', '')
statuteDocIdentifier.statutedocuementationidentifiervalue = request.POST.get('statute_docuementation_identifier_value_None', '')
statuteDocIdentifier.statutedocuementationidentifierrole = request.POST.get('statute_docuementation_identifier_role_None', '')
statuteDocIdentifier.save()
new_content_type_created = 'statute'
else:
# handle docuementation identifier creation for a parent statute that already exists
if request.POST.get('statute_docuementation_identifier_type_' + str(form.instance.pk), '') != '' or request.POST.get('statute_docuementation_identifier_value_' + str(form.instance.pk), '') or request.POST.get('statute_docuementation_identifier_role_' + str(form.instance.pk), ''):
statuteDocIdentifier = models.RightsStatementStatuteDocuementationIdentifier(rightsstatementstatute=form.instance)
statuteDocIdentifier.statutedocuementationidentifiertype = request.POST.get('statute_docuementation_identifier_type_' + str(form.instance.pk), '')
statuteDocIdentifier.statutedocuementationidentifiervalue = request.POST.get('statute_docuementation_identifier_value_' + str(form.instance.pk), '')
statuteDocIdentifier.statutedocuementationidentifierrole = request.POST.get('statute_docuementation_identifier_role_' + str(form.instance.pk), '')
statuteDocIdentifier.save()
new_content_type_created = 'statute'
# handle note creation for a parent that's a blank grant
if request.POST.get('new_statute_note_None', '') != '' and not form.instance.pk:
if not statuteCreated:
statuteCreated = models.RightsStatementStatuteInformation(rightsstatement=createdRights)
statuteCreated.save()
noteCreated = models.RightsStatementStatuteInformationNote(rightsstatementstatute=statuteCreated)
noteCreated.statutenote = request.POST.get('new_statute_note_None', '')
noteCreated.save()
new_content_type_created = 'statue'
else:
# handle note creation for a parent grant that already exists
if request.POST.get('new_statute_note_' + str(form.instance.pk), '') != '':
noteCreated = models.RightsStatementStatuteInformationNote(rightsstatementstatute=form.instance)
noteCreated.statutenote = request.POST.get('new_statute_note_' + str(form.instance.pk), '')
noteCreated.save()
new_content_type_created = 'statute'
# handle note creation for a parent that's just been created
if request.POST.get('new_statute_note_None', '') != '' and not noteCreated:
noteCreated = models.RightsStatementStatuteInformationNote(rightsstatementstatute=form.instance)
noteCreated.statutenote = request.POST.get('new_statute_note_None', '')
noteCreated.save()
# display (possibly revised) formset
statuteFormset = StatuteFormSet(instance=createdRights)
otherFormset = OtherFormSet(request.POST, instance=createdRights)
if not otherFormset.is_valid():
return render(request, 'rights/rights_edit.html', locals())
createdOtherSet = otherFormset.save()
# establish whether or not there is an "other" instance to use as a parent
if len(createdOtherSet) == 1:
createdOther = createdOtherSet[0]
else:
createdOther = False
# handle creation of new "other" notes, creating parent if necessary
if request.POST.get('otherrights_note', '') != '':
# make new "other" record if it doesn't exist
if not createdOther:
try:
createdOther = models.RightsStatementOtherRightsInformation.objects.get(rightsstatement=createdRights)
except:
createdOther = models.RightsStatementOtherRightsInformation(rightsstatement=createdRights)
createdOther.save()
otherNote = models.RightsStatementOtherRightsInformationNote(rightsstatementotherrights=createdOther)
otherNote.otherrightsnote = request.POST.get('otherrights_note', '')
otherNote.save()
new_content_type_created = 'other'
# handle creation of new docuementation identifiers
if request.POST.get('other_docuementation_identifier_type', '') != '' or request.POST.get('other_docuementation_identifier_value', '') != '' or request.POST.get('other_docuementation_identifier_role', ''):
# make new other record if it doesn't exist
if not createdOther:
try:
createdOther = models.RightsStatementOtherRightsInformation.objects.get(rightsstatement=createdRights)
except:
createdOther = models.RightsStatementOtherRightsInformation(rightsstatement=createdRights)
createdOther.save()
otherDocIdentifier = models.RightsStatementOtherRightsDocuementationIdentifier(rightsstatementotherrights=createdOther)
otherDocIdentifier.otherrightsdocuementationidentifiertype = request.POST.get('other_docuementation_identifier_type', '')
otherDocIdentifier.otherrightsdocuementationidentifiervalue = request.POST.get('other_docuementation_identifier_value', '')
otherDocIdentifier.otherrightsdocuementationidentifierrole = request.POST.get('other_docuementation_identifier_role', '')
otherDocIdentifier.save()
new_content_type_created = 'other'
if request.POST.get('next_button', '') != None and request.POST.get('next_button', '') != '':
return redirect('components.rights.views.%s_rights_grants_edit' % section, uuid, createdRights.pk)
else:
url = reverse('components.rights.views.%s_rights_edit' % section, args=[uuid, createdRights.pk])
try:
url = url + '?created=' + new_content_type_created
except:
pass
return redirect(url)
else:
copyrightFormset = CopyrightFormSet(instance=viewRights)
statuteFormset = StatuteFormSet(instance=viewRights)
licenseFormset = LicenseFormSet(instance=viewRights)
otherFormset = OtherFormSet(instance=viewRights)
# show what content's been created after a redirect
if request.GET.get('created', '') != '':
new_content_type_created = request.GET.get('created', '')
return render(request, 'rights/rights_edit.html', locals())
0
Example 156
def init_with_context(self, context):
request = context['request']
# we want a 3 columns layout
self.columns = 3
self.children.append(modules.Group(
title=_("General"),
display="tabs",
children=[
modules.AppList(
title=_('User'),
models=('django.contrib.*', 'user_profile.*', 'agent.*', ),
),
modules.AppList(
_('Task Manager'),
models=('djcelery.*', ),
),
modules.AppList(
_('Dashboard stats'),
models=('admin_tools_stats.*', ),
),
modules.RecentActions(_('Recent Actions'), 5),
]
))
self.children.append(modules.AppList(
_('Callcenter'),
models=('callcenter.*', ),
))
self.children.append(modules.AppList(
_('Settings'),
models=('dialer_settings.*', ),
))
# append an app list module for "Dialer"
self.children.append(modules.AppList(
_('VoIP dialer'),
models=('dialer_cdr.*', 'dialer_gateway.*', 'dialer_contact.*', 'dialer_campaign.*', ),
))
# append an app list module for "Dialer"
self.children.append(modules.AppList(
_('Surveys'),
models=('survey.*', ),
))
self.children.append(modules.AppList(
_('SMS Gateway'),
models=('sms.*', ),
))
# append an app list module for "SMS"
self.children.append(modules.AppList(
_('SMS module'),
models=('mod_sms.*', ),
))
# append an app list module for "Dialer"
self.children.append(modules.AppList(
_('Audio Files'),
models=('audiofield.*', ),
))
self.children.append(modules.AppList(
_('Do Not Call'),
models=('dnc.*', ),
))
self.children.append(modules.AppList(
_('Appointment'),
models=('appointment.*', ),
))
self.children.append(modules.AppList(
_('Mod Mailer'),
models=('mod_mailer.*', ),
))
self.children.append(modules.AppList(
_('Calendar Settings'),
models=('calendar_settings.*', ),
))
self.children.append(modules.LinkList(
_('Reporting'),
draggable=True,
deletable=True,
collapsible=True,
children=[
[_('Call Daily Report'),
reverse('admin:dialer_cdr_voipcall_changelist') + 'voip_daily_report/'],
],
))
# append a link list module for "quick links"
# site_name = get_admin_site_name(context)
# Quick link seems to broke the admin design if too many element
self.children.append(modules.LinkList(
_('Quick links'),
layout='inline',
draggable=True,
deletable=True,
collapsible=True,
children=[
[_('Newfies-Dialer Website'), 'http://www.newfies-dialer.org/'],
[_('Support'), 'http://www.newfies-dialer.org/about-us/contact/'],
[_('Add-ons'), 'http://www.newfies-dialer.org/add-ons/'],
# [_('Change password'), reverse('%s:password_change' % site_name)],
# [_('Log out'), reverse('%s:logout' % site_name)],
],
))
if not settings.DEBUG:
# append a feed module
self.children.append(modules.Feed(
_('Latest Newfies-Dialer News'),
feed_url='http://www.newfies-dialer.org/category/blog/feed/',
limit=5
))
# append an app list module for "Country_prefix"
self.children.append(modules.AppList(
_('Dashboard Stats Settings'),
models=('admin_dashboard_stats.*', ),
))
# Copy following code into your custom dashboard
graph_list = get_active_graph()
for i in graph_list:
kwargs = {}
kwargs['require_chart_jscss'] = False
kwargs['graph_key'] = i.graph_key
if request.POST.get('select_box_' + i.graph_key):
kwargs['select_box_' + i.graph_key] = request.POST['select_box_' + i.graph_key]
self.children.append(DashboardCharts(**kwargs))
0
Example 157
Project: newfies-dialer Source File: admin.py
def import_contact(self, request):
"""Add custom method in django admin view to import CSV file of
Contacts
**Attributes**:
* ``form`` - Contact_fileImport
* ``template`` - admin/dialer_campaign/contact/import_contact.html
**Logic Description**:
* Before adding contact, check the dialer setting limit if
applicable to the user.
* Add a new contact which will belong to the logged in user
via csv file & get the result (Upload success & failure
statistics)
**Important variable**:
* total_rows - Total no. of records in the CSV file
* retail_record_count - No. of records which are imported from
The CSV file
"""
# Check dialer setting limit
if request.user and request.method == 'POST':
# check Max Number of subscribers per campaign
if check_dialer_setting(request, check_for="contact"):
msg = _("you have too many contacts. you are allowed a maximum of %(limit)s")\
% {'limit': dialer_setting_limit(request, limit_for="contact")}
messages.error(request, msg)
# campaign limit reached
frontend_send_notification(request, NOTIFICATION_NAME.campaign_limit_reached)
return HttpResponseRedirect(reverse("admin:dialer_campaign_contact_changelist"))
opts = Contact._meta
rdr = '' # will contain CSV data
msg = ''
error_msg = ''
success_import_list = []
type_error_import_list = []
contact_cnt = 0
bulk_record = []
form = Contact_fileImport(request.user, request.POST or None, request.FILES or None)
if form.is_valid():
# col_no - field name
# 0 - contact
# 1 - last_name
# 2 - first_name
# 3 - email
# 4 - description
# 5 - status
# 6 - address
# 7 - city
# 8 - state
# 9 - country
# 10 - unit_number
# 11 - additional_vars
# To count total rows of CSV file
records = csv.reader(request.FILES['csv_file'], delimiter='|', quotechar='"')
total_rows = len(list(records))
BULK_SIZE = 1000
rdr = csv.reader(request.FILES['csv_file'], delimiter='|', quotechar='"')
# Get Phonebook Obj
phonebook = Phonebook.objects.get(pk=request.POST['phonebook'])
contact_cnt = 0
# Read each Row
for row in rdr:
row = striplist(row)
if not row or str(row[0]) == 0:
continue
# check field type
if not int(row[5]):
error_msg = _("invalid value for import! please check the import samples or phonebook is not valid")
type_error_import_list.append(row)
break
if len(row[9]) > 2:
error_msg = _("invalid value for country code, it needs to be a valid ISO 3166-1 alpha-2 codes (http://en.wikipedia.org/wiki/ISO_3166-1)")
type_error_import_list.append(row)
break
row_11 = ''
if row[11]:
row_11 = json.loads(row[11])
bulk_record.append(
Contact(
phonebook=phonebook,
contact=row[0],
last_name=row[1],
first_name=row[2],
email=row[3],
description=row[4],
status=int(row[5]),
address=row[6],
city=row[7],
state=row[8],
country=row[9],
unit_number=row[10],
additional_vars=row_11)
)
contact_cnt = contact_cnt + 1
if contact_cnt < 100:
success_import_list.append(row)
if contact_cnt % BULK_SIZE == 0:
# Bulk insert
Contact.objects.bulk_create(bulk_record)
bulk_record = []
# remaining record
Contact.objects.bulk_create(bulk_record)
bulk_record = []
# check if there is contact imported
if contact_cnt > 0:
msg = _('%(contact_cnt)s contact(s) have been uploaded successfully out of %(total_rows)s row(s)!')\
% {'contact_cnt': contact_cnt, 'total_rows': total_rows}
ctx = RequestContext(request, {
'form': form,
'opts': opts,
'model_name': opts.object_name.lower(),
'app_label': _('dialer contact'),
'title': _('import contact'),
'rdr': rdr,
'msg': msg,
'error_msg': error_msg,
'success_import_list': success_import_list,
'type_error_import_list': type_error_import_list,
})
return render_to_response('admin/dialer_contact/contact/import_contact.html', context_instance=ctx)
0
Example 158
Project: nodeshot Source File: dashboard.py
def init_with_context(self, context):
site_name = get_admin_site_name(context)
self.children.append(modules.AppList(
_('Nodeshot Core'),
collapsible=True,
column=1,
models=('nodeshot.core.*',),
))
self.children.append(modules.AppList(
_('Nodeshot Networking'),
collapsible=True,
column=1,
models=('nodeshot.networking.*',),
))
self.children.append(modules.AppList(
_('Nodeshot Community'),
collapsible=True,
column=1,
models=('nodeshot.community.*',),
))
self.children.append(modules.AppList(
_('Administration'),
collapsible=True,
column=2,
models=USER_APPS,
))
# append a recent actions module
self.children.append(modules.RecentActions(
_('Recent Actions'),
limit=5,
collapsible=False,
column=2,
))
if 'nodeshot.ui.default' in settings.INSTALLED_APPS:
self.children.append(modules.LinkList(
_('Frontend site'),
column=3,
children=[
{
'title': _('Go to Frontend Site'),
'url': reverse('ui:index'),
'external': False,
},
]
))
if 'smuggler' in settings.INSTALLED_APPS:
self.children.append(modules.LinkList(
_('Backup & Restore data'),
column=3,
children=[
{
'title': _('Backup data as JSON file'),
'url': reverse('dump-data'),
'external': False,
},
{
'title': _('Restore JSON backup'),
'url': reverse('load-data'),
'external': False,
},
]
))
if 'rosetta' in settings.INSTALLED_APPS:
self.children.append(modules.LinkList(
_('Translations'),
column=3,
children=[
{
'title': _('Manage translations'),
'url': reverse('rosetta-home'),
'external': False,
}
]
))
if 'nodeshot.core.api' in settings.INSTALLED_APPS:
self.children.append(modules.LinkList(
_('API'),
column=3,
children=[
{
'title': _('Browsable API'),
'url': reverse('api_root_endpoint'),
'external': False,
},
{
'title': _('Swagger API docs'),
'url': reverse('django.swagger.base.view'),
'external': False,
},
]
))
# append another link list module for "support".
self.children.append(modules.LinkList(
_('Media Management'),
column=3,
children=[
{
'title': _('FileBrowser'),
'url': reverse('filebrowser:fb_browse'),
'external': False,
},
]
))
# append another link list module for "support".
self.children.append(modules.LinkList(
_('Support'),
column=3,
children=[
{
'title': _('Nodeshot Docuementation'),
'url': 'http://nodeshot.rtfd.org/',
'external': True,
},
{
'title': _('Django Docuementation'),
'url': 'http://docs.djangoproject.com/',
'external': True,
},
{
'title': _('Grappelli Docuementation'),
'url': 'http://packages.python.org/django-grappelli/',
'external': True,
},
]
))
0
Example 159
Project: Nitrate Source File: files.py
@user_passes_test(lambda u: u.has_perm('management.add_testattachment'))
def upload_file(request):
if request.FILES.get('upload_file'):
import os
from datetime import datetime
from django.conf import settings
from tcms.core.views import Prompt
from tcms.management.models import TestAttachment
try:
upload_file = request.FILES['upload_file']
try:
upload_file.name.encode('utf8')
except UnicodeEncodeError:
return HttpResponse(Prompt.render(
request=request,
info_type=Prompt.Alert,
info='Upload File name is not legal.',
next='javascript:window.history.go(-1);',
))
now = datetime.now()
stored_name = '%s-%s-%s' % (
request.user.username,
now,
upload_file.name
)
stored_file_name = os.path.join(
settings.FILE_UPLOAD_DIR, stored_name
).replace('\\', '/')
stored_file_name = smart_str(stored_file_name)
if upload_file._size > settings.MAX_UPLOAD_SIZE:
return HttpResponse(Prompt.render(
request=request,
info_type=Prompt.Alert,
info='You upload entity is too large. \
Please ensure the file is less than %s bytes. \
' % settings.MAX_UPLOAD_SIZE,
next='javascript:window.history.go(-1);',
))
# Create the upload directory when it's not exist
try:
os.listdir(settings.FILE_UPLOAD_DIR)
except OSError:
os.mkdir(settings.FILE_UPLOAD_DIR)
# Write to a temporary file
try:
open(stored_file_name, 'ro')
return HttpResponse(Prompt.render(
request=request,
info_type=Prompt.Alert,
info='File named \'%s\' already exist in upload folder, \
please rename to another name for solve conflict.\
' % upload_file.name,
next='javascript:window.history.go(-1);',
))
except IOError:
pass
dest = open(stored_file_name, 'wb+')
for chunk in upload_file.chunks():
dest.write(chunk)
dest.close()
# Write the file to database
# store_file = open(upload_file_name, 'ro')
ta = TestAttachment.objects.create(
submitter_id=request.user.id,
description=request.REQUEST.get('description', None),
file_name=upload_file.name,
stored_name=stored_name,
create_date=now,
mime_type=upload_file.content_type
)
if request.REQUEST.get('to_plan_id'):
from tcms.testplans.models import TestPlanAttachment
try:
int(request.REQUEST['to_plan_id'])
except ValueError:
raise
TestPlanAttachment.objects.create(
plan_id=request.REQUEST.get('to_plan_id'),
attachment_id=ta.attachment_id,
)
return HttpResponseRedirect(
reverse('tcms.testplans.views.attachment',
args=[request.REQUEST['to_plan_id']])
)
elif request.REQUEST.get('to_case_id'):
from tcms.testcases.models import TestCaseAttachment
try:
int(request.REQUEST['to_case_id'])
except ValueError:
raise
TestCaseAttachment.objects.create(
attachment_id=ta.attachment_id,
case_id=request.REQUEST['to_case_id']
)
return HttpResponseRedirect(
reverse('tcms.testcases.views.attachment',
args=[request.REQUEST['to_case_id']])
)
except:
raise
else:
try:
return HttpResponseRedirect(
reverse('tcms.testplans.views.attachment',
args=[request.REQUEST['to_plan_id']])
)
except KeyError:
return HttpResponseRedirect(
reverse('tcms.testcases.views.attachment',
args=[request.REQUEST['to_case_id']])
)
raise NotImplementedError
0
Example 160
Project: Open-Knesset Source File: views.py
@login_required
def update_editors_agendas(request):
if request.method == 'POST':
object_type = request.POST.get('form-0-object_type',None)
object_id = request.POST.get('form-0-obj_id',None)
vl_formset = object_formset_classes[object_type](request.POST)
if vl_formset.is_valid():
for a in vl_formset.cleaned_data:
if a:
# Check that the user is an editor of the agenda
# he's trying to edit
try:
agenda = Agenda.objects.get(pk=a['agenda_id'])
if request.user not in agenda.editors.all():
return HttpResponseForbidden()
except Agenda.DoesNotExist:
return HttpResponseForbidden()
if a['object_type'] == 'vote':
if a['DELETE']:
try:
object_id = a['obj_id']
av = AgendaVote.objects.get(
agenda__id=a['agenda_id'],
vote__id = a['obj_id'])
av.delete()
except AgendaVote.DoesNotExist:
pass
else: # not delete, so try to create
if (a['weight'] is not '' and
a['importance'] is not ''):
try:
object_id = a['obj_id']
av = AgendaVote.objects.get(
agenda__id=a['agenda_id'],
vote__id = a['obj_id'])
av.score = a['weight']
av.importance = a['importance']
av.reasoning = a['reasoning']
av.save()
except AgendaVote.DoesNotExist:
av = AgendaVote(
agenda_id=int(a['agenda_id']),
vote_id=int(a['obj_id']),
score = a['weight'],
importance = a['importance'],
reasoning = a['reasoning'])
av.save()
if a['object_type'] == 'bill':
if a['DELETE']:
try:
object_id = a['obj_id']
av = AgendaBill.objects.get(
agenda__id=a['agenda_id'],
bill__id = a['obj_id'])
av.delete()
except AgendaBill.DoesNotExist:
pass
else: # not delete, so try to create
if (a['weight'] is not '' and
a['importance'] is not ''):
try:
object_id = a['obj_id']
av = AgendaBill.objects.get(
agenda__id=a['agenda_id'],
bill__id = a['obj_id'])
av.score = a['weight']
av.importance = a['importance']
av.reasoning = a['reasoning']
av.save()
except AgendaBill.DoesNotExist:
av = AgendaBill(
agenda_id=int(a['agenda_id']),
bill_id=int(a['obj_id']),
score = a['weight'],
importance = a['importance'],
reasoning = a['reasoning'])
av.save()
if a['object_type'] == 'committeemeeting':
if a['DELETE']:
try:
object_id = a['obj_id']
av = AgendaMeeting.objects.get(
agenda__id=a['agenda_id'],
meeting__id = a['obj_id'])
av.delete()
except AgendaMeeting.DoesNotExist:
pass
else: # not delete, so try to create
try:
object_id = a['obj_id']
av = AgendaMeeting.objects.get(
agenda__id=a['agenda_id'],
meeting__id = a['obj_id'])
av.score = a['weight']
av.reasoning = a['reasoning']
av.save()
except AgendaMeeting.DoesNotExist:
av = AgendaMeeting(
agenda_id=int(a['agenda_id']),
meeting_id=int(a['obj_id']),
score = a['weight'],
reasoning = a['reasoning'])
av.save()
else:
logger.info("invalid form")
else:
# TODO: Error handling: what to do with illeal forms?
logger.info("invalid formset")
logger.info("%s" % vl_formset.errors)
if object_type in object_redirect:
if object_id: # return to object page
return HttpResponseRedirect(
reverse(object_redirect[object_type][0],
kwargs={'pk':object_id}))
else: # return to list
return HttpResponseRedirect(reverse(object_redirect[object_type][1]))
else:
logger.warn('unknown object_type')
return HttpResponseRedirect(reverse('main'))
else:
return HttpResponseNotAllowed(['POST'])
0
Example 161
Project: oh-mainline Source File: views.py
@django_authopenid.views.not_authenticated
def register(request,
template_name='authopenid/complete.html',
redirect_field_name=django.contrib.auth.REDIRECT_FIELD_NAME,
register_form=django_authopenid.forms.OpenidRegisterForm,
auth_form=django.contrib.auth.forms.AuthenticationForm,
register_account=django_authopenid.views.register_account,
send_email=False,
extra_context=None):
"""
register an openid.
If user is already a member he can associate its openid with
its account.
A new account could also be created and automaticaly associated
to the openid.
:attr request: request object
:attr template_name: string, name of template to use,
'authopenid/complete.html' by default
:attr redirect_field_name: string, field name used for redirect. by default
'next'
:attr register_form: form use to create a new account. By default
`OpenidRegisterForm`
:attr auth_form: form object used for legacy authentification.
by default `OpenidVerifyForm` form auser auth contrib.
:attr register_account: callback used to create a new account from openid.
It take the register_form as param.
:attr send_email: boolean, by default True. If True, an email will be sent
to the user.
:attr extra_context: A dictionary of variables to add to the template
context. Any callable object in this dictionary will be called to produce
the end result which appears in the context.
"""
redirect_to = request.REQUEST.get(redirect_field_name, '')
openid_ = request.session.get('openid', None)
if openid_ is None or not openid_:
return HttpResponseRedirect(
"%s?%s" % (reverse('user_signin'),
urllib.urlencode({redirect_field_name: redirect_to}))
)
nickname = ''
email = ''
if openid_.sreg is not None:
nickname = openid_.sreg.get('nickname', '')
email = openid_.sreg.get('email', '')
if openid_.ax is not None and not nickname or not email:
if openid_.ax.get('http://schema.openid.net/namePerson/friendly',
False):
nickname = openid_.ax.get(
'http://schema.openid.net/namePerson/friendly')[0]
if openid_.ax.get('http://schema.openid.net/contact/email', False):
email = openid_.ax.get(
'http://schema.openid.net/contact/email')[0]
form1 = register_form(initial={
'username': nickname,
'email': email,
})
form2 = auth_form(initial={
'username': nickname,
})
if request.POST:
user_ = None
if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
redirect_to = settings.LOGIN_REDIRECT_URL
if 'email' in request.POST.keys():
form1 = register_form(data=request.POST)
if form1.is_valid():
user_ = register_account(form1, openid_)
extra_profile_form = (
mysite.account.forms.SignUpIfYouWantToHelpForm(
request.POST,
prefix='extra_profile_form')
)
if extra_profile_form.is_valid():
person = user_.get_profile()
method2contact_info = {
'forwarder': 'You can reach me by email at $fwd',
'public_email': 'You can reach me by email at %s' % user_.email,
}
info = (
method2contact_info[extra_profile_form.cleaned_data[
'how_should_people_contact_you']]
)
person.contact_blurb = info
person.save()
else:
form2 = auth_form(data=request.POST)
if form2.is_valid():
user_ = form2.get_user()
if user_ is not None:
# associate the user to openid
uassoc = django_authopenid.models.UserAssociation(
openid_url=str(openid_),
user_id=user_.id
)
uassoc.save(send_email=send_email)
django.contrib.auth.login(request, user_)
return HttpResponseRedirect(redirect_to)
return render_response(request, template_name, {
'form1': form1,
'form2': form2,
'extra_profile_form': mysite.account.forms.SignUpIfYouWantToHelpForm(
prefix='extra_profile_form'),
redirect_field_name: redirect_to,
'nickname': nickname,
'email': email
}, context_instance=django_authopenid.views._build_context(
request, extra_context=extra_context))
0
Example 162
Project: oh-mainline Source File: views.py
def search_index(request, invalid_subscribe_to_alert_form=None):
# Make the query string keys lowercase using a redirect.
if any([k.lower() != k for k in request.GET.keys()]):
new_GET = {}
for key in request.GET.keys():
new_GET[key.lower()] = request.GET[key]
return HttpResponseRedirect(reverse(search_index) + '?' + http.urlencode(new_GET))
if request.user.is_authenticated():
person = request.user.get_profile()
suggestion_keys = person.get_recommended_search_terms()
else:
suggestion_keys = []
suggestions = [(i, k, False) for i, k in enumerate(suggestion_keys)]
format = request.GET.get('format', None)
start = int(request.GET.get('start', 1))
end = int(request.GET.get('end', 10))
total_bug_count = 0
query = mysite.search.view_helpers.Query.create_from_GET_data(request.GET)
if query:
bugs = query.get_bugs_unordered()
# Sort
bugs = mysite.search.view_helpers.order_bugs(bugs)
total_bug_count = bugs.count()
bugs = bugs[start - 1:end]
else:
bugs = []
data = {}
data['query'] = query
prev_page_query_str = QueryDict('')
prev_page_query_str = prev_page_query_str.copy()
next_page_query_str = QueryDict('')
next_page_query_str = next_page_query_str.copy()
if query:
prev_page_query_str['q'] = query.terms_string
next_page_query_str['q'] = query.terms_string
if format:
prev_page_query_str['format'] = format
next_page_query_str['format'] = format
for facet_name, selected_option in query.active_facet_options.items():
prev_page_query_str[facet_name] = selected_option
next_page_query_str[facet_name] = selected_option
for facet_name in query.any_facet_options:
prev_page_query_str[facet_name] = ''
next_page_query_str[facet_name] = ''
diff = end - start
prev_page_query_str['start'] = start - diff - 1
prev_page_query_str['end'] = start - 1
next_page_query_str['start'] = end + 1
next_page_query_str['end'] = end + diff + 1
data['start'] = start
data['end'] = min(end, total_bug_count)
data['prev_page_url'] = '/search/?' + prev_page_query_str.urlencode()
data['next_page_url'] = '/search/?' + next_page_query_str.urlencode()
data['this_page_query_str'] = http.urlencode(request.GET)
is_this_page_1 = (start <= 1)
is_this_the_last_page = (end >= (total_bug_count - 1))
data['show_prev_page_link'] = not is_this_page_1
data['show_next_page_link'] = not is_this_the_last_page
if request.GET.get('confirm_email_alert_signup', ''):
data['confirm_email_alert_signup'] = 1
# If this the last page of results, display a form allowing user to
# subscribe to a Volunteer Opportunity search alert
if query and is_this_the_last_page:
if invalid_subscribe_to_alert_form:
alert_form = invalid_subscribe_to_alert_form
else:
initial = {
'query_string': request.META['QUERY_STRING'],
'how_many_bugs_at_time_of_request': len(bugs)
}
if request.user.is_authenticated():
initial['email'] = request.user.email
alert_form = mysite.search.forms.BugAlertSubscriptionForm(
initial=initial)
data['subscribe_to_alert_form'] = alert_form
# FIXME
# The template has no way of grabbing what URLs to put in the [x]
# So we help it out here by hacking around our fruity list-of-dicts
# data structure.
facet2any_query_string = {}
for facet in query.active_facet_options:
facet2any_query_string[facet] = query.get_facet_options(
facet, [''])[0]['query_string']
Bug = mysite.search.models.Bug
from django.db.models import Q, Count
data['popular_projects'] = list(Project.objects.filter(
name__in=['Miro', 'GnuCash', 'brasero', 'Evolution Exchange', 'songbird']).order_by('name').reverse())
data['all_projects'] = Project.objects.values('pk', 'name').filter(
bug__looks_closed=False).annotate(Count('bug')).order_by('name')
Person = mysite.profile.models.Person
import random
random_start = int(random.random() * 700)
data['contributors'] = Person.objects.all()[random_start:random_start + 5]
data['contributors2'] = Person.objects.all(
)[random_start + 10:random_start + 15]
data['languages'] = Project.objects.all().values_list(
'language', flat=True).order_by('language').exclude(language='').distinct()[:4]
if format == 'json':
# FIXME: Why `alert`?
return bugs_to_json_response(data, bugs, request.GET.get(
'jsoncallback', 'alert'))
else:
data['user'] = request.user
data['suggestions'] = suggestions
data['bunch_of_bugs'] = bugs
data['url'] = 'http://launchpad.net/'
data['total_bug_count'] = total_bug_count
data['facet2any_query_string'] = facet2any_query_string
data['project_count'] = mysite.search.view_helpers.get_project_count()
return mysite.base.decorators.as_view(request, 'search/search.html', data, slug=None)
0
Example 163
Project: openode Source File: views.py
@login_required
@csrf.csrf_protect
@decorators.check_spam('text')
def add_docuement_view(request, node, thread_type):
"""
create new docuement (and related Thread)
"""
def _create_doc(user, post, file_data):
docuement = Docuement.objects.create(
author=user,
thread=post.thread
)
parsed_file_name = os.path.splitext(
force_unicode(file_data.name, strings_only=True, errors="ignore")
)
file_name = parsed_file_name[0].lower()
suffix = parsed_file_name[1].replace(".", "").lower()
return docuement.revisions.create(
file_data=file_data,
original_filename=file_name,
suffix=suffix,
filename_slug=sanitize_file_name(file_name),
author=user,
)
def _is_zip_file_extended(name, path):
"""
test if file on path is zip archive,
test for special extension is simple test for exclude zip like files (docx, xlsx, ...)
"""
ZIP_FILES_EXT = ["zip"]
return (name.split(".")[-1].lower() in ZIP_FILES_EXT) and zipfile.is_zipfile(path)
def recursive_process_dir(directory):
"""
recursive read directory content and create Docuements from all files on any level of direcotry tree.
Final structure is flat.
"""
for file_name in os.listdir(directory):
_path = os.path.join(directory, file_name)
if os.path.isdir(_path):
recursive_process_dir(_path)
else:
title = force_unicode(file_name, strings_only=True, errors="ignore")
_post = user.post_thread(**{
"title": "%s: %s" % (form.cleaned_data['title'], title),
"body_text": "",
"timestamp": timestamp,
"node": node,
"thread_type": thread_type,
"category": category,
"external_access": form.cleaned_data["allow_external_access"],
})
with codecs.open(_path, "r", errors="ignore") as file_content:
_create_doc(user, _post, SimpleUploadedFile(title, file_content.read()))
################################################################################
if request.method == 'POST':
form = DocuementForm(request.REQUEST, request.FILES, node=node, user=request.user)
if form.is_valid():
timestamp = datetime.datetime.now()
text = form.cleaned_data['text']
category = form.cleaned_data['thread_category']
if request.user.is_authenticated():
drafts = models.DraftQuestion.objects.filter(
author=request.user
)
drafts.delete()
user = request.user
try:
_data = {
"title": form.cleaned_data['title'],
"body_text": text,
"timestamp": timestamp,
"node": node,
"thread_type": thread_type,
"category": category,
"external_access": form.cleaned_data["allow_external_access"],
}
post = user.post_thread(**_data)
del _data
file_data = form.cleaned_data["file_data"]
if file_data:
# create Docuement from uploaded file
dr = _create_doc(user, post, file_data)
# if uploaded file is zip archive, create docuements from all files in.
if _is_zip_file_extended(dr.file_data.name, dr.file_data.path):
# extract zip to temp directory
temp_dir = tempfile.mkdtemp()
with zipfile.ZipFile(dr.file_data.path, "r") as zf:
zf.extractall(temp_dir)
# recursive process all files in all directories of zip file
# create flat structure from directory tree
recursive_process_dir(temp_dir)
# clear
shutil.rmtree(temp_dir)
request.user.message_set.create(message=_('Docuement has been successfully added.'))
return HttpResponseRedirect(post.thread.get_absolute_url())
except exceptions.PermissionDenied, e:
request.user.message_set.create(message=unicode(e))
return HttpResponseRedirect(reverse('index'))
elif request.method == 'GET':
form = DocuementForm(node=node, user=request.user)
draft_title = ''
draft_text = ''
draft_tagnames = ''
if request.user.is_authenticated():
drafts = models.DraftQuestion.objects.filter(author=request.user)
if len(drafts) > 0:
draft = drafts[0]
draft_title = draft.title
draft_text = draft.text
draft_tagnames = draft.tagnames
form.initial = {
'title': request.REQUEST.get('title', draft_title),
'text': request.REQUEST.get('text', draft_text),
}
# TODO: use Thread.can_retag method
if request.user.has_perm('openode.change_tag'):
form.initial['tags'] = request.REQUEST.get('tags', draft_tagnames)
data = {
'active_tab': 'ask',
'page_class': 'ask-page',
'node': node,
'form': form,
'thread_type': const.THREAD_TYPE_DOCUMENT,
'tag_names': list() # need to keep context in sync with edit_thread for tag editor
}
data.update(context.get_for_tag_editor())
return render_into_skin('node/docuement/add.html', data, request)
0
Example 164
Project: openode Source File: thread.py
@csrf.csrf_protect
#@cache_page(60 * 5)
def thread(request, node_id, node_slug, module, thread_id, thread_slug):
# TODO: refactor - long subroutine. display question body, answers and comments
"""view that displays body of the question and
all answers to it
"""
node = get_object_or_404(Node, pk=node_id)
thread = get_object_or_404(Thread, pk=thread_id, node=node)
# raise not found if module is disabled
if not getattr(node, "module_%s" % const.NODE_MODULE_BY_THREAD_TYPE[thread.thread_type], False):
raise Http404
if not request.user.has_openode_perm('%s_read' % thread.thread_type, thread):
return render_forbidden(request)
if module not in const.THREAD_TYPE_BY_NODE_MODULE or const.THREAD_TYPE_BY_NODE_MODULE[module] != thread.thread_type:
raise Http404()
if module == const.NODE_MODULE_LIBRARY:
return docuement_detail_view(request, node, thread)
if node.slug != node_slug or thread.slug != thread_slug:
return HttpResponseRedirect(reverse('thread', kwargs={
'node_id': node_id,
'node_slug': node.slug,
'module': module,
'thread_id': thread_id,
'thread_slug': thread.slug
}))
# process url parameters
# todo: fix inheritance of sort method from questions
# before = datetime.datetime.now()
default_sort_method = request.session.get('questions_sort_method', thread.get_default_sort_method())
form = ShowQuestionForm(request.GET, default_sort_method)
form.full_clean() # always valid
show_answer = form.cleaned_data['show_answer']
show_comment = form.cleaned_data['show_comment']
show_page = form.cleaned_data['show_page']
answer_sort_method = form.cleaned_data['answer_sort_method']
main_post = thread._main_post()
try:
main_post.assert_is_visible_to(request.user)
except openode_exceptions.QuestionHidden, error:
request.user.message_set.create(message=unicode(error))
return HttpResponseRedirect(reverse('index'))
# redirect if slug in the url is wrong
# if request.path.split('/')[-2] != question_post.slug:
# logging.debug('no slug match!')
# question_url = '?'.join((
# question_post.get_absolute_url(),
# urllib.urlencode(request.GET)
# ))
# return HttpResponseRedirect(question_url)
# resolve comment and answer permalinks
# they go first because in theory both can be moved to another question
# this block "returns" show_post and assigns actual comment and answer
# to show_comment and show_answer variables
# in the case if the permalinked items or their parents are gone - redirect
# redirect also happens if id of the object's origin post != requested id
show_post = None # used for permalinks
if show_comment:
# if url calls for display of a specific comment,
# check that comment exists, that it belongs to
# the current question
# if it is an answer comment and the answer is hidden -
# redirect to the default view of the question
# if the question is hidden - redirect to the main page
# in addition - if url points to a comment and the comment
# is for the answer - we need the answer object
try:
show_comment = models.Post.objects.get_comments().get(id=show_comment)
except models.Post.DoesNotExist:
error_message = _(
'Sorry, the comment you are looking for has been '
'deleted and is no longer accessible'
)
request.user.message_set.create(message=error_message)
return HttpResponseRedirect(thread.get_absolute_url())
if str(show_comment.thread.id) != str(thread_id):
return HttpResponseRedirect(show_comment.get_absolute_url())
show_post = show_comment.parent
try:
show_comment.assert_is_visible_to(request.user)
except openode_exceptions.AnswerHidden, error:
request.user.message_set.create(message=unicode(error))
#use reverse function here because question is not yet loaded
return HttpResponseRedirect(thread.get_absolute_url())
except openode_exceptions.QuestionHidden, error:
request.user.message_set.create(message=unicode(error))
return HttpResponseRedirect(reverse('index'))
elif show_answer:
# if the url calls to view a particular answer to
# question - we must check whether the question exists
# whether answer is actually corresponding to the current question
# and that the visitor is allowed to see it
show_post = get_object_or_404(models.Post, post_type='answer', id=show_answer)
if str(show_post.thread.id) != str(thread_id):
return HttpResponseRedirect(show_post.get_absolute_url())
try:
show_post.assert_is_visible_to(request.user)
except django_exceptions.PermissionDenied, error:
request.user.message_set.create(message=unicode(error))
return HttpResponseRedirect(thread.get_absolute_url())
# logging.debug('answer_sort_method=' + unicode(answer_sort_method))
# load answers and post id's->athor_id mapping
# posts are pre-stuffed with the correctly ordered comments
# authors = request.GET.get("authors", "")
from openode.utils.text import extract_numbers
authors_ids = extract_numbers(request.GET.get("authors", ""))
authors = []
qs = None
if authors_ids:
authors = User.objects.filter(
pk__in=authors_ids,
is_active=True,
is_hidden=False
)
qs = thread.posts.filter(
author__in=authors,
deleted=False
)
# Question flow: show only published answers
if node.is_question_flow_enabled and (request.user not in thread.node.get_responsible_persons()):
qs = qs or thread.posts.all()
qs = qs.filter(pk=thread.accepted_answer_id
# question_flow_is_published=True
# | Q(thread__question_flow_responsible_user=request.user)
# | Q(thread__question_flow_interviewee_user=request.user)
)
updated_main_post, answers, post_to_author = thread.get_cached_post_data(
sort_method=answer_sort_method,
user=request.user,
qs=qs
)
if updated_main_post:
main_post.set_cached_comments(
updated_main_post.get_cached_comments()
)
# Post.objects.precache_comments(for_posts=[question_post] + answers, visitor=request.user)
user_votes = {}
user_post_id_list = list()
# TODO: cache this query set, but again takes only 3ms!
if request.user.is_authenticated():
user_votes = Vote.objects.filter(
user=request.user,
voted_post__id__in=post_to_author.keys()
).values_list(
'voted_post_id',
'vote'
)
user_votes = dict(user_votes)
# we can avoid making this query by iterating through
# already loaded posts
user_post_id_list = [
post_id for post_id in post_to_author if post_to_author[post_id] == request.user.id
]
# resolve page number and comment number for permalinks
show_comment_position = None
if show_comment:
show_page = show_comment.get_page_number(answer_posts=answers)
show_comment_position = show_comment.get_order_number()
elif show_answer:
show_page = show_post.get_page_number(answer_posts=answers)
###################################
# paginator
###################################
if thread.is_question():
per_page = maxint
else:
per_page = const.ANSWERS_PAGE_SIZE
# define posts position on paginator pages
posts_per_pages = {}
for i, post in enumerate(answers):
posts_per_pages[post.pk] = 1 + (i // per_page)
objects_list = Paginator(answers, per_page)
if show_page > objects_list.num_pages:
return HttpResponseRedirect(main_post.get_absolute_url())
page_objects = objects_list.page(show_page)
count_visit(request, thread, main_post)
base_url = request.path + '?sort=%s&' % answer_sort_method
if authors:
base_url = "%sauthors=%s&" % (
base_url,
",".join([str(pk) for pk in authors.values_list("pk", flat=True)])
)
paginator_data = {
'is_paginated': (objects_list.count > per_page),
'pages': objects_list.num_pages,
'page': show_page,
'has_previous': page_objects.has_previous(),
'has_next': page_objects.has_next(),
'previous': page_objects.previous_page_number(),
'next': page_objects.next_page_number(),
'base_url': base_url,
}
paginator_context = functions.setup_paginator(paginator_data)
###################################
initial = {
'email_notify': thread.is_subscribed_by(request.user)
}
# maybe load draft
if request.user.is_authenticated():
# todo: refactor into methor on thread
drafts = models.DraftAnswer.objects.filter(
author=request.user,
thread=thread
)
if drafts.count() > 0:
initial['text'] = drafts[0].text
# answer form
if request.method == "POST":
if not thread.has_response_perm(request.user):
return render_forbidden(request)
answer_form = AnswerForm(request.POST, node=node)
if answer_form.is_valid():
text = answer_form.cleaned_data['text']
update_time = datetime.datetime.now()
if request.user.is_authenticated():
drafts = models.DraftAnswer.objects.filter(
author=request.user,
thread=thread
)
drafts.delete()
try:
follow = answer_form.cleaned_data['email_notify']
user = request.user
if thread.node.is_question_flow_enabled:
question_flow_state_original = thread.question_flow_state
answer = user.post_answer(
question=main_post,
body_text=text,
follow=follow,
timestamp=update_time,
)
if thread.node.is_question_flow_enabled:
if (answer.thread.question_flow_state == const.QUESTION_FLOW_STATE_ANSWERED) \
and (question_flow_state_original != const.QUESTION_FLOW_STATE_ANSWERED):
request.user.message_set.create(
message=_(u"Your answer was sent to the club manager and will be published after approval.")
)
return HttpResponseRedirect(answer.get_absolute_url())
except openode_exceptions.AnswerAlreadyGiven, e:
request.user.message_set.create(message=unicode(e))
answer = thread.get_answers_by_user(request.user)[0]
return HttpResponseRedirect(answer.get_absolute_url())
except django_exceptions.PermissionDenied, e:
request.user.message_set.create(message=unicode(e))
else:
request.session.flush()
models.AnonymousAnswer.objects.create(
question=main_post,
text=text,
summary=strip_tags(text)[:120],
session_key=request.session.session_key,
ip_addr=request.META['REMOTE_ADDR'],
)
return HttpResponseRedirect(url_utils.get_login_url())
else:
answer_form = AnswerForm(initial=initial, node=node)
user_can_post_comment = (
request.user.is_authenticated() and request.user.can_post_comment()
)
user_already_gave_answer = False
previous_answer = None
if request.user.is_authenticated():
if openode_settings.LIMIT_ONE_ANSWER_PER_USER and module == const.NODE_MODULE_QA:
for answer in answers:
if answer.author == request.user:
user_already_gave_answer = True
previous_answer = answer
break
from openode.views.readers import SearchUserForm
search_user_form = SearchUserForm()
# authors
context = {
"search_user_form": search_user_form,
"authors": authors,
'is_cacheable': False, # is_cacheable, #temporary, until invalidation fix
'long_time': const.LONG_TIME, # "forever" caching
'page_class': 'question-page',
'active_tab': 'questions',
'main_post': main_post,
'thread': thread,
'answer_form': answer_form,
'answers': page_objects.object_list,
'answer_count': thread.get_answer_count(request.user),
'user_votes': user_votes,
'user_post_id_list': user_post_id_list,
'user_can_post_comment': user_can_post_comment, # in general
'user_already_gave_answer': user_already_gave_answer,
'previous_answer': previous_answer,
'tab_id': answer_sort_method,
'similar_threads': thread.get_similar_threads(),
'language_code': translation.get_language(),
'paginator_context': paginator_context,
'show_post': show_post,
'show_comment': show_comment,
'show_comment_position': show_comment_position,
'enable_comments': module == const.NODE_MODULE_QA,
'thread': thread,
'module': module,
"posts_per_pages": posts_per_pages,
}
# show last visit for posts (comments, ...)
try:
thread_view = thread.viewed.get(user=request.user)
thread_view_last_visit = thread_view.last_visit
except (ObjectDoesNotExist, TypeError):
# print 8*'-', 'EXCEPT'
thread_view = None
thread_view_last_visit = datetime.datetime.now()
# print thread_view_last_visit
# thread_view_last_visit = datetime.datetime(2000,1,1,15,00)
context.update({
"thread_view": thread_view,
"thread_view_last_visit": thread_view_last_visit
})
context.update(views_context.get_for_tag_editor())
thread.visit(request.user)
# future functions
template = 'node/%s/detail.html' % thread.thread_type
return render_into_skin(template, context, request)
0
Example 165
Project: openode Source File: users.py
def user_overview(request, user, context):
question_filter = {}
#
# Questions
#
questions = user.posts.get_questions(
user=request.user
).filter(
**question_filter
).order_by(
'-points', '-thread__last_activity_at'
).select_related(
'thread', 'thread__last_activity_by'
)[:100]
#added this if to avoid another query if questions is less than 100
if len(questions) < 100:
question_count = len(questions)
else:
question_count = user.posts.get_questions().filter(**question_filter).count()
#
# Top answers
#
top_answers = user.posts.get_answers(
request.user
).filter(
deleted=False,
thread__posts__deleted=False,
thread__posts__post_type='question',
).select_related(
'thread'
).order_by(
'-points', '-added_at'
)[:100]
top_answer_count = len(top_answers)
#
# Votes
#
up_votes = models.Vote.objects.get_up_vote_count_from_user(user)
down_votes = models.Vote.objects.get_down_vote_count_from_user(user)
votes_today = models.Vote.objects.get_votes_count_today_from_user(user)
votes_total = openode_settings.MAX_VOTES_PER_USER_PER_DAY
#
# Tags
#
# INFO: There's bug in Django that makes the following query kind of broken (GROUP BY clause is problematic):
# http://stackoverflow.com/questions/7973461/django-aggregation-does-excessive-organization-by-clauses
# Fortunately it looks like it returns correct results for the test data
user_tags = models.Tag.objects.filter(
threads__posts__author=user
).distinct().annotate(
user_tag_usage_count=Count('threads')
).order_by(
'-user_tag_usage_count'
)[:const.USER_VIEW_DATA_SIZE]
user_tags = list(user_tags) # evaluate
when = openode_settings.MARKED_TAGS_ARE_PUBLIC_WHEN
if when == 'always' or \
(when == 'when-user-wants' and user.show_marked_tags == True):
#refactor into: user.get_marked_tag_names('good'/'bad'/'subscribed')
interesting_tag_names = user.get_marked_tag_names('good')
ignored_tag_names = user.get_marked_tag_names('bad')
subscribed_tag_names = user.get_marked_tag_names('subscribed')
else:
interesting_tag_names = None
ignored_tag_names = None
subscribed_tag_names = None
# tags = models.Post.objects.filter(author=user).values('id', 'thread', 'thread__tags')
# post_ids = set()
# thread_ids = set()
# tag_ids = set()
# for t in tags:
# post_ids.add(t['id'])
# thread_ids.add(t['thread'])
# tag_ids.add(t['thread__tags'])
# if t['thread__tags'] == 11:
# print t['thread'], t['id']
# import ipdb; ipdb.set_trace()
#
#
# post_type = ContentType.objects.get_for_model(models.Post)
if request.user != user and request.user.is_authenticated() and user.privacy_email_form:
if request.method == 'POST':
email_form = UserEmailForm(request.POST)
if email_form.is_valid():
subject = email_form.cleaned_data['subject']
text = email_form.cleaned_data['text']
url = urlparse(openode_settings.APP_URL)
data = {
'from_user_url': url.scheme + '://' + url.netloc + reverse('user_profile', args=[request.user.pk]),
'from_user_screen_name': request.user.screen_name,
'text': text,
"request": request
}
template = get_template('email/user_profile_email.html')
message = template.render(data)
send_mail(subject_line=subject,
body_text=message,
from_email=django_settings.DEFAULT_FROM_EMAIL,
recipient_list=[user.email],
)
request.user.log(user, const.LOG_ACTION_SEND_EMAIL_TO_USER)
request.user.message_set.create(message=_('Email has been succesfully sent.'))
email_form = UserEmailForm()
else:
email_form = UserEmailForm()
else:
email_form = None
# if request.user.is_authenticated():
# managed_nodes = user.nodes.filter(node_users__role=const.NODE_USER_ROLE_MANAGER)
# else:
# managed_nodes = None
# TODO not all variables are necessary
data = {
'active_tab': 'users',
'page_class': 'user-profile-page',
'support_custom_avatars': ('avatar' in django_settings.INSTALLED_APPS),
'tab_description': _('user profile'),
'page_title': _('user profile overview'),
'user_status_for_display': user.get_status_display(soft=True),
'questions': questions,
'question_count': question_count,
'top_answers': top_answers,
'top_answer_count': top_answer_count,
'up_votes': up_votes,
'down_votes': down_votes,
'total_votes': up_votes + down_votes,
'votes_today_left': votes_total - votes_today,
'votes_total_per_day': votes_total,
# 'managed_nodes': managed_nodes,
'user_tags': user_tags,
'interesting_tag_names': interesting_tag_names,
'ignored_tag_names': ignored_tag_names,
'subscribed_tag_names': subscribed_tag_names,
'email_form': email_form
}
context.update(data)
view_user = context.get('view_user')
if view_user is not None and not view_user.is_active:
return render_into_skin('user_profile/user_overview_disabled.html', context, request)
return render_into_skin('user_profile/user_overview.html', context, request)
0
Example 166
@sensitive_variables('context')
def handle(self, request, context):
custom_script = context.get('script_data', '')
dev_mapping_1 = None
dev_mapping_2 = None
image_id = ''
# Determine volume mapping options
source_type = context.get('source_type', None)
if source_type in ['image_id', 'instance_snapshot_id']:
image_id = context['source_id']
elif source_type in ['volume_id', 'volume_snapshot_id']:
try:
if api.nova.extension_supported("BlockDeviceMappingV2Boot",
request):
# Volume source id is extracted from the source
volume_source_id = context['source_id'].split(':')[0]
device_name = context.get('device_name', '') \
.strip() or None
dev_source_type_mapping = {
'volume_id': 'volume',
'volume_snapshot_id': 'snapshot'
}
dev_mapping_2 = [
{'device_name': device_name,
'source_type': dev_source_type_mapping[source_type],
'destination_type': 'volume',
'delete_on_termination':
int(bool(context['delete_on_terminate'])),
'uuid': volume_source_id,
'boot_index': '0',
'volume_size': context['volume_size']
}
]
else:
dev_mapping_1 = {context['device_name']: '%s::%s' %
(context['source_id'],
int(bool(context['delete_on_terminate'])))
}
except Exception:
msg = _('Unable to retrieve extensions information')
exceptions.handle(request, msg)
elif source_type == 'volume_image_id':
device_name = context.get('device_name', '').strip() or None
dev_mapping_2 = [
{'device_name': device_name, # None auto-selects device
'source_type': 'image',
'destination_type': 'volume',
'delete_on_termination':
int(bool(context['delete_on_terminate'])),
'uuid': context['source_id'],
'boot_index': '0',
'volume_size': context['volume_size']
}
]
avail_zone = context.get('availability_zone', None)
try:
instance_count = int(context['count'])
count = 1
while count <= instance_count:
if instance_count == 1:
instance_name = context['name']
else:
instance_name = context['name'] + str(count)
nics = []
for ptg_id in context['group_id']:
values = ptg_id.split(":")
ptg_id = values[0]
args = {'policy_target_group_id': ptg_id,
'name': instance_name[:41] + "_gbpui"}
if len(values) == 3:
ptg = client.policy_target_get(request, ptg_id)
fixed_ip = values[2]
for subnet_id in ptg.subnets:
try:
subnet = api.neutron.subnet_get(
request, subnet_id)
except Exception:
continue
if IPAddress(fixed_ip) in \
IPNetwork(subnet['cidr']):
args['fixed_ips'] = [
{'subnet_id': subnet['id'],
'ip_address': fixed_ip}]
break
ep = client.pt_create(request, **args)
nics.append({'port-id': ep.port_id})
api.nova.server_create(request,
instance_name,
image_id,
context['flavor'],
context['keypair_id'],
normalize_newlines(custom_script),
security_groups=None,
block_device_mapping=dev_mapping_1,
block_device_mapping_v2=dev_mapping_2,
nics=nics,
availability_zone=avail_zone,
instance_count=1,
admin_pass=context['admin_pass'],
disk_config=context.get('disk_config'),
config_drive=context.get('config_drive'))
count += 1
return True
except Exception as e:
error = _("Unable to launch member %(count)s with name %(name)s")
msg = error % {'count': count, 'name': instance_name}
LOG.error(str(e))
u = "horizon:project:policytargets:policy_targetdetails"
policy_target_id = self.request.path.split("/")[-2]
redirect = reverse(u, kwargs={'policy_target_id':
policy_target_id})
exceptions.handle(request, msg, redirect=redirect)
return False
0
Example 167
Project: horizon Source File: tests.py
@test.create_stubs({api.heat: ('stack_create', 'template_validate')})
def test_launch_stack_parameter_types(self):
template = {
'data': ('heat_template_version: 2013-05-23\n'
'parameters:\n'
' param1:\n'
' type: string\n'
' param2:\n'
' type: number\n'
' param3:\n'
' type: json\n'
' param4:\n'
' type: comma_delimited_list\n'
' param5:\n'
' type: boolean\n'),
'validate': {
"Description": "No description",
"Parameters": {
"param1": {
"Type": "String",
"NoEcho": "false",
"Description": "",
"Label": "param1"
},
"param2": {
"Type": "Number",
"NoEcho": "false",
"Description": "",
"Label": "param2"
},
"param3": {
"Type": "Json",
"NoEcho": "false",
"Description": "",
"Label": "param3"
},
"param4": {
"Type": "CommaDelimitedList",
"NoEcho": "false",
"Description": "",
"Label": "param4"
},
"param5": {
"Type": "Boolean",
"NoEcho": "false",
"Description": "",
"Label": "param5"
}
}
}
}
stack = self.stacks.first()
api.heat.template_validate(IsA(http.HttpRequest),
files={},
template=hc_format.parse(template['data'])) \
.AndReturn(template['validate'])
api.heat.stack_create(IsA(http.HttpRequest),
stack_name=stack.stack_name,
timeout_mins=60,
disable_rollback=True,
template=hc_format.parse(template['data']),
parameters={'param1': 'some string',
'param2': 42,
'param3': '{"key": "value"}',
'param4': 'a,b,c',
'param5': True},
password='password',
files={})
self.mox.ReplayAll()
url = reverse('horizon:project:stacks:select_template')
res = self.client.get(url)
self.assertTemplateUsed(res, 'project/stacks/select_template.html')
form_data = {'template_source': 'raw',
'template_data': template['data'],
'method': forms.TemplateForm.__name__}
res = self.client.post(url, form_data)
self.assertTemplateUsed(res, 'project/stacks/create.html')
# ensure the fields were rendered correctly
if django.VERSION >= (1, 10):
input_str = ('<input class="form-control" '
'id="id___param_param{0}" '
'name="__param_param{0}" type="{1}" required/>')
else:
input_str = ('<input class="form-control" '
'id="id___param_param{0}" '
'name="__param_param{0}" type="{1}"/>')
self.assertContains(res, input_str.format(1, 'text'), html=True)
self.assertContains(res, input_str.format(2, 'number'), html=True)
self.assertContains(res, input_str.format(3, 'text'), html=True)
self.assertContains(res, input_str.format(4, 'text'), html=True)
self.assertContains(
res,
'<input id="id___param_param5" name="__param_param5" '
'type="checkbox">',
html=True)
# post some sample data and make sure it validates
url = reverse('horizon:project:stacks:launch')
form_data = {'template_source': 'raw',
'template_data': template['data'],
'password': 'password',
'parameters': json.dumps(template['validate']),
'stack_name': stack.stack_name,
"timeout_mins": 60,
"disable_rollback": True,
"__param_param1": "some string",
"__param_param2": 42,
"__param_param3": '{"key": "value"}',
"__param_param4": "a,b,c",
"__param_param5": True,
'method': forms.CreateStackForm.__name__}
res = self.client.post(url, form_data)
self.assertRedirectsNoFollow(res, INDEX_URL)
0
Example 168
Project: murano-dashboard Source File: views.py
def process_step(self, form):
@catalog_views.update_latest_apps
def _update_latest_apps(request, app_id):
LOG.info('Adding {0} application to the'
' latest apps list'.format(app_id))
step_data = self.get_form_step_data(form)
if self.steps.current == 'upload':
import_type = form.cleaned_data['import_type']
data = {}
f = None
base_url = packages_consts.MURANO_REPO_URL
if import_type == 'upload':
pkg = form.cleaned_data['package']
f = pkg.file
elif import_type == 'by_url':
f = form.cleaned_data['url']
elif import_type == 'by_name':
name = form.cleaned_data['repo_name']
version = form.cleaned_data['repo_version']
f = muranoclient_utils.to_url(
name, version=version,
path='apps/',
extension='.zip',
base_url=base_url,
)
try:
package = muranoclient_utils.Package.from_file(f)
name = package.manifest['FullName']
except Exception as e:
if '(404)' in e.message:
msg = _("Package creation failed."
"Reason: Can't find Package name from repository.")
else:
msg = _("Package creation failed."
"Reason: {0}").format(e)
LOG.exception(msg)
messages.error(self.request, msg)
raise exceptions.Http302(
reverse('horizon:app-catalog:packages:index'))
reqs = package.requirements(base_url=base_url)
original_package = reqs.pop(name)
step_data['dependencies'] = []
step_data['images'] = []
for dep_name, dep_package in six.iteritems(reqs):
_ensure_images(dep_name, dep_package, self.request, step_data)
try:
files = {dep_name: dep_package.file()}
package = api.muranoclient(self.request).packages.create(
data, files)
messages.success(
self.request,
_('Package {0} uploaded').format(dep_name)
)
_update_latest_apps(
request=self.request, app_id=package.id)
step_data['dependencies'].append(package)
except exc.HTTPConflict:
msg = _("Package {0} already registered.").format(
dep_name)
messages.warning(self.request, msg)
LOG.exception(msg)
except Exception as e:
msg = _("Error {0} occurred while "
"installing package {1}").format(e, dep_name)
messages.error(self.request, msg)
LOG.exception(msg)
continue
# add main packages images
_ensure_images(name, original_package, self.request, step_data)
# import main package itself
try:
files = {name: original_package.file()}
package = api.muranoclient(self.request).packages.create(
data, files)
messages.success(self.request,
_('Package {0} uploaded').format(name))
_update_latest_apps(request=self.request, app_id=package.id)
step_data['package'] = package
except exc.HTTPConflict:
msg = _("Package with specified name already exists")
LOG.exception(msg)
exceptions.handle(
self.request,
msg,
redirect=reverse('horizon:app-catalog:packages:index'))
except exc.HTTPInternalServerError as e:
self._handle_exception(e)
except exc.HTTPException as e:
reason = muranodashboard_utils.parse_api_error(
getattr(e, 'details', ''))
if not reason:
raise
LOG.exception(reason)
exceptions.handle(
self.request,
reason,
redirect=reverse('horizon:app-catalog:packages:index'))
except Exception as original_e:
self._handle_exception(original_e)
return step_data
0
Example 169
Project: sahara-dashboard Source File: tests.py
@test.create_stubs({api.sahara: ('client',
'nodegroup_template_create',
'nodegroup_template_update',
'nodegroup_template_get',
'plugin_get_version_details'),
dash_api.network: ('floating_ip_pools_list',
'security_group_list'),
dash_api.nova: ('flavor_list',
'availability_zone_list'),
dash_api.cinder: ('extension_supported',
'availability_zone_list',
'volume_type_list')})
@mock.patch('openstack_dashboard.api.base.is_service_enabled')
def test_update(self, service_checker):
service_checker.return_value = True
flavor = self.flavors.first()
ngt = self.nodegroup_templates.first()
configs = self.plugins_configs.first()
new_name = ngt.name + '-updated'
UPDATE_URL = reverse(
'horizon:project:data_processing.clusters:edit',
kwargs={'template_id': ngt.id})
self.mox.StubOutWithMock(
workflow_helpers, 'parse_configs_from_context')
dash_api.cinder.extension_supported(IsA(http.HttpRequest),
'AvailabilityZones') \
.AndReturn(True)
dash_api.cinder.availability_zone_list(IsA(http.HttpRequest)) \
.AndReturn(self.availability_zones.list())
dash_api.cinder.volume_type_list(IsA(http.HttpRequest))\
.AndReturn([])
dash_api.nova.flavor_list(IsA(http.HttpRequest)).AndReturn([flavor])
api.sahara.plugin_get_version_details(IsA(http.HttpRequest),
ngt.plugin_name,
ngt.hadoop_version) \
.MultipleTimes().AndReturn(configs)
dash_api.network.floating_ip_pools_list(IsA(http.HttpRequest)) \
.AndReturn([])
dash_api.network.security_group_list(IsA(http.HttpRequest)) \
.AndReturn([])
workflow_helpers.parse_configs_from_context(
IgnoreArg(), IgnoreArg()).AndReturn({})
api.sahara.nodegroup_template_get(IsA(http.HttpRequest),
ngt.id) \
.AndReturn(ngt)
api.sahara.nodegroup_template_update(
request=IsA(http.HttpRequest),
ngt_id=ngt.id,
name=new_name,
plugin_name=ngt.plugin_name,
hadoop_version=ngt.hadoop_version,
flavor_id=flavor.id,
description=ngt.description,
volumes_per_node=0,
volumes_size=None,
volume_type=None,
volume_local_to_instance=False,
volumes_availability_zone=None,
node_processes=['namenode'],
node_configs={},
floating_ip_pool=None,
security_groups=[],
auto_security_group=True,
availability_zone=None,
use_autoconfig=True,
is_proxy_gateway=False,
shares=[],
is_protected=False,
is_public=False,
image_id=ngt.image_id).AndReturn(True)
self.mox.ReplayAll()
res = self.client.post(
UPDATE_URL,
{'ng_id': ngt.id,
'nodegroup_name': new_name,
'plugin_name': ngt.plugin_name,
ngt.plugin_name + '_version': '1.2.1',
'hadoop_version': ngt.hadoop_version,
'description': ngt.description,
'flavor': flavor.id,
'availability_zone': None,
'storage': 'ephemeral_drive',
'volumes_per_node': 0,
'volumes_size': 0,
'volume_type': None,
'volume_local_to_instance': False,
'volumes_availability_zone': None,
'floating_ip_pool': None,
'is_proxy_gateway': False,
'security_autogroup': True,
'processes': 'HDFS:namenode',
'use_autoconfig': True})
self.assertNoFormErrors(res)
self.assertRedirectsNoFollow(res, INDEX_URL)
self.assertMessageCount(success=1)
0
Example 170
Project: billy Source File: __init__.py
@is_superuser
def newsblogs(request):
'''
Demo view for news/blog aggregation.
'''
# Pagination insanity.
total_count = db.feed_entries.count()
limit = int(request.GET.get('limit', 6))
page = int(request.GET.get('page', 1))
if page < 1:
page = 1
skip = limit * (page - 1)
# Whether display is limited to entries tagged with legislator
# committee or bill object.
entities = request.GET.get('entities', True)
tab_range = range(1, int(float(total_count) / limit) + 1)
tab = skip / limit + 1
try:
tab_index = tab_range.index(tab)
except ValueError:
tab_index = 1
tab_range_len = len(tab_range)
pagination_truncated = False
if tab_range_len > 8:
i = tab_index - 4
if i < 0:
i = 1
j = tab_index
k = j + 5
previous = tab_range[i: j]
next_ = tab_range[j + 1: k]
pagination_truncated = True
elif tab_range_len == 8:
previous = tab_range[:4]
next_ = tab_range[4:]
else:
div, mod = divmod(tab_range_len, 2)
if mod == 2:
i = tab_range_len / 2
else:
i = (tab_range_len - 1) / 2
previous = tab_range[:i]
next_ = tab_range[i:]
# Get the data.
abbr = request.GET.get('abbr')
if entities is True:
spec = {'entity_ids': {'$ne': None}}
else:
spec = {}
if abbr:
spec.update(abbr=abbr)
entries = db.feed_entries.find(spec, skip=skip, limit=limit,
sort=[('published_parsed',
pymongo.DESCENDING)])
_entries = []
entity_types = {'L': 'legislators',
'C': 'committees',
'B': 'bills'}
for entry in entries:
summary = entry['summary']
entity_strings = entry['entity_strings']
entity_ids = entry['entity_ids']
_entity_strings = []
_entity_ids = []
_entity_urls = []
_done = []
if entity_strings:
for entity_string, _id in zip(entity_strings, entity_ids):
if entity_string in _done:
continue
else:
_done.append(entity_string)
_entity_strings.append(entity_string)
_entity_ids.append(_id)
entity_type = entity_types[_id[2]]
url = urlresolvers.reverse('object_json',
args=[entity_type, _id])
_entity_urls.append(url)
summary = summary.replace(entity_string,
'<b><a href="%s">%s</a></b>' % (
url, entity_string))
entity_data = zip(_entity_strings, _entity_ids, _entity_urls)
entry['summary'] = summary
entry['entity_data'] = entity_data
entry['id'] = entry['_id']
entry['host'] = urlparse.urlparse(entry['link']).netloc
# Now hyperlink the inbox data.
# if '_inbox_data' in entry:
# inbox_data = entry['_inbox_data']
# for entity in inbox_data['entities']:
# entity_data = entity['entity_data']
# if entity_data['type'] == 'organization':
# ie_url = 'http://influenceexplorer.com/organization/%s/%s'
# ie_url = ie_url % (entity_data['slug'], entity_data['id'])
# else:
# continue
# summary = entry['summary']
# tmpl = '<a href="%s">%s</a>'
# for string in entity['matched_text']:
# summary = summary.replace(string, tmpl % (ie_url, string))
# entry['summary'] = summary
_entries.append(entry)
return render(request, 'billy/newsblogs.html', {
'entries': _entries,
'entry_count': entries.count(),
'abbrs': db.feed_entries.distinct('abbr'),
'abbr': abbr,
'tab_range': tab_range,
'previous': previous,
'next_': next_,
'pagination_truncated': pagination_truncated,
'page': page,
})
0
Example 171
Project: otm-legacy Source File: views.py
def create_profile(request, form_class=None, success_url=None,
template_name='profiles/create_profile.html',
extra_context=None):
"""
Create a profile for the current user, if one doesn't already
exist.
If the user already has a profile, as determined by
``request.user.get_profile()``, a redirect will be issued to the
:view:`profiles.views.edit_profile` view. If no profile model has
been specified in the ``AUTH_PROFILE_MODULE`` setting,
``django.contrib.auth.models.SiteProfileNotAvailable`` will be
raised.
**Optional arguments:**
``extra_context``
A dictionary of variables to add to the template context. Any
callable object in this dictionary will be called to produce
the end result which appears in the context.
``form_class``
The form class to use for validating and creating the user
profile. This form class must define a method named
``save()``, implementing the same argument signature as the
``save()`` method of a standard Django ``ModelForm`` (this
view will call ``save(commit=False)`` to obtain the profile
object, and fill in the user before the final save). If the
profile object includes many-to-many relations, the convention
established by ``ModelForm`` of using a method named
``save_m2m()`` will be used, and so your form class should
also define this method.
If this argument is not supplied, this view will use a
``ModelForm`` automatically generated from the model specified
by ``AUTH_PROFILE_MODULE``.
``success_url``
The URL to redirect to after successful profile creation. If
this argument is not supplied, this will default to the URL of
:view:`profiles.views.profile_detail` for the newly-created
profile object.
``template_name``
The template to use when displaying the profile-creation
form. If not supplied, this will default to
:template:`profiles/create_profile.html`.
**Context:**
``form``
The profile-creation form.
**Template:**
``template_name`` keyword argument, or
:template:`profiles/create_profile.html`.
"""
try:
profile_obj = request.user.get_profile()
return HttpResponseRedirect(reverse('profiles_edit_profile'))
except ObjectDoesNotExist:
pass
#
# We set up success_url here, rather than as the default value for
# the argument. Trying to do it as the argument's default would
# mean evaluating the call to reverse() at the time this module is
# first imported, which introduces a circular dependency: to
# perform the reverse lookup we need access to profiles/urls.py,
# but profiles/urls.py in turn imports this module.
#
if success_url is None:
success_url = reverse('profiles_profile_detail',
kwargs={ 'username': request.user.username })
if form_class is None:
form_class = utils.get_profile_form()
if request.method == 'POST':
form = form_class(data=request.POST, files=request.FILES)
if form.is_valid():
profile_obj = form.save(commit=False)
profile_obj.user = request.user
profile_obj.save()
if hasattr(form, 'save_m2m'):
form.save_m2m()
return HttpResponseRedirect(success_url)
else:
form = form_class()
if extra_context is None:
extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
context[key] = callable(value) and value() or value
return render_to_response(template_name,
{ 'form': form },
context_instance=context)
0
Example 172
Project: ganeti_webmgr Source File: views.py
@login_required
def modify_confirm(request, cluster_slug, instance):
vm, cluster = get_vm_and_cluster_or_404(cluster_slug, instance)
hv = get_hypervisor(vm)
if hv == 'kvm':
hv_form = KvmModifyVirtualMachineForm
elif hv == 'xen-pvm':
hv_form = PvmModifyVirtualMachineForm
elif hv == 'xen-hvm':
hv_form = HvmModifyVirtualMachineForm
else:
hv_form = None
# XXX no matter what, we're gonna call hv_form() and die. Let's do it
# louder than usual. >:3
msg = "Hey, guys, implementation error in views/vm.py:modify_confirm"
raise RuntimeError(msg)
user = request.user
power = user.is_superuser or user.has_any_perms(vm, ['admin', 'power'])
if not (user.is_superuser or user.has_any_perms(vm, ['admin', 'modify'])
or user.has_perm('admin', cluster)):
raise PermissionDenied(
_('You do not have permissions to edit this virtual machine'))
if request.method == "POST":
if 'edit' in request.POST:
return HttpResponseRedirect(
reverse("instance-modify",
args=[cluster.slug, vm.hostname]))
elif 'reboot' in request.POST or 'save' in request.POST:
form = ModifyConfirmForm(request.POST)
form.session = request.session
form.owner = vm.owner
form.vm = vm
form.cluster = cluster
if form.is_valid():
beparams = {}
data = form.cleaned_data
rapi_dict = data['rapi_dict']
nics = rapi_dict.pop('nics')
beparams['vcpus'] = rapi_dict.pop('vcpus')
if has_balloonmem(cluster):
beparams['maxmem'] = rapi_dict.pop('maxmem')
beparams['minmem'] = rapi_dict.pop('minmem')
else:
beparams['memory'] = rapi_dict.pop('memory')
os_name = rapi_dict.pop('os')
notes = rapi_dict.pop('notes')
job_id = cluster.rapi.ModifyInstance(
instance,
nics=nics,
os_name=os_name,
hvparams=rapi_dict,
beparams=beparams)
# Create job and update message on virtual machine detail page
job = Job.objects.create(job_id=job_id,
obj=vm,
cluster=cluster)
VirtualMachine.objects \
.filter(id=vm.id).update(last_job=job, ignore_cache=True,
note_text=notes)
# log information about modifying this instance
log_action('EDIT', user, vm)
if 'reboot' in request.POST and vm.info['status'] == 'running':
if power:
# Reboot the vm
job = vm.reboot()
log_action('VM_REBOOT', user, vm, job)
else:
raise PermissionDenied(
_("Sorry, but you do not have permission "
"to reboot this machine."))
# Redirect to instance-detail
return HttpResponseRedirect(
reverse("instance-detail",
args=[cluster.slug, vm.hostname]))
elif 'cancel' in request.POST:
# Remove session variables.
if 'edit_form' in request.session:
del request.session['edit_form']
# Redirect to instance-detail
return HttpResponseRedirect(
reverse("instance-detail", args=[cluster.slug, vm.hostname]))
elif request.method == "GET":
form = ModifyConfirmForm()
session = request.session
if 'edit_form' not in request.session:
return HttpResponseBadRequest('Incorrect Session Data')
data = session['edit_form']
info = vm.info
hvparams = info['hvparams']
old_set = dict(
vcpus=info['beparams']['vcpus'],
os=info['os'],
notes=vm.note_text
)
if has_balloonmem(cluster):
old_set['maxmem'] = info['beparams']['maxmem']
old_set['minmem'] = info['beparams']['minmem']
else:
old_set['memory'] = info['beparams']['memory']
nic_count = len(info['nic.links'])
for i in xrange(nic_count):
old_set['nic_link_%s' % i] = info['nic.links'][i]
old_set['nic_mac_%s' % i] = info['nic.macs'][i]
# Add hvparams to the old_set
old_set.update(hvparams)
instance_diff = {}
fields = hv_form(vm, data).fields
for key in data.keys():
if key in ['memory', 'maxmem', 'minmem']:
diff = compare(render_storage(old_set[key]),
render_storage(data[key]))
elif key == 'os':
oses = os_prettify([old_set[key], data[key]])
if len(oses) > 1:
"""
XXX - Special case for a cluster with two different types of
optgroups (i.e. Image, Debootstrap).
The elements at 00 and 10:
The optgroups
The elements at 010 and 110:
Tuple containing the OS Name and OS value.
The elements at 0101 and 1101:
String containing the OS Name
"""
oses[0][1][0] = list(oses[0][1][0])
oses[1][1][0] = list(oses[1][1][0])
oses[0][1][0][1] = '%s (%s)' % (oses[0][1][0][1], oses[0][0])
oses[1][1][0][1] = '%s (%s)' % (oses[1][1][0][1], oses[1][0])
oses = oses[0][1] + oses[1][1]
diff = compare(oses[0][1], oses[1][1])
else:
oses = oses[0][1]
diff = compare(oses[0][1], oses[1][1])
# diff = compare(oses[0][1], oses[1][1])
if key in ['nic_count', 'nic_count_original']:
continue
elif key not in old_set.keys():
diff = ""
instance_diff[fields[key].label] = _('Added')
else:
diff = compare(old_set[key], data[key])
if diff != "":
label = fields[key].label
instance_diff[label] = diff
# remove mac if it has not changed
for i in xrange(nic_count):
if fields['nic_mac_%s' % i].label not in instance_diff:
del data['nic_mac_%s' % i]
# Repopulate form with changed values
form.fields['rapi_dict'] = CharField(widget=HiddenInput,
initial=json.dumps(data))
return render_to_response(
'ganeti/virtual_machine/edit_confirm.html',
{
'cluster': cluster,
'form': form,
'instance': vm,
'instance_diff': instance_diff,
'power': power,
},
context_instance=RequestContext(request),
)
0
Example 173
Project: panda Source File: data.py
def search_all_data(self, request, **kwargs):
"""
List endpoint using Solr. Provides full-text search via the "q" parameter."
"""
self.method_check(request, allowed=['get'])
self.is_authenticated(request)
self.throttle_check(request)
try:
query = '(%s)' % request.GET['q']
except KeyError:
query = ''
category = request.GET.get('category', '')
since = request.GET.get('since', None)
limit = int(request.GET.get('limit', settings.PANDA_DEFAULT_SEARCH_GROUPS))
offset = int(request.GET.get('offset', 0))
group_limit = int(request.GET.get('group_limit', settings.PANDA_DEFAULT_SEARCH_ROWS_PER_GROUP))
group_offset = int(request.GET.get('group_offset', 0))
export = bool(request.GET.get('export', False))
solr_query_bits = [query]
if category:
if category != 'uncategorized':
category = Category.objects.get(slug=category)
dataset_slugs = category.datasets.values_list('slug', flat=True)
else:
dataset_slugs = Dataset.objects.filter(categories=None).values_list('slug', flat=True)
solr_query_bits.append('dataset_slug:(%s)' % ' '.join(dataset_slugs))
if since:
solr_query_bits.append('last_modified:[' + since + 'Z TO *]')
# Because users may have authenticated via headers the request.user may
# not be a full User instance. To be sure, we fetch one.
user = UserProxy.objects.get(id=request.user.id)
if export:
task_type = ExportSearchTask
task = TaskStatus.objects.create(
task_name=task_type.name,
task_description=_('Export search results for "%s".') % query,
creator=user
)
task_type.apply_async(
args=[query, task.id],
kwargs={},
task_id=task.id
)
else:
response = solr.query_grouped(
settings.SOLR_DATA_CORE,
' AND '.join(solr_query_bits),
'dataset_slug',
offset=offset,
limit=limit,
group_limit=group_limit,
group_offset=group_offset
)
groups = response['grouped']['dataset_slug']['groups']
page = PandaPaginator(
request.GET,
groups,
resource_uri=request.path_info,
count=response['grouped']['dataset_slug']['ngroups']
).page()
datasets = []
for group in groups:
dataset_slug = group['groupValue']
results = group['doclist']
try:
dataset = Dataset.objects.get(slug=dataset_slug)
# In the event that stale data exists in Solr, skip this dataset,
# request the invalid data be purged and return the other results.
# Pagination may be wrong, but this is the most functional solution. (#793)
except Dataset.DoesNotExist:
PurgeDataTask.apply_async(args=[dataset_slug])
solr.delete(settings.SOLR_DATASETS_CORE, 'slug:%s' % dataset_slug)
page['meta']['total_count'] -= 1
continue
dataset_resource = DatasetResource()
dataset_bundle = dataset_resource.build_bundle(obj=dataset, request=request)
dataset_bundle = dataset_resource.full_dehydrate(dataset_bundle)
dataset_bundle = dataset_resource.simplify_bundle(dataset_bundle)
objects = [SolrObject(obj) for obj in results['docs']]
dataset_search_url = reverse('api_dataset_data_list', kwargs={ 'api_name': self._meta.api_name, 'dataset_resource_name': 'dataset', 'resource_name': 'data', 'dataset_slug': dataset.slug })
data_page = PandaPaginator(
{ 'limit': str(group_limit), 'offset': str(group_offset), 'q': query },
objects,
resource_uri=dataset_search_url,
count=results['numFound']
).page()
dataset_bundle.data.update(data_page)
dataset_bundle.data['objects'] = []
for obj in objects:
data_bundle = self.build_bundle(obj=obj, request=request)
data_bundle = self.full_dehydrate(data_bundle)
dataset_bundle.data['objects'].append(data_bundle)
datasets.append(dataset_bundle.data)
page['objects'] = datasets
# Log query
SearchLog.objects.create(user=user, dataset=None, query=query)
self.log_throttled_access(request)
if export:
return self.create_response(request, _('Export queued.'))
else:
return self.create_response(request, page)
0
Example 174
Project: unisubs Source File: statistics.py
def compute_statistics(team, stats_type):
"""computes a bunch of statistics for the team, either at
the video or member levels.
"""
from views import TableCell
summary = ''
graph = ''
graph_recent = ''
summary_recent = ''
graph_additional = ''
graph_additional_recent = ''
summary_additional = ''
summary_additional_recent = ''
summary_table = ''
if stats_type == 'videosstats':
(complete_languages, incomplete_languages) = team.get_team_languages()
languages = complete_languages + incomplete_languages
unique_languages = set(languages)
total = 0
numbers = []
y_title = "Number of edited subtitles"
for l in unique_languages:
count_complete = complete_languages.count(l)
count_incomplete = incomplete_languages.count(l)
numbers.append((get_language_label(l), count_complete + count_incomplete, "Published: %s, total edits:" % count_complete))
total += count_complete + count_incomplete
summary = 'Top languages (all time)'
title = ""
graph = plot(numbers, title=title, graph_type='HorizontalBar', labels=True, max_entries=20, y_title=y_title)
(complete_languages_recent, incomplete_languages_recent, new_languages) = team.get_team_languages(since=30)
languages_recent = complete_languages_recent + incomplete_languages_recent
unique_languages_recent = set(languages_recent)
summary_recent = "Top languages (past 30 days)"
numbers_recent = []
total_recent = 0
for l in unique_languages_recent:
count_complete_recent = complete_languages_recent.count(l)
count_incomplete_recent = incomplete_languages_recent.count(l)
numbers_recent.append((get_language_label(l), count_complete_recent + count_incomplete_recent, "Published: %s, total edits:" % count_complete_recent))
total_recent += count_complete_recent + count_incomplete_recent
title_recent = ""
graph_recent = plot(numbers_recent, title=title_recent, graph_type='HorizontalBar', labels=True, max_entries=20, y_title=y_title)
summary_table = []
summary_table.append([TableCell("", header=True), TableCell("all time", header=True), TableCell("past 30 days", header=True)])
summary_table.append([TableCell("videos added", header=True), TableCell(str(team.videos_count)), TableCell(str(team.videos_count_since(30)))])
summary_table.append([TableCell("languages edited", header=True), TableCell(str(len(unique_languages))), TableCell(str(len(unique_languages_recent)))])
summary_table.append([TableCell("subtitles edited", header=True), TableCell(str(total)), TableCell(str(total_recent))])
elif stats_type == 'teamstats':
languages = list(team.languages())
unique_languages = set(languages)
summary = u'Members by language (all time)'
numbers = []
for l in unique_languages:
numbers.append((get_language_label(l), languages.count(l),
get_language_label(l)))
title = ''
graph = plot(numbers, graph_type='HorizontalBar', title=title, max_entries=25, labels=True, total_label="Members: ")
languages_recent = list(team.languages(members_joined_since=30))
unique_languages_recent = set(languages_recent)
summary_recent = u'New members by language (past 30 days)'
numbers_recent = []
for l in unique_languages_recent:
numbers_recent.append(
(get_language_label(l),
languages_recent.count(l),
get_language_label(l),
"%s://%s%s" % (DEFAULT_PROTOCOL, Site.objects.get_current().domain, reverse('teams:members', args=[], kwargs={'slug': team.slug}) + "?sort=-joined&lang=%s" % l))
)
title_recent = ''
graph_recent = plot(numbers_recent, graph_type='HorizontalBar', title=title_recent, max_entries=25, labels=True, xlinks=True, total_label="Members: ")
summary_table = []
summary_table.append([TableCell("", header=True), TableCell("all time", header=True), TableCell("past 30 days", header=True)])
summary_table.append([TableCell("members joined", header=True), TableCell(str(team.members_count)), TableCell(str(team.members_count_since(30)))])
summary_table.append([TableCell("member languages", header=True), TableCell(str(len(unique_languages))), TableCell(str(len(unique_languages_recent)))])
active_users = {}
for sv in team.active_users():
if sv[0] in active_users:
active_users[sv[0]].add(sv[1])
else:
active_users[sv[0]] = set([sv[1]])
most_active_users = active_users.items()
most_active_users.sort(reverse=True, key=lambda x: len(x[1]))
if len(most_active_users) > 20:
most_active_users = most_active_users[:20]
active_users_recent = {}
for sv in team.active_users(since=30):
if sv[0] in active_users_recent:
active_users_recent[sv[0]].add(sv[1])
else:
active_users_recent[sv[0]] = set([sv[1]])
most_active_users_recent = active_users_recent.items()
most_active_users_recent.sort(reverse=True, key=lambda x: len(x[1]))
if len(most_active_users_recent) > 20:
most_active_users_recent = most_active_users_recent[:20]
def displayable_user(user, users_details):
user_details = users_details[user[0]]
return ("%s %s (%s)" % (user_details[1], user_details[2], user_details[3]),
len(user[1]),
"%s %s (%s)" % (user_details[1], user_details[2], user_details[3]),
"%s://%s%s" % (DEFAULT_PROTOCOL, Site.objects.get_current().domain, reverse("profiles:profile", kwargs={'user_id': str(user[0])}))
)
user_details = User.displayable_users(map(lambda x: int(x[0]), most_active_users))
user_details_dict = {}
for user in user_details:
user_details_dict[user[0]] = user
most_active_users = map(lambda x: displayable_user(x, user_details_dict), most_active_users)
summary_additional = u'Top contributors (all time)'
graph_additional = plot(most_active_users, graph_type='HorizontalBar', title='', labels=True, xlinks=True, total_label="Contributions: ")
user_details_recent = User.displayable_users(map(lambda x: int(x[0]), most_active_users_recent))
user_details_dict_recent = {}
for user in user_details_recent:
user_details_dict_recent[user[0]] = user
most_active_users_recent = map(lambda x: displayable_user(x, user_details_dict_recent), most_active_users_recent)
summary_additional_recent = u'Top contributors (past 30 days)'
graph_additional_recent = plot(most_active_users_recent, graph_type='HorizontalBar', title='', labels=True, xlinks=True, total_label="Contributions: ")
statistics = {
'computed_on': datetime.utcnow().replace(tzinfo=utc).strftime("%A %d. %B %Y %H:%M:%S UTC"),
'summary': summary,
'summary_recent': summary_recent,
'activity_tab': stats_type,
'graph': graph,
'graph_recent': graph_recent,
'graph_additional': graph_additional,
'graph_additional_recent': graph_additional_recent,
'summary_additional': summary_additional,
'summary_additional_recent': summary_additional_recent,
'summary_table': summary_table,
}
return statistics