Here are the examples of the python api django.shortcuts.get_object_or_404 taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
177 Examples
0
Example 101
Project: saleor Source File: views.py
def product_details(request, slug, product_id):
"""Product details page
The following variables are available to the template:
product:
The Product instance itself.
is_visible:
Whether the product is visible to regular users (for cases when an
admin is previewing a product before publishing).
form:
The add-to-cart form.
price_range:
The PriceRange for the product including all discounts.
undiscounted_price_range:
The PriceRange excluding all discounts.
discount:
Either a Price instance equal to the discount value or None if no
discount was available.
local_price_range:
The same PriceRange from price_range represented in user's local
currency. The value will be None if exchange rate is not available or
the local currency is the same as site's default currency.
"""
products = products_with_details(user=request.user)
product = get_object_or_404(products, id=product_id)
if product.get_slug() != slug:
return HttpResponsePermanentRedirect(product.get_absolute_url())
today = datetime.date.today()
is_visible = (
product.available_on is None or product.available_on <= today)
form_class = get_form_class_for_product(product)
cart = get_cart_from_request(request)
# add to cart handling
form = form_class(cart=cart, product=product,
data=request.POST or None)
if form.is_valid():
form.save()
return redirect('cart:index')
# price handling
price_range = product.get_price_range(discounts=request.discounts)
undiscounted_price_range = product.get_price_range()
if undiscounted_price_range.min_price > price_range.min_price:
discount = undiscounted_price_range.min_price - price_range.min_price
else:
discount = None
local_price_range = to_local_currency(price_range, request.currency)
template_name = 'product/details_%s.html' % (
type(product).__name__.lower(),)
templates = [template_name, 'product/details.html']
return TemplateResponse(
request, templates,
{
'discount': discount,
'form': form,
'is_visible': is_visible,
'local_price_range': local_price_range,
'price_range': price_range,
'product': product,
'undiscounted_price_range': undiscounted_price_range})
0
Example 102
Project: kuma Source File: translate.py
@block_user_agents
@login_required
@process_docuement_path
@check_readonly
@prevent_indexing
@never_cache
def translate(request, docuement_slug, docuement_locale, revision_id=None):
"""
Create a new translation of a wiki docuement.
* docuement_slug is for the default locale
* translation is to the request locale
"""
# TODO: Refactor this view into two views? (new, edit)
# That might help reduce the headache-inducing branchiness.
# The parent docuement to translate from
parent_doc = get_object_or_404(Docuement,
locale=settings.WIKI_DEFAULT_LANGUAGE,
slug=docuement_slug)
if not revision_id:
# HACK: Seems weird, but sticking the translate-to locale in a query
# param is the best way to avoid the MindTouch-legacy locale
# redirection logic.
docuement_locale = request.GET.get('tolocale',
docuement_locale)
# Set a "Discard Changes" page
discard_href = ''
if settings.WIKI_DEFAULT_LANGUAGE == docuement_locale:
# Don't translate to the default language.
return redirect(reverse(
'wiki.edit', locale=settings.WIKI_DEFAULT_LANGUAGE,
args=[parent_doc.slug]))
if not parent_doc.is_localizable:
message = _(u'You cannot translate this docuement.')
context = {'message': message}
return render(request, 'handlers/400.html', context, status=400)
if revision_id:
revision = get_object_or_404(Revision, pk=revision_id)
else:
revision = None
based_on_rev = parent_doc.current_or_latest_revision()
disclose_description = bool(request.GET.get('opendescription'))
try:
doc = parent_doc.translations.get(locale=docuement_locale)
slug_dict = split_slug(doc.slug)
except Docuement.DoesNotExist:
doc = None
disclose_description = True
slug_dict = split_slug(docuement_slug)
# Find the "real" parent topic, which is its translation
if parent_doc.parent_topic:
try:
parent_topic_translated_doc = (parent_doc.parent_topic
.translations
.get(locale=docuement_locale))
slug_dict = split_slug(parent_topic_translated_doc.slug +
'/' +
slug_dict['specific'])
except ObjectDoesNotExist:
pass
user_has_doc_perm = (not doc) or (doc and doc.allows_editing_by(request.user))
user_has_rev_perm = (not doc) or (doc and doc.allows_revision_by(request.user))
if not user_has_doc_perm and not user_has_rev_perm:
# User has no perms, bye.
raise PermissionDenied
doc_form = rev_form = None
if user_has_doc_perm:
if doc:
# If there's an existing doc, populate form from it.
discard_href = doc.get_absolute_url()
doc.slug = slug_dict['specific']
doc_initial = docuement_form_initial(doc)
else:
# If no existing doc, bring over the original title and slug.
discard_href = parent_doc.get_absolute_url()
doc_initial = {'title': based_on_rev.title,
'slug': slug_dict['specific']}
doc_form = DocuementForm(initial=doc_initial,
parent_slug=slug_dict['parent'])
if user_has_rev_perm:
initial = {
'based_on': based_on_rev.id,
'current_rev': doc.current_or_latest_revision().id if doc else None,
'comment': '',
'toc_depth': based_on_rev.toc_depth,
'localization_tags': ['inprogress'],
}
content = None
if revision is not None:
content = revision.content
elif not doc:
content = based_on_rev.content
if content:
initial.update(content=kuma.wiki.content.parse(content)
.filterEditorSafety()
.serialize())
instance = doc and doc.current_or_latest_revision()
rev_form = RevisionForm(request=request,
instance=instance,
initial=initial,
parent_slug=slug_dict['parent'])
if request.method == 'POST':
which_form = request.POST.get('form-type', 'both')
doc_form_invalid = False
# Grab the posted slug value in case it's invalid
posted_slug = request.POST.get('slug', slug_dict['specific'])
if user_has_doc_perm and which_form in ['doc', 'both']:
disclose_description = True
post_data = request.POST.copy()
post_data.update({'locale': docuement_locale})
doc_form = DocuementForm(post_data, instance=doc,
parent_slug=slug_dict['parent'])
doc_form.instance.locale = docuement_locale
doc_form.instance.parent = parent_doc
if which_form == 'both':
# Sending a new copy of post so the slug change above
# doesn't cause problems during validation
rev_form = RevisionForm(request=request,
data=post_data,
parent_slug=slug_dict['parent'])
# If we are submitting the whole form, we need to check that
# the Revision is valid before saving the Docuement.
if doc_form.is_valid() and (which_form == 'doc' or
rev_form.is_valid()):
doc = doc_form.save(parent=parent_doc)
if which_form == 'doc':
url = urlparams(doc.get_edit_url(), opendescription=1)
return redirect(url)
else:
doc_form.data['slug'] = posted_slug
doc_form_invalid = True
if doc and user_has_rev_perm and which_form in ['rev', 'both']:
post_data = request.POST.copy()
if 'slug' not in post_data:
post_data['slug'] = posted_slug
# update the post data with the toc_depth of original
post_data['toc_depth'] = based_on_rev.toc_depth
# Pass in the locale for the akistmet "blog_lang".
post_data['locale'] = docuement_locale
rev_form = RevisionForm(request=request,
data=post_data,
parent_slug=slug_dict['parent'])
rev_form.instance.docuement = doc # for rev_form.clean()
if rev_form.is_valid() and not doc_form_invalid:
parent_id = request.POST.get('parent_id', '')
# Attempt to set a parent
if parent_id:
try:
parent_doc = get_object_or_404(Docuement, id=parent_id)
rev_form.instance.docuement.parent = parent_doc
doc.parent = parent_doc
rev_form.instance.based_on.docuement = doc.original
except Docuement.DoesNotExist:
pass
rev_form.save(doc)
# If this is an Ajax POST, then return a JsonResponse
if request.is_ajax():
data = {
'error': False,
'new_revision_id': rev_form.instance.id,
}
return JsonResponse(data)
return redirect(doc)
else:
# If this is an Ajax POST, then return a JsonResponse with error
if request.is_ajax():
if 'current_rev' in rev_form._errors:
# Make the error message safe so the '<' and '>' don't
# get turned into '<' and '>', respectively
rev_form.errors['current_rev'][0] = mark_safe(
rev_form.errors['current_rev'][0])
errors = [rev_form.errors[key][0] for key in rev_form.errors.keys()]
data = {
"error": True,
"error_message": errors,
"new_revision_id": rev_form.instance.id,
}
return JsonResponse(data=data)
if doc:
from_id = smart_int(request.GET.get('from'), None)
to_id = smart_int(request.GET.get('to'), None)
revision_from = get_object_or_none(Revision,
pk=from_id,
docuement=doc.parent)
revision_to = get_object_or_none(Revision,
pk=to_id,
docuement=doc.parent)
else:
revision_from = revision_to = None
parent_split = split_slug(parent_doc.slug)
language_mapping = get_language_mapping()
language = language_mapping[docuement_locale.lower()]
default_locale = language_mapping[settings.WIKI_DEFAULT_LANGUAGE.lower()]
context = {
'parent': parent_doc,
'docuement': doc,
'docuement_form': doc_form,
'revision_form': rev_form,
'locale': docuement_locale,
'default_locale': default_locale,
'language': language,
'based_on': based_on_rev,
'disclose_description': disclose_description,
'discard_href': discard_href,
'attachment_form': AttachmentRevisionForm(),
'specific_slug': parent_split['specific'],
'parent_slug': parent_split['parent'],
'revision_from': revision_from,
'revision_to': revision_to,
}
return render(request, 'wiki/translate.html', context)
0
Example 103
Project: hyperkitty Source File: mlist.py
@check_mlist_private
def overview(request, mlist_fqdn=None):
if not mlist_fqdn:
return redirect('/')
mlist = get_object_or_404(MailingList, name=mlist_fqdn)
threads = []
for thread_obj in mlist.recent_threads:
thread_obj.category_widget = get_category_widget(
None, thread_obj.category)[0]
threads.append(thread_obj)
# top threads are the one with the most answers
top_threads = sorted(threads, key=lambda t: t.emails_count, reverse=True)
# active threads are the ones that have the most recent posting
active_threads = sorted(threads, key=lambda t: t.date_active, reverse=True)
# top authors are the ones that have the most kudos. How do we determine
# that? Most likes for their post?
if settings.USE_MOCKUPS:
authors = generate_top_author()
authors = sorted(authors, key=lambda author: author.kudos)
authors.reverse()
else:
authors = []
# Popular threads
pop_threads = []
for t in threads:
votes = t.get_votes()
if votes["likes"] - votes["dislikes"] > 0:
pop_threads.append(t)
def _get_thread_vote_result(t):
votes = t.get_votes()
return votes["likes"] - votes["dislikes"]
pop_threads.sort(key=_get_thread_vote_result, reverse=True)
# Threads by category
threads_by_category = {}
for thread in active_threads:
if not thread.category:
continue
# don't use defaultdict, use .setdefault():
# http://stackoverflow.com/questions/4764110/django-template-cant-loop-defaultdict
if len(threads_by_category.setdefault(thread.category, [])) >= 5:
continue
threads_by_category[thread.category].append(thread)
# Personalized discussion groups: flagged/favorited threads and threads by user
if request.user.is_authenticated():
favorites = [ f.thread for f in Favorite.objects.filter(
thread__mailinglist=mlist, user=request.user) ]
mm_user_id = request.user.hyperkitty_profile.get_mailman_user_id()
threads_posted_to = mlist.threads.filter(
emails__sender__mailman_id=mm_user_id).distinct()
else:
favorites = []
threads_posted_to = []
# Empty messages # TODO: translate this
empty_messages = {
"flagged": 'You have not flagged any discussions (yet).',
"posted": 'You have not posted to this list (yet).',
"active": 'No discussions this month (yet).',
"popular": 'No vote has been cast this month (yet).',
}
context = {
'view_name': 'overview',
'mlist' : mlist,
'top_threads': top_threads[:20],
'most_active_threads': active_threads[:20],
'top_author': authors,
'pop_threads': pop_threads[:20],
'threads_by_category': threads_by_category,
'months_list': get_months(mlist),
'flagged_threads': favorites,
'threads_posted_to': threads_posted_to,
'empty_messages': empty_messages,
}
return render(request, "hyperkitty/overview.html", context)
0
Example 104
Project: META-SHARE Source File: views.py
def view(request, resource_name=None, object_id=None):
"""
Render browse or detail view for the repository application.
"""
# only published resources may be viewed
resource = get_object_or_404(resourceInfoType_model,
storage_object__identifier=object_id,
storage_object__publication_status=PUBLISHED)
if request.path_info != resource.get_absolute_url():
return redirect(resource.get_absolute_url())
# Convert resource to ElementTree and then to template tuples.
lr_content = _convert_to_template_tuples(
resource.export_to_elementtree(pretty=True))
# get the 'best' language version of a "DictField" and all other versions
resource_name = resource.identificationInfo.get_default_resourceName()
res_short_names = resource.identificationInfo.resourceShortName.values()
description = resource.identificationInfo.get_default_description()
other_res_names = [name for name in resource.identificationInfo \
.resourceName.itervalues() if name != resource_name]
other_descriptions = [name for name in resource.identificationInfo \
.description.itervalues() if name != description]
# Create fields lists
url = resource.identificationInfo.url
metashare_id = resource.identificationInfo.metaShareId
identifier = resource.identificationInfo.identifier
resource_type = resource.resourceComponentType.as_subclass().resourceType
media_types = set(model_utils.get_resource_media_types(resource))
linguality_infos = set(model_utils.get_resource_linguality_infos(resource))
license_types = set(model_utils.get_resource_license_types(resource))
distribution_info_tuple = None
contact_person_tuples = []
metadata_info_tuple = None
version_info_tuple = None
validation_info_tuples = []
usage_info_tuple = None
docuementation_info_tuple = None
resource_creation_info_tuple = None
relation_info_tuples = []
resource_component_tuple = None
for _tuple in lr_content[1]:
if _tuple[0] == "Distribution":
distribution_info_tuple = _tuple
elif _tuple[0] == "Contact person":
contact_person_tuples.append(_tuple)
elif _tuple[0] == "Metadata":
metadata_info_tuple = _tuple
elif _tuple[0] == "Version":
version_info_tuple = _tuple
elif _tuple[0] == "Validation":
validation_info_tuples.append(_tuple)
elif _tuple[0] == "Usage":
usage_info_tuple = _tuple
elif _tuple[0] == "Resource docuementation":
docuementation_info_tuple = _tuple
elif _tuple[0] == "Resource creation":
resource_creation_info_tuple = _tuple
elif _tuple[0] == "Relation":
relation_info_tuples.append(_tuple)
elif _tuple[0] == "Resource component":
resource_component_tuple = _tuple[1]
# Convert resource_component_tuple to nested dictionaries
resource_component_dicts = {}
validation_dicts = []
relation_dicts = []
# Convert several tuples to dictionaries to facilitate rendering
# the templates.
contact_person_dicts = []
for item in contact_person_tuples:
contact_person_dicts.append(tuple2dict([item]))
distribution_dict = tuple2dict([distribution_info_tuple])
resource_component_dict = tuple2dict(resource_component_tuple)
resource_creation_dict = tuple2dict([resource_creation_info_tuple])
metadata_dict = tuple2dict([metadata_info_tuple])
usage_dict = tuple2dict([usage_info_tuple])
version_dict = tuple2dict([version_info_tuple])
docuementation_dict = tuple2dict([docuementation_info_tuple])
for item in validation_info_tuples:
validation_dicts.append(tuple2dict([item]))
for item in relation_info_tuples:
relation_dicts.append(tuple2dict([item]))
# Count individual media resource components
text_counts = []
video_counts = []
if resource_type == "corpus":
for key, value in resource_component_dict['Resource_component']['Corpus_media'].items():
if "Corpus_text" in key and not "numerical" in key and not "ngram" in key:
text_counts.append(value)
elif "Corpus_video" in key:
video_counts.append(value)
# Create a list of resource components dictionaries
if resource_type == "corpus":
for media_type in media_types:
if media_type == "text":
resource_component_dicts['text'] = \
resource_component_dict['Resource_component'] \
['Corpus_media']['Corpus_text']
if media_type == "audio":
resource_component_dicts['audio'] = \
resource_component_dict['Resource_component'] \
['Corpus_media']['Corpus_audio']
if media_type == "video":
resource_component_dicts['video'] = \
resource_component_dict['Resource_component'] \
['Corpus_media']['Corpus_video']
if media_type == "image":
resource_component_dicts['image'] = \
resource_component_dict['Resource_component'] \
['Corpus_media']['Corpus_image']
if media_type == "textNgram":
resource_component_dicts['textNgram'] = \
resource_component_dict['Resource_component'] \
['Corpus_media']['Corpus_textNgram']
if media_type == "textNumerical":
resource_component_dicts['textNumerical'] = \
resource_component_dict['Resource_component'] \
['Corpus_media']['Corpus_textNumerical']
elif resource_type == "languageDescription":
for media_type in media_types:
if media_type == "text":
resource_component_dicts['text'] = \
resource_component_dict['Resource_component'] \
['Language_description_media']['Language_description_text']
if media_type == "image":
resource_component_dicts['image'] = \
resource_component_dict['Resource_component'] \
['Language_description_media']['Language_description_image']
if media_type == "video":
resource_component_dicts['video'] = \
resource_component_dict['Resource_component'] \
['Language_description_media']['Language_description_video']
elif resource_type == "lexicalConceptualResource":
for media_type in media_types:
if media_type == "text":
resource_component_dicts['text'] = \
resource_component_dict['Resource_component'] \
['Lexical_conceptual_resource_media'] \
['Lexical_conceptual_resource_text']
if media_type == "audio":
resource_component_dicts['audio'] = \
resource_component_dict['Resource_component'] \
['Lexical_conceptual_resource_media'] \
['Lexical_conceptual_resource_audio']
if media_type == "video":
resource_component_dicts['video'] = \
resource_component_dict['Resource_component'] \
['Lexical_conceptual_resource_media'] \
['Lexical_conceptual_resource_video']
if media_type == "image":
resource_component_dicts['image'] = \
resource_component_dict['Resource_component'] \
['Lexical_conceptual_resource_media'] \
['Lexical_conceptual_resource_image']
elif resource_type == "toolService":
resource_component_dicts['toolService'] = \
resource_component_dict['Resource_component']
# Define context for template rendering.
context = {
'contact_person_dicts': contact_person_dicts,
'description': description,
'distribution_dict': distribution_dict,
'docuementation_dict': docuementation_dict,
'license_types': license_types,
'linguality_infos': linguality_infos,
'mediaTypes': media_types,
'metadata_dict': metadata_dict,
'metaShareId': metashare_id,
'identifier': identifier,
'other_res_names': other_res_names,
'other_descriptions': other_descriptions,
'relation_dicts': relation_dicts,
'res_short_names': res_short_names,
'resource': resource,
'resource_component_dicts': resource_component_dicts,
'resource_component_dict': resource_component_dict,
'resourceName': resource_name,
'resourceType': resource_type,
'resource_creation_dict': resource_creation_dict,
'url': url,
'usage_dict': usage_dict,
'validation_dicts': validation_dicts,
'version_dict': version_dict,
'text_counts': text_counts,
'video_counts': video_counts,
}
template = 'repository/resource_view/lr_view.html'
# For users who have edit permission for this resource, we have to add
# LR_EDIT which contains the URL of the Django admin backend page
# for this resource.
if has_edit_permission(request, resource):
context['LR_EDIT'] = reverse(
'admin:repository_resourceinfotype_model_change', \
args=(resource.id,))
# Update statistics:
if saveLRStats(resource, VIEW_STAT, request):
# update view count in the search index, too
update_lr_index_entry(resource)
# update view tracker
tracker = SessionResourcesTracker.getTracker(request)
tracker.add_view(resource, datetime.now())
request.session['tracker'] = tracker
# Add download/view/last updated statistics to the template context.
context['LR_STATS'] = getLRStats(resource.storage_object.identifier)
# Add recommendations for 'also viewed' resources
context['also_viewed'] = \
_format_recommendations(get_view_recommendations(resource))
# Add recommendations for 'also downloaded' resources
context['also_downloaded'] = \
_format_recommendations(get_download_recommendations(resource))
# Add 'more from same' links
if get_more_from_same_projects_qs(resource).count():
context['search_rel_projects'] = '{}/repository/search?q={}:{}'.format(
DJANGO_URL, MORE_FROM_SAME_PROJECTS,
resource.storage_object.identifier)
if get_more_from_same_creators_qs(resource).count():
context['search_rel_creators'] = '{}/repository/search?q={}:{}'.format(
DJANGO_URL, MORE_FROM_SAME_CREATORS,
resource.storage_object.identifier)
# Render and return template with the defined context.
ctx = RequestContext(request)
return render_to_response(template, context, context_instance=ctx)
0
Example 105
Project: django-admin2 Source File: test_permissions.py
def test_view_binding(self):
user_admin = djadmin2_site.get_admin_by_name('auth_user')
post_admin = djadmin2_site.get_admin_by_name('blog_post')
request = self.factory.get(reverse('admin2:auth_user_index'))
request.user = self.user
permissions = TemplatePermissionChecker(request, user_admin)
context = {
'post_admin': post_admin,
'post_add_view': post_admin.create_view,
'permissions': permissions,
}
result = self.render(
'{% load admin2_tags %}'
'{{ permissions|for_view:"add" }}',
context)
self.assertEqual(result, 'False')
# view classes are not supported yet
result = self.render(
'{% load admin2_tags %}'
'{{ permissions|for_view:post_add_view }}',
context)
self.assertEqual(result, '')
result = self.render(
'{% load admin2_tags %}'
# user add permission
'{{ permissions.has_add_permission }}'
'{% with permissions|for_admin:"blog_post"|for_view:"add" as post_add_perm %}'
# post add permission
'{{ post_add_perm }}'
'{% endwith %}',
context)
self.assertEqual(result, 'FalseFalse')
post_add_permission = Permission.objects.get(
content_type__app_label='blog',
content_type__model='post',
codename='add_post')
self.user.user_permissions.add(post_add_permission)
user_change_permission = Permission.objects.get(
content_type__app_label='auth',
content_type__model='user',
codename='change_user')
self.user.user_permissions.add(user_change_permission)
# invalidate the users permission cache
self.user = get_object_or_404(User, pk=self.user.id)
request.user = self.user
result = self.render(
'{% load admin2_tags %}'
# user add permission
'{{ permissions.has_add_permission }}'
'{% with permissions|for_admin:"blog_post"|for_view:"add" as post_add_perm %}'
# post add permission
'{{ post_add_perm }}'
'{% endwith %}'
# user change permission
'{{ permissions|for_view:"change" }}',
context)
self.assertEqual(result, 'FalseTrueTrue')
# giving a string (the name of the view) also works
result = self.render(
'{% load admin2_tags %}'
'{% with permissions|for_view:"change" as user_change_perm %}'
'1{{ user_change_perm }}'
'2{{ user_change_perm|for_view:"add" }}'
# this shouldn't return True or False but '' since the
# previously bound change view doesn't belong to the newly
# bound blog_post admin
'3{{ user_change_perm|for_admin:"blog_post" }}'
'4{{ user_change_perm|for_admin:"blog_post"|for_view:"add" }}'
'{% endwith %}',
context)
self.assertEqual(result, '1True2False34True')
0
Example 106
Project: django-uocLTI Source File: views.py
@csrf_exempt
def launch_lti(request):
""" Receives a request from the lti consumer and creates/authenticates user in django """
""" See post items in log by setting LTI_DEBUG=True in settings """
if settings.LTI_DEBUG:
for item in request.POST:
print ('%s: %s \r' % (item, request.POST[item]))
if 'oauth_consumer_key' not in request.POST:
raise PermissionDenied()
""" key/secret from settings """
consumer_key = settings.CONSUMER_KEY
secret = settings.LTI_SECRET
tool_provider = DjangoToolProvider(consumer_key, secret, request.POST)
print "ROLES: %s " % tool_provider.roles
try: # attempt to validate request, if fails raises 403 Forbidden
if tool_provider.valid_request(request) == False:
raise PermissionDenied()
except:
raise PermissionDenied()
""" RETRIEVE username, names, email and roles. These may be specific to the consumer,
in order to change them from the default values: see README.txt """
first_name = get_lti_value(settings.LTI_FIRST_NAME, tool_provider)
last_name = get_lti_value(settings.LTI_LAST_NAME, tool_provider)
email = get_lti_value(settings.LTI_EMAIL, tool_provider)
# avatar = tool_provider.custom_params['custom_photo']
roles = get_lti_value(settings.LTI_ROLES, tool_provider)
user_id = get_lti_value('user_id', tool_provider)
if not email or not user_id:
print "Email and/or user_id wasn't found in post, return Permission Denied"
raise PermissionDenied()
""" CHECK IF USER'S ROLES ALLOW ENTRY, IF RESTRICTION SET BY VELVET_ROLES SETTING """
if settings.VELVET_ROLES:
""" Roles allowed for entry into the application. If these are not set in settings then we allow all roles to enter """
if not roles:
""" if roles is None, then setting for LTI_ROLES may be wrong, return 403 for user and print error to log """
print "VELVET_ROLES is set but the roles for the user were not found. Check that the setting for LTI_ROLES is correct."
raise PermissionDenied()
if not isinstance(roles, list): roles = (roles,) # In the case we are using a custom field for roles, may be a string and needs to be converted to a list
is_role_allowed = [m for velvet_role in settings.VELVET_ROLES for m in roles if velvet_role.lower()==m.lower()]
if not is_role_allowed:
print "User does not have accepted role for entry, roles: %s" % roles
raise PermissionDenied()
""" GET OR CREATE NEW USER AND LTI_PROFILE """
lti_username = '%s:user_%s' % (request.POST['oauth_consumer_key'], user_id) #create username with consumer_key and user_id
try:
""" Check if user already exists using email, if not create new """
user = User.objects.get(email=email)
if user.username != lti_username:
""" If the username is not in the format user_id, change it and save. This could happen
if there was a previously populated User table. """
user.username = lti_username
user.save()
except User.DoesNotExist:
""" first time entry, create new user """
user = User.objects.create_user(lti_username, email)
user.set_unusable_password()
if first_name: user.first_name = first_name
if last_name: user.last_name = last_name
user.save()
except User.MultipleObjectsReturned:
""" If the application is not requiring unique emails, multiple users may be returned if there was an existing
User table before implementing this app with multiple users for the same email address. Could add code to merge them, but for now we return 404 if
the user with the lti_username does not exist """
user = get_object_or_404(User, username=lti_username)
""" CHECK IF ANY OF USER'S ROLES ARE IN THE VELVET_ADMIN_ROLES SETTING, IF SO MAKE SUPERUSER IF IS NOT ALREADY """
if not user.is_superuser and settings.VELVET_ADMIN_ROLES:
if [m for l in settings.VELVET_ADMIN_ROLES for m in roles if l.lower() in m.lower()]:
user.is_superuser = True
user.is_staff = True
user.save()
""" Save extra info to custom profile model (add/remove fields in models.py)"""
lti_userprofile = user.get_profile()
lti_userprofile.roles = roles
# lti_userprofile.avatar = avatar #TO BE ADDED: function to grab user profile image if exists
lti_userprofile.save()
""" Log in user and redirect to LOGIN_REDIRECT_URL defined in settings (default: accounts/profile) """
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
0
Example 107
Project: airmozilla Source File: views.py
@transaction.atomic
def home(request):
context = {
'q': None,
'events_found': None,
'search_error': None,
'tags': None,
'possible_tags': None,
'channels': None,
'possible_channels': None,
'found_channels': [],
'found_channels_count': 0,
}
if request.GET.get('q'):
form = forms.SearchForm(request.GET)
else:
form = forms.SearchForm()
if request.GET.get('q') and form.is_valid():
context['q'] = form.cleaned_data['q']
privacy_filter = {}
privacy_exclude = {}
qs = Event.objects.scheduled_or_processing()
if request.user.is_active:
if is_contributor(request.user):
privacy_exclude = {'privacy': Event.PRIVACY_COMPANY}
else:
# privacy_filter = {'privacy': Event.PRIVACY_PUBLIC}
privacy_exclude = {'privacy': Event.PRIVACY_COMPANY}
qs = qs.approved()
extra = {}
rest, params = split_search(context['q'], ('tag', 'channel'))
if params.get('tag'):
tags = Tag.objects.filter(name__iexact=params['tag'])
if tags:
context['q'] = rest
context['tags'] = extra['tags'] = tags
else:
# is the search term possibly a tag?
all_tag_names = Tag.objects.all().values_list('name', flat=True)
tags_regex = re.compile(
r'\b(%s)\b' %
('|'.join(re.escape(x) for x in all_tag_names),),
re.I
)
# next we need to turn all of these into a Tag QuerySet
# because we can't do `filter(name__in=tags_regex.findall(...))`
# because that case sensitive.
tag_ids = []
for match in tags_regex.findall(rest):
tag_ids.extend(
Tag.objects.filter(name__iexact=match)
.values_list('id', flat=True)
)
possible_tags = Tag.objects.filter(
id__in=tag_ids
)
for tag in possible_tags:
regex = re.compile(re.escape(tag.name), re.I)
tag._query_string = regex.sub(
'',
context['q'],
)
tag._query_string += ' tag: %s' % tag.name
# reduce all excess whitespace into 1
tag._query_string = re.sub(
'\s\s+',
' ',
tag._query_string
)
tag._query_string = tag._query_string.strip()
context['possible_tags'] = possible_tags
if params.get('channel'):
channels = Channel.objects.filter(name__iexact=params['channel'])
if channels:
context['q'] = rest
context['channels'] = extra['channels'] = channels
else:
# is the search term possibly a channel?
all_channel_names = (
Channel.objects.all().values_list('name', flat=True)
)
channels_regex = re.compile(
r'\b(%s)\b' %
('|'.join(re.escape(x) for x in all_channel_names),),
re.I
)
channel_ids = []
for match in channels_regex.findall(rest):
channel_ids.extend(
Channel.objects
.filter(name__iexact=match).values_list('id', flat=True)
)
possible_channels = Channel.objects.filter(
id__in=channel_ids
)
for channel in possible_channels:
regex = re.compile(re.escape(channel.name), re.I)
channel._query_string = regex.sub(
'',
context['q'],
)
channel._query_string += ' channel: %s' % channel.name
# reduce all excess whitespace into 1
channel._query_string = re.sub(
'\s\s+',
' ',
channel._query_string
)
channel._query_string = channel._query_string.strip()
context['possible_channels'] = possible_channels
events = _search(
qs,
context['q'],
privacy_filter=privacy_filter,
privacy_exclude=privacy_exclude,
sort=request.GET.get('sort'),
**extra
)
if not events.count() and utils.possible_to_or_query(context['q']):
events = _search(
qs,
context['q'],
privacy_filter=privacy_filter,
privacy_exclude=privacy_exclude,
sort=request.GET.get('sort'),
fuzzy=True
)
found_channels = _find_channels(context['q'])
context['found_channels'] = found_channels # it's a list
context['found_channels_count'] = len(found_channels)
elif request.GET.get('ss'):
savedsearch = get_object_or_404(
SavedSearch,
id=request.GET.get('ss')
)
context['savedsearch'] = savedsearch
events = savedsearch.get_events()
# But if you're just browsing we want to make sure you don't
# see anything you're not supposed to see.
if request.user.is_active:
if is_contributor(request.user):
events = events.exclude(privacy=Event.PRIVACY_COMPANY)
else:
events = events.filter(privacy=Event.PRIVACY_PUBLIC)
# It's not obvious how to sort these. They all match the saved
# search.
# Let's keep it simple and sort by start time for now
events = events.order_by('-start_time')
else:
events = None
if events is not None:
try:
page = int(request.GET.get('page', 1))
if page < 1:
raise ValueError
except ValueError:
return http.HttpResponseBadRequest('Invalid page')
# we use the paginator() function to get the Paginator
# instance so we can avoid calling `events.count()` for the
# header of the page where it says "XX events found"
try:
with transaction.atomic():
pager, events_paged = paginator(events, page, 10)
_database_error_happened = False
except DatabaseError:
_database_error_happened = True
# don't feed the trolls, just return nothing found
pager, events_paged = paginator(Event.objects.none(), 1, 10)
next_page_url = prev_page_url = None
def url_maker(page):
querystring = {'page': page}
if context.get('savedsearch'):
querystring['ss'] = context['savedsearch'].id
else:
querystring['q'] = context['q'].encode('utf-8')
querystring = urllib.urlencode(querystring)
return '%s?%s' % (reverse('search:home'), querystring)
if events_paged.has_next():
next_page_url = url_maker(events_paged.next_page_number())
if events_paged.has_previous():
prev_page_url = url_maker(events_paged.previous_page_number())
context['events_paged'] = events_paged
context['next_page_url'] = next_page_url
context['prev_page_url'] = prev_page_url
context['events_found'] = pager.count
context['channels'] = get_event_channels(events_paged)
log_searches = settings.LOG_SEARCHES and '_nolog' not in request.GET
if (
log_searches and
not _database_error_happened and
request.GET.get('q', '').strip()
):
logged_search = LoggedSearch.objects.create(
term=request.GET['q'][:200],
results=events.count(),
page=page,
user=request.user.is_authenticated() and request.user or None
)
request.session['logged_search'] = (
logged_search.pk,
time.time()
)
elif request.GET.get('q'):
context['search_error'] = form.errors['q']
else:
context['events'] = []
context['form'] = form
return render(request, 'search/home.html', context)
0
Example 108
Project: django-mr_reports Source File: views.py
def render_report(request, report_id, format=''):
"""Render a given report, or ask for parameters if needed
A utils.execute_subscription also runs this function using a mock request object
so don't always expect request to contain things like user, etc.
"""
report = get_object_or_404(Report, pk=report_id)
subscriptions, subscription_formset, subscribe_parameters, show_subscription_form = [], None, '', False
today = datetime.datetime.today()
curr_url = request.get_full_path()
base_path = ''
datasets = []
#If form exists, and is not bound, or is not valid, prompt for parameters
#otherwise render report
ParameterForm = build_parameter_form(report)
prompt_for_parameters = False
if ParameterForm:
if request.GET:
parameter_form = ParameterForm(request.GET)
if parameter_form.is_valid():
#render report
datasets = report.get_all_data(parameter_form)
#Include links to PDF and CSV versions of report
if '?' in curr_url:
csv_url = ''.join([curr_url.split('?')[0],'csv/?',curr_url.split('?')[1]])
pdf_url = ''.join([curr_url.split('?')[0],'pdf/?',curr_url.split('?')[1]])
subscribe_parameters = curr_url.split('?')[1]
else:
csv_url, pdf_url = '','' #when running as a scheduled email we won't have curr_url
else:
prompt_for_parameters = True
else:
prompt_for_parameters = True
parameter_form = ParameterForm()
else:
#render report
parameter_form = None
datasets = report.get_all_data(parameter_form)
#Include links to PDF and CSV versions of report
csv_url = curr_url + 'csv/'
pdf_url = curr_url + 'pdf/'
#pull subscriptions if any, handle saving
if getattr(request,'user',False):
if request.POST:
subscription_formset = SubscriptionFormSet(request.POST)
if subscription_formset.is_valid():
#add in non displayed fields: send_to and report
instances = subscription_formset.save(commit=False)
for instance in instances:
instance.send_to = request.user
instance.report = report
instance.save()
return HttpResponseRedirect(curr_url)
else:
#print subscription_formset.forms[-1].changed_data
#Show subscription form when loading page to highlight errors
show_subscription_form = True
else:
#Note, Django 1.6 won't allow an initial/default value for time :-( lest it thinks an
#unchanged extra form has been changed.
subscriptions = Subscription.objects.filter(send_to=request.user, report=report)
subscription_formset = SubscriptionFormSet(queryset=subscriptions,
initial=[{'frequency':'Monthly'}])
#Footer:
footer_html = getattr(settings,'MR_REPORTS_FOOTER_HTML',
"<p><em>Generated by <a href=''>Mr. Reports</a>.</em></p>")
#Handle alternative outputs
if format=='csv':
assert datasets and not prompt_for_parameters
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="%s.csv"' % report.filename()
response = data_to_csv(response,datasets)
return response
elif format=='pdf':
assert datasets and not prompt_for_parameters
base_path = settings.BASE_PATH.rstrip('/')
context = RequestContext(request, locals())
return output_pdf(request, context, report)
else:
#normal page render
return render(request, 'mr_reports/report.html', locals())
0
Example 109
Project: remo Source File: views.py
@never_cache
@user_passes_test(lambda u: u.groups.filter(Q(name='Rep') | Q(name='Admin')),
login_url=settings.LOGIN_REDIRECT_URL)
@permission_check(permissions=['profiles.can_edit_profiles'],
filter_field='display_name', owner_field='user',
model=UserProfile)
def edit(request, display_name):
"""Edit user profile.
Permission to edit user profile is granted to the user who owns
the profile and all the users with permissions to edit profiles.
Argument display_name should be lowered before queries because we
allow case-insensitive profile urls. E.g. both /u/Giorgos and
/u/giorgos are the same person.
"""
def profile_date_form_validation(form):
"""Convenience function to only validate datejoinedform when
user has permissions.
"""
if request.user.has_perm('profiles.can_edit_profiles'):
if form.is_valid():
return True
return False
return True
user = get_object_or_404(User,
userprofile__display_name__iexact=display_name)
userform = forms.ChangeUserForm(request.POST or None, instance=user)
profileform = forms.ChangeProfileForm(request.POST or None,
instance=user.userprofile,
request=request)
profile_date_form = forms.ChangeDatesForm(request.POST or None,
instance=user.userprofile)
if (userform.is_valid() and profileform.is_valid() and
profile_date_form_validation(profile_date_form)):
userform.save()
profileform.save()
if request.user.has_perm('profiles.can_edit_profiles'):
# Update groups.
groups = {'Mentor': 'mentor_group',
'Admin': 'admin_group',
'Council': 'council_group',
'Rep': 'rep_group',
'Alumni': 'alumni_group',
'Review': 'review_group',
'Peers': 'peers_group'}
for group_db, group_html in groups.items():
if Group.objects.filter(name=group_db).exists():
if request.POST.get(group_html, None):
user.groups.add(Group.objects.get(name=group_db))
else:
user.groups.remove(Group.objects.get(name=group_db))
# Update date fields
profile_date_form.save()
messages.success(request, 'Profile successfully edited.')
statsd.incr('profiles.edit_profile')
if request.user == user:
return redirect('profiles_view_my_profile')
else:
redirect_url = reverse('profiles_view_profile',
kwargs={'display_name':
user.userprofile.display_name})
return redirect(redirect_url)
else:
# If forms are not valid and the fields are dirty, get a fresh copy
# of the object.
# This is needed when an invalid display_name is used.
# Django tries to resolve the url based on this display_name, which
# results in a NoReverseMatch error. See also bug:
# https://bugzilla.mozilla.org/show_bug.cgi?id=1147541
user = User.objects.get(pk=user.id)
group_bits = map(lambda x: user.groups.filter(name=x).exists(),
['Admin', 'Council', 'Mentor', 'Rep', 'Alumni', 'Review', 'Peers'])
functional_areas = map(int, profileform['functional_areas'].value())
user_is_alumni = user.groups.filter(name='Alumni').exists()
return render(request, 'profiles_edit.jinja',
{'userform': userform,
'profileform': profileform,
'profile_date_form': profile_date_form,
'pageuser': user,
'group_bits': group_bits,
'range_years': range(1950, now().date().year - 11),
'functional_areas': functional_areas,
'user_is_alumni': user_is_alumni})
0
Example 110
Project: ganetimgr Source File: instances.py
@login_required
@check_instance_readonly
def instance(request, cluster_slug, instance):
cluster = get_object_or_404(Cluster, slug=cluster_slug)
instance = cluster.get_instance_or_404(instance)
if request.method == 'POST':
configform = InstanceConfigForm(request.POST)
if configform.is_valid():
needs_reboot = False
# The instance needs reboot if any of the hvparams have changed.
if configform.cleaned_data['cdrom_type'] == 'none':
configform.cleaned_data['cdrom_image_path'] = ""
for key, val in configform.cleaned_data.items():
if key == "cdrom_type":
continue
if key == "whitelist_ip":
continue
if configform.cleaned_data[key] != instance.hvparams[key]:
if instance.admin_state:
needs_reboot = True
if configform.cleaned_data['cdrom_type'] == 'none':
configform.cleaned_data['cdrom_image_path'] = ""
elif (configform.cleaned_data['cdrom_image_path'] !=
instance.hvparams['cdrom_image_path']):
# This should be an http URL
if (
not (
configform.cleaned_data['cdrom_image_path'].startswith(
'http://'
) or
configform.cleaned_data['cdrom_image_path'].startswith(
'https://'
) or
configform.cleaned_data['cdrom_image_path'] == ""
)
):
# Remove this, we don't want them to
# be able to read local files
del configform.cleaned_data['cdrom_image_path']
data = {}
whitelistip = None
for key, val in configform.cleaned_data.items():
if key == "cdrom_type":
continue
if key == "whitelist_ip":
whitelistip = val
if len(val) == 0:
whitelistip = None
continue
data[key] = val
auditlog = auditlog_entry(
request,
"Setting %s" % (
", ".join(
[
"%s:%s" % (key, value) for key, value in data.iteritems()
]
)
),
instance,
cluster_slug
)
jobid = instance.set_params(hvparams=data)
auditlog.update(job_id=jobid)
if needs_reboot:
instance.cluster.tag_instance(
instance.name,
["%s:needsreboot" % (settings.GANETI_TAG_PREFIX)]
)
if instance.whitelistip and whitelistip is None:
auditlog = auditlog_entry(
request,
"Remove whitelist %s" % instance.whitelistip,
instance,
cluster_slug
)
jobid = instance.cluster.untag_instance(
instance.name,
["%s:whitelist_ip:%s" % (
settings.GANETI_TAG_PREFIX,
instance.whitelistip
)]
)
auditlog.update(job_id=jobid)
instance.cluster.migrate_instance(instance.name)
if whitelistip:
if instance.whitelistip:
auditlog = auditlog_entry(
request,
"Remove whitelist %s" % instance.whitelistip,
instance,
cluster_slug
)
jobid = instance.cluster.untag_instance(
instance.name,
["%s:whitelist_ip:%s" % (
settings.GANETI_TAG_PREFIX,
instance.whitelistip
)])
auditlog.update(job_id=jobid)
auditlog = auditlog_entry(
request,
"Add whitelist %s" % whitelistip, instance, cluster_slug
)
jobid = instance.cluster.tag_instance(
instance.name,
["%s:whitelist_ip:%s" % (settings.GANETI_TAG_PREFIX, whitelistip)]
)
auditlog.update(job_id=jobid)
instance.cluster.migrate_instance(instance.name)
# Prevent form re-submission via browser refresh
return HttpResponseRedirect(
reverse(
'instance-detail',
kwargs={'cluster_slug': cluster_slug, 'instance': instance}
)
)
else:
if 'cdrom_image_path' in instance.hvparams.keys():
if instance.hvparams['cdrom_image_path']:
instance.hvparams['cdrom_type'] = 'iso'
else:
instance.hvparams['cdrom_type'] = 'none'
else:
instance.hvparams['cdrom_type'] = 'none'
if instance.whitelistip:
instance.hvparams['whitelist_ip'] = instance.whitelistip
else:
instance.hvparams['whitelist_ip'] = ''
configform = InstanceConfigForm(instance.hvparams)
instance.cpu_url = reverse(
'graph',
args=(cluster.slug, instance.name, 'cpu-ts')
)
instance.net_url = []
for (nic_i, link) in enumerate(instance.nic_links):
instance.net_url.append(
reverse(
'graph',
args=(cluster.slug, instance.name, 'net-ts', '/eth%s' % nic_i)
)
)
instance.netw = []
try:
instance.osname = get_os_details(
instance.osparams['img_id']).get(
'description', instance.osparams['img_id']
)
except Exception:
try:
instance.osname = instance.osparams['img_id']
except Exception:
instance.osname = instance.os
instance.node_group_locked = instance.pnode in instance.cluster.locked_nodes_from_nodegroup()
for (nic_i, link) in enumerate(instance.nic_links):
if instance.nic_ips[nic_i] is None:
instance.netw.append("%s" % (instance.nic_links[nic_i]))
else:
instance.netw.append("%s@%s" % (
instance.nic_ips[nic_i], instance.nic_links[nic_i])
)
if instance.isolate and instance.whitelistip is None:
djmessages.add_message(
request,
msgs.ERROR,
"Your instance is isolated from the network and" +
" you have not set an \"Allowed From\" address." +
" To access your instance from a specific network range," +
" you can set it via the instance configuration form"
)
if instance.needsreboot:
djmessages.add_message(
request,
msgs.ERROR,
"You have modified one or more of your instance's core " +
"configuration components (any of network adapter, hard" +
" disk type, boot device, cdrom). In order for these changes " +
"to take effect, you need to <strong>Reboot</strong>" +
" your instance.",
extra_tags='safe'
)
ret_dict = {'cluster': cluster,
'instance': instance
}
if not request.user.has_perm('ganeti.view_instances') or (
request.user.is_superuser or
request.user in instance.users or
set.intersection(set(request.user.groups.all()), set(instance.groups))
):
ret_dict['configform'] = configform
return render(
request,
'instances/instance.html',
ret_dict
)
0
Example 111
Project: django-scaffold Source File: admin.py
@csrf_protect_m
@transaction.commit_on_success
def move_view(self, request, object_id):
"""This view allows the user to move sections within the node tree."""
#FIXME: should be an AJAX responder version of this view.
model = self.model
opts = model._meta
try:
obj = self.queryset(request).get(pk=unquote(object_id))
except model.DoesNotExist:
# Don't raise Http404 just yet, because we haven't checked
# permissions. We don't want an unauthenticated user to be able
# to determine whether a given object exists.
obj = None
if not self.has_change_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_(
'%(name)s object with primary key %(key)r does not exist.') % {
'name': force_unicode(opts.verbose_name),
'key': escape(object_id)
})
if request.method == 'POST':
rel = request.POST.get('relationship')
if request.POST.get('to') == 'TOP':
rel_to = obj.get_root_nodes()[0]
rel = 'top'
else:
rel_to = get_object_or_404(model,
pk=request.POST.get('to')
)
if rel_to.pk == obj.pk:
return HttpResponseBadRequest(
"Unable to move node relative to itself."
)
pos_map = {
'top': 'left',
'neighbor': 'right',
'child': 'first-child'
}
if rel not in pos_map.keys():
return HttpResponseBadRequest(
"Position must be one of %s " % ", ".join(pos_map.keys())
)
try:
obj.move(rel_to, pos_map[rel])
except Exception, e:
return HttpResponseServerError("Unable to move node. %s" % e)
else:
if model.find_problems()[4] != []:
model.fix_tree()
# Log that a section has been successfully moved.
change_message = "%s moved." % obj.title
self.log_change(request, obj, change_message)
# Redirect to sections index page.
return self.redirect_to_scaffold_index(request)
# Exclude the node from the list of candidates...
other_secs = model.objects.exclude(pk=object_id)
# ...then exclude descendants of the node being moved.
other_secs = [n for n in other_secs if not n.is_descendant_of(obj)]
# Provides a sections tree for user reference.
def crawl(node):
html_class = node.pk == obj.pk and ' class="active"' or ""
if node.is_leaf():
return "<li%s>%s</li>" % (html_class, node.title)
else:
children = node.get_children()
html = "<li%s>%s<ul>" % (html_class, node.title)
html += "".join(
map(crawl, children)
)
return html + "</ul></li>"
root_nodes = self.model.get_root_nodes()
tree_html = '<ul id="node-list" class="treeview-red">%s</ul>'
tree_html = tree_html % ("".join(map(crawl, root_nodes)))
context = {
'obj': obj,
'tree': other_secs,
'title': "Move %s" % self.app_context['model_label'],
'preview': tree_html
}
return self.render_scaffold_page(request,
"move.html", context
)
0
Example 112
@secure_required
@login_required
@permission_required_or_403('change_profile', (get_profile_model(), 'user__username', 'username'))
def profile_edit(request, username, edit_profile_form=EditProfileForm,
template_name='userena/profile_form.html', success_url=None,
extra_context=None, **kwargs):
"""
Edit profile.
Edits a profile selected by the supplied username. First checks
permissions if the user is allowed to edit this profile, if denied will
show a 404. When the profile is successfully edited will redirect to
``success_url``.
:param username:
Username of the user which profile should be edited.
:param edit_profile_form:
Form that is used to edit the profile. The :func:`EditProfileForm.save`
method of this form will be called when the form
:func:`EditProfileForm.is_valid`. Defaults to :class:`EditProfileForm`
from userena.
:param template_name:
String of the template that is used to render this view. Defaults to
``userena/edit_profile_form.html``.
:param success_url:
Named URL which will be passed on to a django ``reverse`` function after
the form is successfully saved. Defaults to the ``userena_detail`` url.
:param extra_context:
Dictionary containing variables that are passed on to the
``template_name`` template. ``form`` key will always be the form used
to edit the profile, and the ``profile`` key is always the edited
profile.
**Context**
``form``
Form that is used to alter the profile.
``profile``
Instance of the ``Profile`` that is edited.
"""
user = get_object_or_404(get_user_model(), username__iexact=username)
profile = user.get_profile()
user_initial = {'first_name': user.first_name, 'last_name': user.last_name}
form = edit_profile_form(instance=profile, initial=user_initial)
if request.method == 'POST':
form = edit_profile_form(request.POST, request.FILES, instance=profile, initial=user_initial)
if form.is_valid():
profile = form.save(commit=False)
profile.save()
# # go trough all the task categories for this volunteer
# for category in TaskCategory.objects.all():
# exists = VolunteerCategory.objects.filter(volunteer=profile, category=category)
# selected = form.cleaned_data.get('categories').filter(name=category.name)
# # when the category does not exist and was selected, add it
# if not exists and selected:
# profilecategory = VolunteerCategory(volunteer=profile, category=category)
# profilecategory.save()
# # when the category exists and was deselected, delete it
# elif exists and not selected:
# profilecategory = VolunteerCategory.objects.filter(volunteer=profile, category=category)
# profilecategory.delete()
if userena_settings.USERENA_USE_MESSAGES:
messages.success(request, _('Your profile has been updated.'), fail_silently=True)
if success_url:
# Send a signal that the profile has changed
userena_signals.profile_change.send(sender=None, user=user)
redirect_to = success_url
else: redirect_to = reverse('userena_profile_detail', kwargs={'username': username})
return redirect(redirect_to)
if not extra_context: extra_context = dict()
extra_context['form'] = form
extra_context['profile'] = profile
return ExtraContextTemplateView.as_view(template_name=template_name,
extra_context=extra_context)(request)
0
Example 113
Project: eyebrowse-server Source File: views.py
@render_to('stats/profile_viz.html')
def profile_viz(request, username=None):
if request.GET.get("date") is None or request.GET.get("date") == "null":
return redirect_to(request,
"/users/%s/visualizations?date=last week&query=%s" %
(username, request.GET.get("query", "")))
if request.user.is_authenticated():
user = get_object_or_404(User, username=request.user.username)
userprof = UserProfile.objects.get(user=user)
confirmed = userprof.confirmed
if not confirmed:
return redirect('/consent')
else:
user = None
userprof = None
username, follows, profile_user, empty_search_msg, nav_bar = _profile_info(
user, username)
get_dict, query, date, sort, filter = _get_query(request)
logger.info(get_dict)
logger.info(date)
get_dict["orderBy"] = "end_time"
get_dict["direction"] = "hl"
get_dict["filter"] = ""
get_dict["page"] = request.GET.get("page", 1)
get_dict["username"] = profile_user.username
get_dict["sort"] = "time"
hist, history_stream = live_stream_query_manager(get_dict, profile_user)
# stats
tot_time, item_count = profile_stat_gen(profile_user)
fav_data = FavData.objects.get(user=profile_user)
num_history = EyeHistory.objects.filter(user=profile_user).count()
is_online = online_user(user=profile_user)
following_count = profile_user.profile.follows.count()
follower_count = UserProfile.objects.filter(
follows=profile_user.profile).count()
today = datetime.now() - timedelta(hours=24)
day_count = hist.filter(start_time__gt=today
).values('url', 'title'
).annotate(num_urls=Sum('total_time')
).order_by('-num_urls')[:3]
day_domains = hist.filter(
start_time__gt=today
).values('domain'
).annotate(num_domains=Sum('total_time')
).order_by('-num_domains')[:5]
day_chart = {}
for domain in day_domains:
day_chart[domain['domain']] = domain['num_domains']
last_week = today - timedelta(days=7)
week_count = hist.filter(start_time__gt=last_week).values(
'url', 'title'
).annotate(num_urls=Sum('total_time')
).order_by('-num_urls')[:3]
week_domains = hist.filter(
start_time__gt=last_week
).values('domain'
).annotate(num_domains=Sum('total_time')
).order_by('-num_domains')[:5]
week_chart = {}
for domain in week_domains:
week_chart[domain['domain']] = domain['num_domains']
template_dict = {
'visualization': True,
'username': profile_user.username,
'following_count': following_count,
'follower_count': follower_count,
"profile_user": profile_user,
"history_stream": history_stream,
"empty_search_msg": empty_search_msg,
"follows": str(follows),
"is_online": is_online,
"num_history": num_history,
"tot_time": tot_time,
"item_count": item_count,
"fav_data": fav_data,
"query": query,
"date": date,
'day_articles': day_count,
'week_articles': week_count,
'day_chart': json.dumps(day_chart),
'week_chart': json.dumps(week_chart),
}
return _template_values(
request,
page_title="profile history",
navbar=nav_bar,
sub_navbar="subnav_data",
**template_dict)
0
Example 114
def get(self, request, **kwargs):
client = get_object_or_404(Client, id=kwargs.get("client_id"))
loanaccount = get_object_or_404(LoanAccount, id=self.kwargs.get("loanaccount_id"))
receipts_list = Receipts.objects.filter(
client=client,
member_loan_account=loanaccount
).exclude(
demand_loanprinciple_amount_atinstant=0,
demand_loaninterest_amount_atinstant=0
)
try:
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename=' + \
client.first_name + client.last_name + "_ledger.xls"
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet("Ledger")
row_num = 0
columns = [
(u"Date", 1000),
(u"Receipt Number", 1000),
(u"Demand Principal", 2000),
(u"Demand Interest", 2000),
(u"Collection Principal", 2000),
(u"Collection Interest", 2000),
(u"Balance Principal", 2000),
(u"Balance Interest", 2000),
(u"Loan Outstanding", 2000),
]
font_style = xlwt.XFStyle()
font_style.font.bold = True
for col_num in range(len(columns)):
ws.write(row_num, col_num, columns[col_num][0], font_style)
ws.col(col_num).width = columns[col_num][1]
font_style = xlwt.XFStyle()
font_style.alignment.wrap = 1
for receipt in receipts_list:
row_num += 1
if receipt.demand_loanprinciple_amount_atinstant:
var1 = d(receipt.demand_loanprinciple_amount_atinstant)
else:
var1 = 0
if receipt.loanprinciple_amount:
var2 = d(receipt.loanprinciple_amount)
else:
var2 = 0
if var1 > var2:
balance_principle = d(d(var1) - d(var2))
else:
balance_principle = 0
if receipt.demand_loaninterest_amount_atinstant:
var4 = d(receipt.demand_loaninterest_amount_atinstant)
else:
var4 = 0
if receipt.loaninterest_amount:
var5 = d(receipt.loaninterest_amount)
else:
var5 = 0
if var4 > var5:
balance_interest = d(d(var4) - d(var5))
else:
balance_interest = 0
row = [
str(receipt.date),
receipt.receipt_number,
receipt.demand_loanprinciple_amount_atinstant,
receipt.demand_loaninterest_amount_atinstant,
receipt.loanprinciple_amount,
receipt.loaninterest_amount,
balance_principle,
balance_interest,
receipt.principle_loan_balance_atinstant,
]
for col_num in range(len(row)):
ws.write(row_num, col_num, row[col_num], font_style)
wb.save(response)
return response
except Exception as err:
errmsg = "%s" % (err)
return HttpResponse(errmsg)
0
Example 115
@login_required
def view(req, step):
"""Main uploader view"""
upload_session = None
upload_id = req.GET.get('id', None)
if step is None:
if upload_id:
# upload recovery
upload_obj = get_object_or_404(
Upload,
import_id=upload_id,
user=req.user)
session = upload_obj.get_session()
if session:
req.session[upload_id] = session
return _next_step_response(req, session)
step = 'save'
# delete existing session
if upload_id and upload_id in req.session:
del req.session[upload_id]
else:
if not upload_id:
return render_to_response(
"upload/layer_upload_invalid.html",
RequestContext(
req,
{}))
upload_obj = get_object_or_404(Upload, import_id=upload_id, user=req.user)
session = upload_obj.get_session()
if session:
upload_session = session
else:
upload_session = req.session[upload_id]
try:
if req.method == 'GET' and upload_session:
# set the current step to match the requested page - this
# could happen if the form is ajax w/ progress monitoring as
# the advance would have already happened @hacky
upload_session.completed_step = get_previous_step(
upload_session,
step)
resp = _steps[step](req, upload_session)
# must be put back to update object in session
if upload_session:
if step == 'final':
delete_session = True
try:
resp_js = json.loads(resp.content)
delete_session = resp_js.get('status') != 'pending'
except:
pass
if delete_session:
# we're done with this session, wax it
Upload.objects.update_from_session(upload_session)
upload_session = None
del req.session[upload_id]
else:
req.session[upload_id] = upload_session
elif upload_id in req.session:
upload_session = req.session[upload_id]
if upload_session:
Upload.objects.update_from_session(upload_session)
return resp
except BadStatusLine:
logger.exception('bad status line, geoserver down?')
return _error_response(req, errors=[_geoserver_down_error_msg])
except gsimporter.RequestFailed as e:
logger.exception('request failed')
errors = e.args
# http bad gateway or service unavailable
if int(errors[0]) in (502, 503):
errors = [_geoserver_down_error_msg]
return _error_response(req, errors=errors)
except gsimporter.BadRequest as e:
logger.exception('bad request')
return _error_response(req, errors=e.args)
except Exception as e:
return _error_response(req, exception=e)
0
Example 116
Project: airmozilla Source File: views.py
@cache_page(60)
@json_view
@transaction.atomic
def event_data(request, id):
event = get_object_or_404(Event, pk=id)
context = {}
try:
discussion = Discussion.objects.get(event=event)
context['discussion'] = {
'enabled': discussion.enabled,
'moderate_all': discussion.moderate_all,
'closed': discussion.closed,
}
except Discussion.DoesNotExist:
context['discussion'] = {
'enabled': False
}
if not context['discussion']['enabled']:
if request.method == 'POST':
return http.HttpResponseBadRequest("Discussion not enabled")
else:
return context
_can_manage_comments = can_manage_comments(request.user, discussion)
if request.method == 'POST':
if not request.user.is_authenticated():
return http.HttpResponseForbidden(
'Must be signed in'
)
if request.POST.get('approve'):
# but are you allowed?
if not _can_manage_comments:
return http.HttpResponseForbidden(
'Unable to approve comment'
)
comment = get_object_or_404(Comment, pk=request.POST['approve'])
comment.status = Comment.STATUS_APPROVED
comment.save()
if comment.reply_to:
sending.send_reply_notification(comment, request)
return {'ok': True}
if request.POST.get('unapprove'):
# but are you allowed?
if not _can_manage_comments:
return http.HttpResponseForbidden(
'Unable to unapprove comment'
)
comment = get_object_or_404(Comment, pk=request.POST['unapprove'])
comment.status = Comment.STATUS_POSTED
comment.save()
return {'ok': True}
if request.POST.get('remove'):
# but are you allowed?
if not _can_manage_comments:
return http.HttpResponseForbidden(
'Unable to remove comment'
)
comment = get_object_or_404(Comment, pk=request.POST['remove'])
comment.status = Comment.STATUS_REMOVED
comment.save()
return {'ok': True}
if request.POST.get('flag'):
comment = get_object_or_404(Comment, pk=request.POST['flag'])
comment.flagged += 1
comment.save()
return {'ok': True}
if request.POST.get('unflag'):
# but are you allowed?
if not _can_manage_comments:
return http.HttpResponseForbidden(
'Unable to unflag comment'
)
comment = get_object_or_404(Comment, pk=request.POST['unflag'])
comment.flagged = 0
comment.save()
return {'ok': True}
form = forms.CommentForm(request.POST)
if form.is_valid():
if discussion.moderate_all:
status = Comment.STATUS_POSTED
else:
status = Comment.STATUS_APPROVED
new_comment, created = Comment.objects.get_or_create(
event=event,
comment=form.cleaned_data['comment'],
reply_to=form.cleaned_data['reply_to'],
user=request.user,
status=status,
)
if form.cleaned_data['name']:
first_name, last_name = _first_last_name(
form.cleaned_data['name']
)
request.user.first_name = first_name
request.user.last_name = last_name
request.user.save()
if created:
if discussion.moderate_all and _can_manage_comments:
new_comment.status = Comment.STATUS_APPROVED
new_comment.save()
if discussion.moderate_all and discussion.notify_all:
sending.send_moderator_notifications(new_comment, request)
else:
return http.HttpResponseBadRequest(str(form.errors))
comments = Comment.objects.filter(
event=event,
reply_to__isnull=True
)
if request.user.is_authenticated():
query_filter = Q(status=Comment.STATUS_APPROVED) | Q(user=request.user)
if _can_manage_comments:
query_filter = query_filter | Q(status=Comment.STATUS_POSTED)
else:
query_filter = Q(status=Comment.STATUS_APPROVED)
comments = comments.filter(query_filter)
sub_context = {
'comments': comments.order_by('created'),
'discussion': discussion,
'request': request,
'Comment': Comment,
'can_manage_comments': _can_manage_comments,
'root': True,
'query_filter': query_filter,
}
context['html'] = render_to_string(
'comments/comments.html',
sub_context
)
context['can_manage_comments'] = _can_manage_comments
context['latest_comment'] = get_latest_comment(
event,
include_posted=_can_manage_comments
)
return context
0
Example 117
Project: healthsites Source File: views.py
@csrf_exempt
def map(request):
"""View for request."""
if request.user.is_authenticated():
user = get_object_or_404(User, username=request.user)
request.user = get_profile(user)
if request.method == 'POST':
search_query = request.POST.get('q')
option = request.POST.get('option')
if option == 'place':
map_url = reverse('map')
return HttpResponseRedirect(
map_url + "?place=%s" % search_query)
elif option == 'what3words':
locality_values = Value.objects.filter(
specification__attribute__key='what3words').filter(
data=search_query)
if locality_values:
locality_value = locality_values[0]
else:
return render_to_response(
'map.html',
context_instance=RequestContext(request)
)
locality_uuid = locality_value.locality.uuid
map_url = reverse('map')
return HttpResponseRedirect(
map_url + "#!/locality/%s" % locality_uuid)
elif option == 'healthsite':
localities = Locality.objects.filter(
name=search_query)
if len(localities) > 0:
locality = localities[0]
locality_uuid = locality.uuid
map_url = reverse('map')
return HttpResponseRedirect(
map_url + "#!/locality/%s" % locality_uuid)
else:
return render_to_response(
'map.html',
context_instance=RequestContext(request)
)
else:
tag = request.GET.get('tag')
country = request.GET.get('country')
place = request.GET.get('place')
attribute = request.GET.get('attribute')
result = {}
if tag:
result = search_locality_by_tag(tag)
result['tag'] = tag
elif country:
result = get_country_statistic(country)
result['country'] = country
result['polygon'] = Country.objects.get(name__iexact=country).polygon_geometry.geojson
elif place:
result = search_place(request, place)
elif attribute:
uuid = request.GET.get('uuid')
result = search_locality_by_spec_data("attribute", attribute, uuid)
result['attribute'] = {'attribute': attribute, 'uuid': uuid, 'name': result['locality_name'],
'location': result['location']}
elif len(request.GET) == 0:
result = search_place(request, place)
else:
uuid = request.GET.get('uuid')
for item in request.GET:
if item != "uuid":
spec = item
data = request.GET.get(item)
result = search_locality_by_spec_data(spec, data, uuid)
result['spec'] = {'spec': spec, 'data': data, 'uuid': uuid, 'name': result['locality_name'],
'location': result['location']}
if 'new_geom' in request.session:
result["new_geom"] = request.session['new_geom']
del request.session['new_geom']
return render_to_response(
'map.html',
result,
context_instance=RequestContext(request)
)
0
Example 118
Project: kuma Source File: views.py
@require_POST
@permission_required('users.add_userban')
def ban_user_and_cleanup_summary(request, username):
"""
A summary page of actions taken when banning a user and reverting revisions
This method takes all the revisions from the last three days,
sends back the list of revisions that were successfully reverted/deleted
and submitted to Akismet, and also a list of
revisions where no action was taken (revisions needing follow up).
"""
user = get_object_or_404(User, username=username)
# Is this user already banned?
user_ban = UserBan.objects.filter(user=user, is_active=True)
# If the user is not banned, ban user; else, update 'by' and 'reason'
if not user_ban.exists():
ban = UserBan(user=user,
by=request.user,
reason='Spam',
is_active=True)
ban.save()
else:
user_ban.update(by=request.user, reason='Spam')
date_three_days_ago = datetime.now().date() - timedelta(days=3)
revisions_from_last_three_days = user.created_revisions.prefetch_related('docuement')
revisions_from_last_three_days = revisions_from_last_three_days.defer('content', 'summary').order_by('-id')
revisions_from_last_three_days = revisions_from_last_three_days.filter(created__gte=date_three_days_ago)
""" The "Actions Taken" section """
# The revisions to be submitted to Akismet and reverted,
# these must be sorted descending so that they are reverted accordingly
revisions_to_mark_as_spam_and_revert = revisions_from_last_three_days.filter(
id__in=request.POST.getlist('revision-id')).order_by('-id')
# 1. Submit revisions to Akismet as spam
# 2. If this is the most recent revision for a docuement:
# Revert revision if it has a previous version OR
# Delete revision if it is a new docuement
submitted_to_akismet = []
not_submitted_to_akismet = []
revisions_reverted_list = []
revisions_not_reverted_list = []
revisions_deleted_list = []
revisions_not_deleted_list = []
latest_is_not_spam = [
rev for rev in revision_by_distinct_doc(revisions_to_mark_as_spam_and_revert)
if rev.docuement.current_revision != rev
]
previous_good_rev = {}
for revision in revisions_to_mark_as_spam_and_revert:
submission = RevisionAkismetSubmission(sender=request.user, type="spam")
akismet_submission_data = {'revision': revision.id}
data = RevisionAkismetSubmissionSpamForm(
data=akismet_submission_data,
instance=submission,
request=request)
# Submit to Akismet or note that validation & sending to Akismet failed
if data.is_valid():
data.save()
# Since we only want to display 1 revision per docuement, only add to
# this list if this is one of the revisions for a distinct docuement
submitted_to_akismet.append(revision)
else:
not_submitted_to_akismet.append(revision)
# If there is a current revision and the revision is not in the spam list,
# to be reverted, do not revert any revisions
try:
revision.docuement.refresh_from_db(fields=['current_revision'])
except Docuement.DoesNotExist:
continue # This docuement was previously deleted in this loop, continue
if revision.docuement.current_revision not in revisions_to_mark_as_spam_and_revert:
if revision.docuement_id not in previous_good_rev:
previous_good_rev[revision.docuement_id] = revision.docuement.current_revision
continue # This docuement has a more current revision, no need to revert
# Loop through all previous revisions to find the oldest spam
# revision on a specific docuement from this request.
while revision.previous in revisions_to_mark_as_spam_and_revert:
revision = revision.previous
# If this is a new revision on an existing docuement, revert it
if revision.previous:
previous_good_rev[revision.docuement_id] = revision.previous
reverted = revert_docuement(request=request,
revision_id=revision.previous.id)
if reverted:
revisions_reverted_list.append(revision)
else:
# If the revert was unsuccessful, include this in the follow-up list
revisions_not_reverted_list.append(revision)
# If this is a new docuement/translation, delete it
else:
deleted = delete_docuement(request=request,
docuement=revision.docuement)
if deleted:
revisions_deleted_list.append(revision)
else:
# If the delete was unsuccessful, include this in the follow-up list
revisions_not_deleted_list.append(revision)
# Find just the latest revision for each docuement
submitted_to_akismet_by_distinct_doc = revision_by_distinct_doc(submitted_to_akismet)
not_submitted_to_akismet_by_distinct_doc = revision_by_distinct_doc(not_submitted_to_akismet)
revisions_reverted_by_distinct_doc = revision_by_distinct_doc(revisions_reverted_list)
revisions_not_reverted_by_distinct_doc = revision_by_distinct_doc(revisions_not_reverted_list)
revisions_deleted_by_distinct_doc = revision_by_distinct_doc(revisions_deleted_list)
revisions_not_deleted_by_distinct_doc = revision_by_distinct_doc(revisions_not_deleted_list)
actions_taken = {
'revisions_reported_as_spam': submitted_to_akismet_by_distinct_doc,
'revisions_reverted_list': revisions_reverted_by_distinct_doc,
'revisions_deleted_list': revisions_deleted_by_distinct_doc
}
""" The "Needs followup" section """
# TODO: Phase V: If user made actions while reviewer was banning them
new_action_by_user = []
skipped_revisions = [rev for rev in revisions_to_mark_as_spam_and_revert
if rev.docuement_id in previous_good_rev and
rev.id < previous_good_rev[rev.docuement_id].id]
skipped_revisions = revision_by_distinct_doc(skipped_revisions)
needs_follow_up = {
'manual_revert': new_action_by_user,
'skipped_revisions': skipped_revisions,
'not_submitted_to_akismet': not_submitted_to_akismet_by_distinct_doc,
'not_reverted_list': revisions_not_reverted_by_distinct_doc,
'not_deleted_list': revisions_not_deleted_by_distinct_doc
}
""" The "No Actions Taken" section """
revisions_already_spam = revisions_from_last_three_days.filter(
id__in=request.POST.getlist('revision-already-spam')
)
revisions_already_spam = list(revisions_already_spam)
revisions_already_spam_by_distinct_doc = revision_by_distinct_doc(revisions_already_spam)
identified_as_not_spam = [rev for rev in revisions_from_last_three_days
if rev not in revisions_already_spam and
rev not in revisions_to_mark_as_spam_and_revert]
identified_as_not_spam_by_distinct_doc = revision_by_distinct_doc(identified_as_not_spam)
no_actions_taken = {
'latest_revision_is_not_spam': latest_is_not_spam,
'revisions_already_identified_as_spam': revisions_already_spam_by_distinct_doc,
'revisions_identified_as_not_spam': identified_as_not_spam_by_distinct_doc
}
context = {'detail_user': user,
'form': UserBanForm(),
'actions_taken': actions_taken,
'needs_follow_up': needs_follow_up,
'no_actions_taken': no_actions_taken}
# Send an email to the spam watch mailing list.
ban_and_revert_notification(user, request.user, context)
return render(request,
'users/ban_user_and_cleanup_summary.html',
context)
0
Example 119
Project: ocf Source File: views.py
def aggregate_crud(request, agg_id=None):
'''
Create/update an OpenFlow Aggregate.
'''
if agg_id != None:
aggregate = get_object_or_404(OpenFlowAggregate, pk=agg_id)
client = aggregate.client
else:
aggregate = None
client = None
if request.method == "GET":
agg_form = OpenFlowAggregateForm(instance=aggregate)
client_form = PasswordXMLRPCServerProxyForm(instance=client)
elif request.method == "POST":
logger.debug("aggregate_crud got post")
agg_form = OpenFlowAggregateForm(
data=request.POST, instance=aggregate)
client_form = PasswordXMLRPCServerProxyForm(
data=request.POST, instance=client)
logger.debug("Validating")
if client_form.is_valid() and agg_form.is_valid():
logger.debug("Forms are valid")
logger.debug("Got logo %s" % request.POST.get("logo", ""))
# Save the client first
client = client_form.save()
# Then save the aggregate and add the client
aggregate = agg_form.save(commit=False)
aggregate.client = client
aggregate.save()
agg_form.save_m2m()
try:
info = aggregate.client.proxy.get_am_info()
aggregate.vlan_auto_assignment = info["vlan_auto_assignment"]
aggregate.flowspace_auto_approval = info["flowspace_auto_approval"]
except Exception as e:
# logger.debug("Aggregate %s: could not check automatic resource assignment" % str(aggregate.name))
pass
try:
err = ' '
aggregate.client.proxy.checkFlowVisor()
aggregate.setup_new_aggregate(request.build_absolute_uri("/"))
except Exception as e:
err = str(e)
if err is not ' ':
#transaction.rollback()
if "check_fv_set" in err:
msg_type = DatedMessage.TYPE_WARNING
if agg_id:
flowvisor_msg = "Topology could not be updated because could not connect to FlowVisor."
else:
flowvisor_msg = "New Aggregate set, but there is no FlowVisor connected to it."
else:
flowvisor_msg = err
msg_type = DatedMessage.TYPE_ERROR
DatedMessage.objects.post_message_to_user(
flowvisor_msg, user=request.user, msg_type=msg_type,
)
return HttpResponseRedirect("/")
aggregate.save()
give_permission_to(
"can_use_aggregate",
aggregate,
request.user,
can_delegate=True
)
give_permission_to(
"can_edit_aggregate",
aggregate,
request.user,
can_delegate=True
)
DatedMessage.objects.post_message_to_user(
"Successfully created/updated aggregate %s. %s" % (aggregate.name,err),
user=request.user, msg_type=DatedMessage.TYPE_SUCCESS,
)
return HttpResponseRedirect(reverse("openflow_aggregate_add_links", args=[aggregate.id]))
logger.debug("Validation failed")
else:
return HttpResponseNotAllowed("GET", "POST")
available = aggregate.check_status() if agg_id else False
return simple.direct_to_template(
request,
template="openflow_aggregate_crud.html",
extra_context={
"agg_form": agg_form,
"client_form": client_form,
"create": not agg_id,
"aggregate": aggregate,
"available": available,
"breadcrumbs": (
('Home', reverse("home")),
("%s OpenFlow Aggregate" % ("Update" if agg_id else "Add"),
request.path),
)
},
)
0
Example 120
Project: moztrap Source File: views.py
@never_cache
@permission_required("execution.execute")
@lists.finder(RunTestsFinder)
@lists.filter("runcaseversions", filterset_class=RunTestsRunCaseVersionFilterSet)
@lists.sort("runcaseversions", defaultfield="order")
@ajax("runtests/list/_runtest_list.html")
def run(request, run_id, env_id):
run = get_object_or_404(model.Run.objects.select_related("product"), pk=run_id)
if not run.status == model.Run.STATUS.active:
messages.info(
request,
"That test run is currently not open for testing. "
"Please select a different test run.")
return redirect("runtests")
# if the environment specified in the URL doesn't exist for this run,
# then ask the user to specify one that does.
try:
environment = run.environments.get(pk=env_id)
except model.Environment.DoesNotExist:
return redirect("runtests_environment", run_id=run_id)
if request.method == "POST":
# Based on this action, create a new Result object with the values we
# get from the post.
prefix = "action-"
while True:
rcv = None
try:
action, rcv_id = [
(k[len(prefix):], int(v)) for k, v in request.POST.items()
if k.startswith(prefix)
][0]
except IndexError:
break
try:
defaults = ACTIONS[action].copy()
except KeyError:
messages.error(
request, "{0} is not a valid action.".format(action))
break
try:
rcv = run.runcaseversions.get(pk=rcv_id)
except model.RunCaseVersion.DoesNotExist:
messages.error(
request,
"{0} is not a valid run/caseversion ID.".format(rcv_id))
break
# take the values out of the POST so we can pass them in to the
# method call on the Result object
for argname in defaults.keys():
try:
defaults[argname] = request.POST[argname]
except KeyError:
pass
# put the values specific to this run
defaults.update({
"environment": environment,
"user": request.user,
})
getattr(rcv, action)(**defaults)
break
if request.is_ajax():
# if we don't know the runcaseversion id, we return an empty
# response.
if rcv is None:
return HttpResponse(
json.dumps({"html": "", "no_replace": True}),
content_type="application/json",
)
# by not returning a TemplateResponse, we skip the sort and finder
# decorators, which aren't applicable to a single case.
return render(
request,
"runtests/list/_runtest_list_item.html",
{
"environment": environment,
"runcaseversion": rcv,
"run": run
}
)
else:
return redirect(request.get_full_path())
envform = EnvironmentSelectionForm(
current=environment.id, environments=run.environments.all())
current_result_select = (
"SELECT status from execution_result as r "
"WHERE r.runcaseversion_id = execution_runcaseversion.id "
"AND r.environment_id = {0} "
"AND r.status not in ({1}) "
"AND r.is_latest = 1 "
"ORDER BY r.created_on DESC LIMIT 1".format(
environment.id,
", ".join(
["'{0}'".format(x) for x in model.Result.PENDING_STATES]
)))
return TemplateResponse(
request,
"runtests/run.html",
{
"environment": environment,
"product": run.productversion.product,
"productversion": run.productversion,
"run": run,
"envform": envform,
"runcaseversions": run.runcaseversions.select_related(
"caseversion__case",
).prefetch_related(
"caseversion__tags",
"caseversion__attachments",
"caseversion__steps",
).filter(
environments=environment,
).extra(select={
"current_result": current_result_select}),
"finder": {
# finder decorator populates top column (products), we
# prepopulate the other two columns
"productversions": model.ProductVersion.objects.filter(
product=run.productversion.product),
"runs": model.Run.objects.order_by("name").filter(
productversion=run.productversion,
status=model.Run.STATUS.active),
},
}
)
0
Example 121
Project: soclone Source File: views.py
def edit_answer(request, answer_id):
"""Edits an Answer."""
answer = get_object_or_404(Answer, id=answer_id)
if not auth.can_edit_post(request.user, answer):
raise Http404
latest_revision = answer.get_latest_revision()
preview = None
revision_form = None
if request.method == 'POST':
if 'select_revision' in request.POST:
# The user submitted to change the revision to start editing from
revision_form = RevisionForm(answer, latest_revision, request.POST)
if revision_form.is_valid():
# Replace Question details with those from the selected revision
form = EditAnswerForm(answer,
AnswerRevision.objects.get(answer=answer,
revision=revision_form.cleaned_data['revision']))
else:
# Make sure we keep a hold of the user's other input, even
# though they appear to be messing about.
form = EditAnswerForm(answer, latest_revision, request.POST)
else:
# Always check modifications against the latest revision
form = EditAnswerForm(answer, latest_revision, request.POST)
if form.is_valid():
html = sanitize_html(
markdowner.convert(form.cleaned_data['text']))
if 'preview' in request.POST:
# The user submitted to preview the formatted question
preview = mark_safe(html)
elif 'submit' in request.POST:
if form.has_changed():
edited_at = datetime.datetime.now()
# Update the Answer itself
updated_fields = {
'last_edited_at': edited_at,
'last_edited_by': request.user,
'html': html,
}
if ('wiki' in form.cleaned_data and
form.cleaned_data['wiki']):
updated_fields['wiki'] = True
updated_fields['wikified_at'] = edited_at
Answer.objects.filter(
id=answer.id).update(**updated_fields)
# Create a new revision
revision = AnswerRevision(
answer = answer,
author = request.user,
revised_at = edited_at,
text = form.cleaned_data['text']
)
if form.cleaned_data['summary']:
revision.summary = form.cleaned_data['summary']
else:
revision.summary = \
diff.generate_answer_revision_summary(
latest_revision, revision,
('wiki' in updated_fields))
revision.save()
# TODO 5 body edits by the asker = automatic wiki mode
# TODO 4 individual editors = automatic wiki mode
# TODO Badges related to editing Answers
return HttpResponseRedirect(answer.get_absolute_url())
else:
revision_form = RevisionForm(answer, latest_revision)
form = EditAnswerForm(answer, latest_revision)
if revision_form is None:
# We're about to redisplay after a POST where we didn't care which
# revision was selected - make sure the revision the user started from
# is still selected on redisplay.
revision_form = RevisionForm(answer, latest_revision, request.POST)
return render_to_response('edit_answer.html', {
'title': u'Edit Answer',
'question': answer.question,
'answer': answer,
'revision_form': revision_form,
'form': form,
'preview': preview,
}, context_instance=RequestContext(request))
0
Example 122
Project: ionyweb Source File: page.py
def post(self, request, pk):
"""
Modify the page
"""
# Get page which is currently updated
page = get_object_or_404(request.website.pages, pk=pk)
# Saving url of current page
old_url_current_page = request.page.get_absolute_url()
# Settings Refresh
refresh_manager = False
refresh_page = False
msg_user = None
# ----------------------
# Moving Page Management
# ----------------------
if 'move' in request.POST:
if 'previous' in request.POST:
page_top = get_object_or_404(request.website.pages, pk=request.POST['previous'])
page.move_to(page_top, 'right')
else:
if 'next' in request.POST:
page_top = get_object_or_404(request.website.pages, pk=request.POST['next'])
page.move_to(page_top, 'left')
else:
if 'parent' in request.POST:
page_top = get_object_or_404(request.website.pages, pk=request.POST['parent'])
page.move_to(page_top, 'first-child')
# We save updates.
page.save()
# Ask refresh manager
refresh_manager = True
# Messgae fo user
msg_user = MESSAGES.get('items_move_success', '')
# ----------------------
# Settings page as draft
# ----------------------
elif 'draft' in request.POST:
page.draft = not page.draft
page.save()
refresh_manager = True
msg_user = MESSAGES.get('page_draft_toggle', '')
# ----------------------
# Updating settings page
# ----------------------
else:
# Get POST values
post_values = request.POST.copy()
post_values['website'] = request.website.id
# Creation of form
form = PageWAForm(post_values, instance=page)
if form.is_valid():
page = form.save()
# We ask content updating
if page == request.page:
refresh_page = True
# Message for user
msg_user = MESSAGES.get('app_edit_success', '')
else:
# We reload the edit form with errors
content = render_to_string('administration/page/page-edit.html',
{'form': form,
'page': page},
context_instance = RequestContext(request))
response = Response(status.HTTP_203_NON_AUTHORITATIVE_INFORMATION,
{"html": content,
"msg": MESSAGES.get('default_error', "")})
return self.render(response)
# ---------------
# Refresh Website
# ---------------
# Update cache for current page displayed.
request.page = get_object_or_404(request.website.pages, pk=request.page.id)
# Check if we need reload current page
# if current url changed or refresh content asked.
new_url_current_page = request.page.get_absolute_url()
if old_url_current_page != new_url_current_page or refresh_page:
response = Response(status.HTTP_202_ACCEPTED,
{'location': new_url_current_page})
return self.render(response)
# Else we refresh only page manager and navigation.
# Page manager:
if refresh_manager:
pages_list = request.website.pages.all()
page_manager_html = render_to_string('administration/page/page-list.html',
{'pages': pages_list,},
context_instance = RequestContext(request))
else:
page_manager_html = None
navigation_html = RenderingContext(request).html_navigation
# Response
response = Response(status.HTTP_200_OK,
{"manager_html": page_manager_html,
"navigation_html": navigation_html,
# "page_html": page_content_html,
"msg": msg_user})
return self.render(response)
0
Example 123
Project: ocf Source File: views.py
def flowspace(request, slice_id, fsmode = 'advanced', free_vlan = None, alertMessage=""):
"""
Add flowspace.
"""
slice = get_object_or_404(Slice, id=slice_id)
class SliverMultipleChoiceField(forms.ModelMultipleChoiceField):
def label_from_instance(self, obj):
return "%s" % obj.resource.as_leaf_class()
def widget_attrs(self, widget):
return {"class": "wide"}
def formfield_callback(f):
if f.name == "slivers":
return SliverMultipleChoiceField(
queryset=OpenFlowInterfaceSliver.objects.filter(slice=slice),
initial=OpenFlowInterfaceSliver.objects.filter(slice=slice))
else:
return f.formfield()
if request.method == "POST":
continue_to_start_slice = False
# No extra forms apart from the one being shown
flowspace_form_number = 0
if fsmode == 'failed':
# If an exception was risen from the previous step, the flowspace needs to be requested here
flowspace_form_number = 1
# create a formset to handle all flowspaces
FSFormSet = forms.models.modelformset_factory(
model=FlowSpaceRule,
formfield_callback=formfield_callback,
can_delete=True,
extra=flowspace_form_number,
)
# Default formset
formset = FSFormSet(
queryset=FlowSpaceRule.objects.filter(
slivers__slice=slice).distinct(),
)
if formset.is_valid():
formset.save()
if fsmode == 'advanced':
formset = FSFormSet(
request.POST,
queryset=FlowSpaceRule.objects.filter(
slivers__slice=slice).distinct(),
)
if formset.is_valid():
formset.save()
continue_to_start_slice = True
elif fsmode == 'simple':
#create a simple flowspacerule containing only the vlans tags and the OF ports
try:
#create_simple_slice_vlan_based(free_vlan[0], slice)
create_slice_with_vlan_range(slice, free_vlan)
continue_to_start_slice = True
except:
#continue_to_start_slice flag will deal with this
pass
if continue_to_start_slice:
slice_save_start(request, slice_id)
if fsmode == 'simple':
return HttpResponseRedirect(reverse("slice_detail", args=[slice_id]))
else:
return HttpResponseRedirect(request.path)
elif request.method == "GET":
flowspace_form_contents = FlowSpaceRule.objects.filter(slivers__slice=slice).distinct()
flowspace_form_number = 1
# When coming from the OpenFlow switches topology selection page...
if "HTTP_REFERER" in request.META:
# Checks if the referer page is the topology selcetion
if reverse("book_openflow", args=[slice_id]) in request.META['HTTP_REFERER']:
# If no flowspace has been selected yet, show an extra form to allow user to choose at least one
if not flowspace_form_contents:
flowspace_form_number = 1 # Show an extra (1) form besides the already selected one
# Otherwise, when there is some already requested flowspace, show only the requested ones (no extra forms)
else:
flowspace_form_number = 0 # No extra forms apart from the one(s) being shown
# Redefine formset to handle all flowspaces
# Extra: field that determines how many extra flowspaces there are
FSFormSet = forms.models.modelformset_factory(
model=FlowSpaceRule,
formfield_callback=formfield_callback,
can_delete=True,
extra=flowspace_form_number, # Show number of forms according to origin path request and so on
)
formset = FSFormSet(
queryset=flowspace_form_contents,
)
else:
return HttpResponseNotAllowed("GET", "POST")
done = PlanetLabSliver.objects.filter(slice=slice).count() == 0
return simple.direct_to_template(
request,
template="openflow_select_flowspace.html",
extra_context={
"slice": slice,
"fsformset": formset,
"alertMessage":alertMessage,
"done": done,
"breadcrumbs": (
("Home", reverse("home")),
("Project %s" % slice.project.name, reverse("project_detail", args=[slice.project.id])),
("Slice %s" % slice.name, reverse("slice_detail", args=[slice_id])),
("Choose Flowspace", reverse("flowspace", args=[slice_id])),
),
},
)
0
Example 124
Project: django-rubberstamp Source File: views.py
def type_perms(request, app, code, target_app, target_model, obj_pk=None):
"""
Takes the same arguments as ``object_list``, but returns a form to specify
users and groups to assign/unassign the given permission to.
Also accepts an optional argument, the primary key of an object of the
given type; if given, then the permissions will be assigned for that
specific object instead of the type.
Renders the template ``'rubberstamp/type_perms.html'``, with context
containing the following:
* ``perm``, the `AppPermission` instance
* ``type``, the `ContentType` of the objects
* ``assign_form``, a Django form to select users and groups
If an object is specific, the context will also include:
* ``object``, the object
"""
target_ct = get_object_or_404(
ContentType, app_label=target_app, model=target_model)
perm = get_object_or_404(AppPermission,
app_label=app, codename=code, content_types=target_ct)
TargetClass = target_ct.model_class()
if obj_pk:
obj = get_object_or_404(TargetClass, pk=obj_pk)
else:
obj = None
perm_name = '%s.%s.%s.%s' % (app, code, target_app, target_model)
perm_filter = {
'permission': perm,
'content_type': target_ct,
'object_id': obj_pk
}
perms = AssignedPermission.objects.filter(
**perm_filter).select_related('user', 'group')
current_users = set(User.objects.filter(
id__in=perms.filter(user__isnull=False).values_list('user')))
current_groups = set(Group.objects.filter(
id__in=perms.filter(group__isnull=False).values_list('group')))
initial = {
'users': list(current_users),
'groups': list(current_groups)
}
if request.method == 'POST':
assign_form = PermissionAssignForm(request.POST, initial=initial)
if assign_form.is_valid():
selected_users = set(assign_form.cleaned_data['users'])
selected_groups = set(assign_form.cleaned_data['groups'])
for user in selected_users - current_users:
AppPermission.objects.assign(perm_name, user, obj=obj)
for group in selected_groups - current_groups:
AppPermission.objects.assign(perm_name, group, obj=obj)
for user in current_users - selected_users:
AppPermission.objects.remove(perm_name, user, obj=obj)
for group in current_groups - selected_groups:
AppPermission.objects.remove(perm_name, group, obj=obj)
else:
assign_form = PermissionAssignForm(initial=initial)
context_dict = {
'perm': perm,
'type': target_ct,
'assign_form': assign_form,
}
if obj:
context_dict['object'] = obj
return render_to_response(
'rubberstamp/type_perms.html',
context_dict,
RequestContext(request)
)
0
Example 125
Project: synnefo Source File: im.py
@transaction.commit_on_success
@require_http_methods(["GET", "POST"])
@cookie_fix
def signup(request, template_name='im/signup.html', on_success='index',
extra_context=None, activation_backend=None):
"""
Allows a user to create a local account.
In case of GET request renders a form for entering the user information.
In case of POST handles the signup.
The user activation will be delegated to the backend specified by the
``activation_backend`` keyword argument if present, otherwise to the
``astakos.im.activation_backends.InvitationBackend`` if
settings.ASTAKOS_INVITATIONS_ENABLED is True or
``astakos.im.activation_backends.SimpleBackend`` if not (see
activation_backends);
Upon successful user creation, if ``next`` url parameter is present the
user is redirected there otherwise renders the same page with a success
message.
On unsuccessful creation, renders ``template_name`` with an error message.
**Arguments**
``template_name``
A custom template to render. This is optional;
if not specified, this will default to ``im/signup.html``.
``extra_context``
An dictionary of variables to add to the template context.
``on_success``
Resolvable view name to redirect on registration success.
**Template:**
im/signup.html or ``template_name`` keyword argument.
"""
extra_context = extra_context or {}
if request.user.is_authenticated():
logger.info("%s already signed in, redirect to index",
request.user.log_display)
return HttpResponseRedirect(reverse('index'))
provider = get_query(request).get('provider', 'local')
try:
auth.get_provider(provider)
except auth.InvalidProvider, e:
messages.error(request, e.message)
return HttpResponseRedirect(reverse("signup"))
if not auth.get_provider(provider).get_create_policy:
logger.error("%s provider not available for signup", provider)
raise PermissionDenied
instance = None
# user registered using third party provider
third_party_token = request.REQUEST.get('third_party_token', None)
unverified = None
pending = None
if third_party_token:
# retreive third party entry. This was created right after the initial
# third party provider handshake.
pending = get_object_or_404(PendingThirdPartyUser,
token=third_party_token)
provider = pending.provider
# clone third party instance into the corresponding AstakosUser
instance = pending.get_user_instance()
get_unverified = AstakosUserAuthProvider.objects.unverified
# check existing unverified entries
unverified = get_unverified(pending.provider,
identifier=pending.third_party_identifier)
get_verified = AstakosUserAuthProvider.objects.verified
verified = get_verified(pending.provider,
identifier=pending.third_party_identifier)
if verified:
# an existing verified user already exists for the third party
# identifier
pending.delete()
raise Http404
if unverified and request.method == 'GET':
messages.warning(request, unverified.get_pending_registration_msg)
# prepare activation backend based on current request
if not activation_backend:
activation_backend = activation_backends.get_backend()
form_kwargs = {'instance': instance, 'request': request}
if third_party_token:
form_kwargs['third_party_token'] = third_party_token
if pending:
form_kwargs['initial'] = {
'first_name': pending.first_name,
'last_name': pending.last_name,
'email': pending.email
}
form = activation_backend.get_signup_form(
provider, None, **form_kwargs)
if request.method == 'POST':
form = activation_backend.get_signup_form(
provider,
request.POST,
**form_kwargs)
if form.is_valid():
user = form.create_user()
result = activation_backend.handle_registration(user)
if result.status == \
activation_backend.Result.PENDING_MODERATION:
# user should be warned that his account is not active yet
status = messages.WARNING
else:
status = messages.SUCCESS
message = result.message
activation_backend.send_result_notifications(result, user)
# commit user entry
transaction.commit()
if user and user.is_active:
# activation backend directly activated the user
# log him in
next = request.POST.get('next', '')
response = prepare_response(request, user, next=next)
return response
messages.add_message(request, status, message)
return HttpResponseRedirect(reverse(on_success))
ldap_login_form = None
if 'ldap' in settings.IM_MODULES:
ldap_login_form = LDAPLoginForm(request)
return render_response(
template_name,
login_form=ldap_login_form,
signup_form=form,
third_party_token=third_party_token,
provider=provider,
context_instance=get_context(request, extra_context))
0
Example 126
Project: lava-server Source File: images.py
@BreadCrumb("{name}", parent=image_report_list, needs=['name'])
def image_report_detail(request, name):
image = get_object_or_404(Image, name=name)
from dashboard_app.filters import get_filter_testruns
test_runs = get_filter_testruns(request.user, image.filter)
build_number_to_cols = {}
test_run_names = set()
for test_run in test_runs:
name = test_run.test.test_id
denorm = test_run.denormalization
if denorm.count_fail == 0:
cls = 'present pass'
else:
cls = 'present fail'
bug_links = sorted([b.bug_link for b in test_run.bug_links.all()])
measurements = [{'measurement': str(item.measurement)}
for item in test_run.test_results.all()]
if not hasattr(test_run, 'build_number'):
test_run.build_number = str(test_run.bundle.uploaded_on)
test_run_data = dict(
present=True,
cls=cls,
uuid=test_run.analyzer_assigned_uuid,
passes=denorm.count_pass,
total=denorm.count_pass + denorm.count_fail,
link=test_run.get_permalink(),
bug_links=bug_links,
measurements=measurements,
)
if (test_run.build_number, test_run.bundle.uploaded_on) not in build_number_to_cols:
build_number_to_cols[(test_run.build_number, test_run.bundle.uploaded_on)] = {
'test_runs': {},
'number': str(test_run.build_number),
'date': str(test_run.bundle.uploaded_on),
'link': test_run.bundle.get_absolute_url(),
}
build_number_to_cols[(test_run.build_number, test_run.bundle.uploaded_on)]['test_runs'][name] = test_run_data
if name != 'lava':
test_run_names.add(name)
test_run_names = sorted(test_run_names)
test_run_names.insert(0, 'lava')
cols = [c for n, c in sorted(build_number_to_cols.items())]
table_data = {}
for test_run_name in test_run_names:
row_data = []
for col in cols:
test_run_data = col['test_runs'].get(test_run_name)
if not test_run_data:
test_run_data = dict(
present=False,
cls='missing',
)
row_data.append(test_run_data)
table_data[test_run_name] = row_data
template = loader.get_template("dashboard_app/image-report.html")
return HttpResponse(template.render(
{
'bread_crumb_trail': BreadCrumbTrail.leading_to(
image_report_detail, name=image.name),
'image': image,
'chart_data': json.dumps(table_data),
'test_names': json.dumps(test_run_names),
'columns': json.dumps(cols),
}, request=request))
0
Example 127
Project: karaage Source File: views.py
@usage_required
def index(request, machine_category_id):
machine_category = get_object_or_404(
MachineCategory, pk=machine_category_id)
mc_list = MachineCategory.objects.exclude(id__exact=machine_category_id)
result = progress(request)
if result is not None:
return result
start, end = get_date_range(request)
result = gen_cache_for_machine_category(
request, start, end, machine_category)
if result is not None:
return render(
template_name='kgusage/progress.html',
context={'task_id': result.task_id},
request=request)
show_zeros = True
institute_list = Institute.active.all()
i_list = []
m_list = []
mc_cache = usage.get_machine_category_usage(machine_category, start, end)
total = mc_cache.cpu_time
total_jobs = mc_cache.no_jobs
available_time = mc_cache.available_time
total_time = ((end - start).days + 1) * 24 * 60 * 60
avg_cpus = available_time / total_time
for m_cache in models.MachineCache.objects.filter(
machine__category=machine_category,
date=datetime.date.today(), start=start, end=end):
m = m_cache.machine
time = m_cache.cpu_time
jobs = m_cache.no_jobs
m_list.append({'machine': m, 'usage': time, 'jobs': jobs})
for i_cache in models.InstituteCache.objects.filter(
machine_category=machine_category,
date=datetime.date.today(), start=start, end=end):
i = i_cache.institute
time = i_cache.cpu_time
jobs = i_cache.no_jobs
try:
quota = InstituteQuota.objects.get(
institute=i, machine_category=machine_category)
display_quota = quota.quota
except InstituteQuota.DoesNotExist:
display_quota = None
if display_quota is None and time == 0 and jobs == 0:
continue
data_row = {
'institute': i,
'usage': time,
'jobs': jobs,
'quota': display_quota
}
if available_time != 0:
data_row['percent'] = Decimal(time) / Decimal(available_time) * 100
else:
data_row['percent'] = 0
if data_row['quota'] is not None:
if data_row['quota'] != 0:
data_row['p_used'] = (data_row['percent'] /
data_row['quota']) * 100
else:
data_row['p_used'] = None
data_row['diff'] = data_row['percent'] - data_row['quota']
if data_row['diff'] <= 0:
data_row['class'] = 'green'
else:
data_row['class'] = 'red'
else:
data_row['class'] = 'green'
data_row['diff'] = None
data_row['p_used'] = None
i_list.append(data_row)
# Unused Entry
unused = {'usage': available_time - total, 'quota': 0}
if available_time != 0:
unused['percent'] = (unused['usage'] / available_time) * 100
else:
unused['percent'] = 0
unused['diff'] = unused['percent'] - unused['quota'] / 100
if unused['diff'] <= 0:
unused['class'] = 'green'
else:
unused['class'] = 'red'
if available_time != 0:
utilization = (Decimal(total) / available_time) * 100
else:
utilization = 0
institutes_graph = graphs.get_institute_graph_url(
start, end, machine_category)
machines_graph = graphs.get_machine_graph_url(
start, end, machine_category)
trend_graph = graphs.get_trend_graph_url(
start, end, machine_category)
return render(
template_name='kgusage/usage_institute_list.html',
context=locals(),
request=request)
0
Example 128
@login_required
def timeline(request, gid, pid):
"""
TODO:
- Clean up: flake8 and flow control improvements
- Extend Historical Events to include 19th Century and before
- Balance events so they don't crowd together
- Comments
"""
person = get_object_or_404(Person, gedcom_id=gid, pointer=pid)
now = datetime.now().year
# Don't show timelines for people without valid birth dates.
if not valid_event_date(person.birth) or \
(not valid_event_date(person.death) and
(now - person.birth.date.year > 100)):
return HttpResponse('{"events": []}', content_type="application/json")
start_date = person.birth.date.year
events = [
{
'text': 'born',
'year': start_date,
'type': 'personal'
}
]
if person.spousal_families.exists():
for family in person.spousal_families.iterator():
if valid_event_date(family.joined):
events.append({
'text': 'married',
'year': family.joined.date.year,
'type': 'personal'
})
if valid_event_date(family.separated):
events.append({
'text': 'divorced',
'year': family.separated.date.year,
'type': 'personal'
})
for child in family.children.iterator():
if valid_event_date(child.birth):
events.append({
'text': child.full_name + " born",
'year': child.birth.date.year,
'type': 'personal'
})
if valid_event_date(child.death):
if child.death.date < person.birth.date:
events.append({
'name': child.full_name + " died",
'year': child.death.date.year,
'type': 'personal'
})
if not valid_event_date(person.death):
end_date = now
events.append({'text': 'now', 'year': now, 'type': 'personal'})
else:
end_date = person.death.date.year
events.append({'text': 'died', 'year': end_date, 'type': 'personal'})
# Don't show timelines for people with only birth & end_date.
if len(events) < 3:
return HttpResponse('{"events": []}', content_type="application/json")
# open_years is an set of years where historical events may be added into
# the timeline, to prevent overcrowding of items
open_years = set(range(start_date + 1, end_date))
for e in events:
open_years -= set([e['year'] - 1, e['year'], e['year'] + 1])
number_allowed = max(((end_date - start_date) / 3) + 2 - len(events), 5)
historical_count = 0
random.shuffle(HISTORICAL)
for text, year in HISTORICAL:
if historical_count > number_allowed:
break
if year not in open_years:
continue
events.append({'text': text, 'year': year, 'type': 'historical'})
# Keep historical events three years apart to keep from crowding.
open_years -= set([year - 2, year - 1, year, year + 1, year + 2])
historical_count += 1
response = {'start': start_date, 'end': end_date, 'events': events}
return HttpResponse(json.dumps(response), content_type="application/json")
0
Example 129
Project: META-SHARE Source File: views.py
def reset(request, uuid=None):
"""
Resets the password for the given reset id.
"""
# If the uuid argument is not available, we have to render the reset form.
if not uuid:
# Check if the ResetRequestForm form has been submitted.
if request.method == "POST":
# If so, bind the reset form to HTTP POST values.
form = ResetRequestForm(request.POST)
# Check if the form has validated successfully.
if form.is_valid():
# Create a new ResetRequest instance for the User.
user = User.objects.get(
username=form.cleaned_data['username'],
email=form.cleaned_data['email'])
new_object = ResetRequest(user=user)
new_object.save()
# Render reset email template with correct values.
data = {'firstname': user.first_name,
'lastname': user.last_name,
'shortname': user.username,
'confirmation_url': '{0}/accounts/reset/{1}/'.format(
DJANGO_URL, new_object.uuid)}
email = render_to_string('accounts/reset.email', data)
try:
# Send out reset email to the given email address.
send_mail(_('Please confirm your META-SHARE reset request'),
email, '[email protected]', [user.email],
fail_silently=False)
except SMTPException:
# If the email could not be sent successfully, we simply
# redirect the user to the front page.
return redirect('metashare.views.frontpage')
# Add a message to the user after successful creation.
messages.success(request,
_("We have received your reset request and sent you an " \
"email with further reset instructions."))
# Redirect the user to the front page.
return redirect('metashare.views.frontpage')
# Otherwise, create an empty ResetRequestForm instance.
else:
form = ResetRequestForm()
dictionary = {'title': _('Reset user account'), 'form': form}
return render_to_response('accounts/reset_account.html', dictionary,
context_instance=RequestContext(request))
# If the uuid is given, we have to process the corresponding ResetRequest.
# We lookup the ResetRequest instance and create a new, random password.
user_reset = get_object_or_404(ResetRequest, uuid=uuid)
random_password = User.objects.make_random_password()
# Then we update the corresponding User instance with the new password.
user = user_reset.user
user.set_password(random_password)
user.save()
# Delete reset request instance.
user_reset.delete()
# Render re-activation email template with correct values.
data = {'firstname': user_reset.user.first_name,
'lastname': user.last_name,
'shortname': user.username,
'random_password': random_password}
email = render_to_string('accounts/reactivation.email', data)
try:
# Send out re-activation email to the given email address.
send_mail(_('Your META-SHARE user account has been re-activated'),
email, '[email protected]', [user.email], fail_silently=False)
except SMTPException:
# If the email could not be sent successfully, tell the user about it.
messages.error(request,
_("There was an error sending out the activation email " \
"for your user account. Please contact the administrator at %s.")
% (User.objects.filter(is_superuser=True) \
.values_list('email', flat=True)[0],))
# Redirect the user to the front page.
return redirect('metashare.views.frontpage')
# Add a message to the user after successful creation.
messages.success(request,
_("We have re-activated your user account and sent you an email with " \
"your personal password which allows you to login to the website."))
# Redirect the user to the front page.
return redirect('metashare.views.frontpage')
0
Example 130
Project: 3bot Source File: workflow.py
@login_required
def detail_perf(request, slug, template='threebot/workflow/detail_perf.html'):
orgs = get_my_orgs(request)
workflow = get_object_or_404(Workflow, owner__in=orgs, slug=slug)
wf_preset, created = WorkflowPreset.objects.get_or_create(user=request.user, workflow=workflow)
preset = {}
ready_to_perform = False # if true: each form is valid an request method is POST
logs = filter_workflow_log_history(workflow=workflow, quantity=5)
workflow_tasks = order_workflow_tasks(workflow)
# serve relevant forms
initials_for_worker_form = {}
if request.GET.get('worker'):
initials_for_worker_form['worker'] = request.GET.get('worker')
worker_form = WorkerSelectForm(request.POST or None, request=request, workflow=workflow, initial=initials_for_worker_form)
for wf_task in workflow_tasks:
extra = wf_task.task.required_inputs
wf_task.form = TaskParameterForm(request.POST or None, request=request, extra=extra, workflow_task=wf_task)
if request.method == 'POST':
ready_to_perform = True
if worker_form.is_valid():
worker_ids = worker_form.cleaned_data['worker']
preset.update({'worker_id': worker_ids})
else:
ready_to_perform = False
for wf_task in workflow_tasks:
if wf_task.form.is_valid():
pass
else:
ready_to_perform = False
if ready_to_perform:
inp = {}
for wf_task in workflow_tasks:
data = wf_task.form.cleaned_data
preset.update({wf_task.id: {}})
form_dict = {}
for data_type in Parameter.DATA_TYPE_CHOICES:
form_dict[data_type[0]] = {}
for template_input, path_to_value in data.iteritems(): # TODO: better identifier
# template_input = "wt_task_1.email.recipient_email"
# path_to_value = "[email protected]"
# path_to_value = "output.string.output_<WorkflowTask.id>"
template_input_list = template_input.split('.')
wf_task_id = template_input_list[0]
template_input_data_type = template_input_list[1]
template_input_name = template_input_list[2]
path_to_value_list = path_to_value.split('.')
param_owner = path_to_value_list[0]
if len(path_to_value_list) == 3:
param_data_type = path_to_value_list[1]
param_name = path_to_value_list[2]
# k[0] = wt_task id:
# k[1] = data_type:
# k[2] = value:
# val[0] = param owner
# val[1] = param data_type
# val[2] = param name
if param_owner == 'global':
value = OrganizationParameter.objects.get(data_type=param_data_type, name=param_name)
form_dict[template_input_data_type][template_input_name] = value.value
if param_owner == 'user':
value = UserParameter.objects.get(data_type=param_data_type, name=param_name, owner=request.user)
form_dict[template_input_data_type][template_input_name] = value.value
if param_owner == 'output':
# we set this to "output_<id>". while performing we replace this with the output returned from the WorkflowTask with id = <id>
form_dict[template_input_data_type][template_input_name] = '%s' % str(param_name)
if param_owner == 'prompted':
prompted_value = data['prompt_%s' % template_input].split('.', 2)
form_dict[template_input_data_type][template_input_name] = prompted_value[2]
# update presets
if not wf_task.form[template_input].is_hidden:
templatefield = '%s.%s' % (template_input_data_type, template_input_name)
preset[wf_task.id][templatefield] = path_to_value
inp['%s' % wf_task.id] = form_dict
wf_preset.defaults = preset
wf_preset.save()
workers = Worker.objects.filter(id__in=worker_ids)
for worker in workers:
workflow_log = WorkflowLog(workflow=workflow, inputs=inp, outputs={}, performed_by=request.user, performed_on=worker)
workflow_log.save()
run_workflow(workflow_log.id)
return redirect('core_workflow_log_detail', slug=workflow.slug, id=workflow_log.id) # redirects to latest
# else:
# raise("error")
return render_to_response(template, {'request': request,
'workflow': workflow,
'workflow_tasks': workflow_tasks,
'worker_form': worker_form,
'logs': logs,
'parameter_form': UserParameterCreateForm(user=request.user),
}, context_instance=RequestContext(request))
0
Example 131
Project: tollgate Source File: views.py
@user_passes_test(lambda u: u.has_perm('frontend.can_register_attendance'))
def signin3(request, uid):
u = get_object_or_404(User, id=uid)
my_profile = get_userprofile(request.user)
current_event = get_current_event()
if current_event == None:
messages.warning(request,
_('No event is currently active. Please make one.')
)
return redirect('admin:frontend_event_add')
if has_userprofile_attended(current_event, u.get_profile()):
# see if the user is already signed in.
# if so, direct them back to the start.
messages.error(request,
_('That user has already been signed in for this event.')
)
# return them to the signin start page
return redirect('signin')
if request.method == 'POST':
f = SignInForm3(request.POST)
if f.is_valid():
# create an attendance!
if f.cleaned_data['quota_unlimited']:
# check if setting unlimited quota is allowed.
if my_profile.maximum_quota_signins == 0:
# create unmetered attendance
a = EventAttendance(
quota_unmetered=True,
event=current_event,
user_profile=u.get_profile(),
registered_by=request.user.get_profile()
)
else:
a = None
messages.error(request, _("""\
You are not permitted to sign in users with unlimited quota.
"""))
else:
quota_amount = f.cleaned_data['quota_amount']
if my_profile.maximum_quota_signins == 0 or \
my_profile.maximum_quota_signins >= quota_amount:
a = EventAttendance(
quota_amount=quota_amount * 1048576,
event=current_event,
user_profile=u.get_profile(),
registered_by=request.user.get_profile()
)
else:
a = None
messages.error(request, _("""\
You are not permitted to sign in users with more than
%(max_quota)d MiB of quota.
""") % dict(max_quota=my_profile.maximum_quota_signins))
if a != None:
# attendance created, proceed
a.save()
# now sync user connections
enable_user_quota(a)
# attendance created, go back to signin page
messages.success(request,
_('Attendance registered, and enabled internet access for user.')
)
return redirect('signin')
else:
f = SignInForm3()
return render_to_response('frontend/signin3.html', dict(
form=f,
u=u
), context_instance=RequestContext(request))
0
Example 132
Project: eyebrowse-server Source File: views.py
@render_to('stats/profile_data.html')
def profile_data(request, username=None):
if request.user.is_authenticated():
user = get_object_or_404(User, username=request.user.username)
userprof = UserProfile.objects.get(user=user)
confirmed = userprof.confirmed
if not confirmed:
return redirect('/consent')
else:
user = None
userprof = None
"""
Own profile page
"""
username, follows, profile_user, empty_search_msg, nav_bar = _profile_info(
user, username)
get_dict, query, date, sort, filter = _get_query(request)
get_dict["orderBy"] = "end_time"
get_dict["direction"] = "hl"
get_dict["filter"] = ""
get_dict["page"] = request.GET.get("page", 1)
get_dict["username"] = profile_user.username
get_dict["sort"] = "time"
hist, history_stream = live_stream_query_manager(get_dict, request.user, empty_search_msg=empty_search_msg)
# stats
tot_time, item_count = profile_stat_gen(profile_user)
fav_data = FavData.objects.get(user=profile_user)
num_history = EyeHistory.objects.filter(user=profile_user).count()
is_online = online_user(user=profile_user)
following_count = profile_user.profile.follows.count()
follower_count = UserProfile.objects.filter(
follows=profile_user.profile).count()
today = datetime.now() - timedelta(hours=24)
day_count = hist.filter(
start_time__gt=today
).values('url', 'title').annotate(
num_urls=Sum('total_time')
).order_by('-num_urls')[:3]
day_domains = hist.filter(
start_time__gt=today
).values('domain'
).annotate(num_domains=Sum('total_time')
).order_by('-num_domains')[:5]
day_chart = {}
for domain in day_domains:
day_chart[domain['domain']] = domain['num_domains']
last_week = today - timedelta(days=7)
week_count = hist.filter(
start_time__gt=last_week
).values('url', 'title'
).annotate(num_urls=Sum('total_time')
).order_by('-num_urls')[:3]
week_domains = hist.filter(
start_time__gt=last_week
).values('domain'
).annotate(num_domains=Sum('total_time')
).order_by('-num_domains')[:5]
week_chart = {}
for domain in week_domains:
week_chart[domain['domain']] = domain['num_domains']
template_dict = {
'username': profile_user.username,
'following_count': following_count,
'follower_count': follower_count,
"profile_user": profile_user,
"history_stream": history_stream,
"empty_search_msg": empty_search_msg,
"follows": str(follows),
"is_online": is_online,
"num_history": num_history,
"tot_time": tot_time,
"item_count": item_count,
"fav_data": fav_data,
"query": query,
"date": date,
'day_articles': day_count,
'week_articles': week_count,
'day_chart': json.dumps(day_chart),
'week_chart': json.dumps(week_chart),
}
return _template_values(request,
page_title="profile history",
navbar=nav_bar,
sub_navbar="subnav_data",
**template_dict)
0
Example 133
Project: migasfree Source File: stats.py
@login_required
def delay_schedule(request, version_name=None):
title = _("Provided Computers / Delay")
version_selection = Version.get_version_names()
if version_name is None:
return render(
request,
'lines.html',
{
'title': title,
'version_selection': version_selection,
}
)
version = get_object_or_404(Version, name=version_name)
title += ' [%s]' % version.name
line_chart = pygal.Line(
no_data_text=_('There are no updates'),
x_label_rotation=LABEL_ROTATION,
legend_at_bottom=True,
style=DEFAULT_STYLE,
js=[JS_FILE],
width=WIDTH,
height=HEIGHT,
)
maximum_delay = 0
for schedule in Schedule.objects.all():
lst_attributes = []
d = 1
value = 0
line = []
delays = ScheduleDelay.objects.filter(
schedule__name=schedule.name
).order_by("delay")
for delay in delays:
for i in range(d, delay.delay):
line.append([i, value])
d += 1
for duration in range(0, delay.duration):
lst_att_delay = []
for att in delay.attributes.all():
lst_att_delay.append(att.id)
value += Login.objects.extra(
select={'deployment': 'computer_id'},
where=[
"computer_id %%%% %s = %s" %
(delay.duration, duration)
]
).filter(
~ Q(attributes__id__in=lst_attributes) &
Q(attributes__id__in=lst_att_delay) &
Q(computer__version=version.id) &
Q(computer__status__in=Computer.PRODUCTIVE_STATUS)
).values('computer_id').annotate(lastdate=Max('date')).count()
line.append([d, value])
d += 1
for att in delay.attributes.all():
lst_attributes.append(att.id)
maximum_delay = max(maximum_delay, d)
line_chart.add(schedule.name, [row[1] for row in line])
labels = []
for i in range(0, maximum_delay + 1):
labels.append(_('%d days') % i)
line_chart.x_labels = labels
return render(
request,
'lines.html',
{
'title': title,
'version_selection': version_selection,
'current_version': version.name,
'chart': line_chart.render_data_uri(),
'tabular_data': line_chart.render_table(),
}
)
0
Example 134
Project: ocf Source File: views.py
def confirm_requests(request):
"""Confirm the approval of the permission requests."""
approved_req_ids = request.session.setdefault("approved_req_ids", [])
delegatable_req_ids = request.session.setdefault("delegatable_req_ids", [])
denied_req_ids = request.session.setdefault("denied_req_ids", [])
approved_reqs = []
for req_id in approved_req_ids:
req = get_object_or_404(PermissionRequest, id=req_id)
delegatable = req_id in delegatable_req_ids
approved_reqs.append((req, delegatable))
denied_reqs = []
for req_id in denied_req_ids:
denied_reqs.append(
get_object_or_404(PermissionRequest, id=req_id))
if request.method == "POST":
# check if confirmed and then do actions.
if request.POST.get("post", "no") == "yes":
for req in denied_reqs:
req.deny()
# DatedMessage.objects.post_message_to_user(
# "Request for permission %s for object %s denied."
# % (req.requested_permission.permission.name,
# req.requested_permission.target),
# user=req.requesting_user,
# sender=req.permission_owner,
# msg_type=DatedMessage.TYPE_WARNING)
post_message = "Request for %s denied." % str(req.requested_permission.target).capitalize()
if req.requested_permission.permission.name == "can_create_project":
# Removes "* Project name: "
try:
project_name = req.message.split("||")[0].strip()[16:]
post_message = "Request for project %s creation denied." % project_name
# Notify requesting user
try:
send_mail(
settings.EMAIL_SUBJECT_PREFIX + "Denied project request for '%s'" % (project_name),
"Your request for the creation of project '%s' has been denied.\n\n\nYou may want to get in contact with the Island Manager for further details." % project_name,
from_email = settings.DEFAULT_FROM_EMAIL,
recipient_list = [req.requesting_user.email],
)
except Exception as e:
print "[WARNING] User e-mail notification could not be sent. Details: %s" % str(e)
except:
pass
# -------------------------------------------
# It is not about permission granting anymore
# -------------------------------------------
# Notify requesting user
DatedMessage.objects.post_message_to_user(
post_message,
user = req.requesting_user,
sender = req.permission_owner,
msg_type = DatedMessage.TYPE_WARNING)
# Notify user with permission (e.g. root)
DatedMessage.objects.post_message_to_user(
post_message,
user = request.user,
sender = req.permission_owner,
msg_type = DatedMessage.TYPE_WARNING)
for req, delegate in approved_reqs:
# --------------------------------------------------------
# Do NOT grant permission to create projects in the future
# --------------------------------------------------------
# req.allow(can_delegate=delegate)
req.deny()
# DatedMessage.objects.post_message_to_user(
# "Request for permission %s for object %s approved."
# % (req.requested_permission.permission.name,
# req.requested_permission.target),
# user=req.requesting_user,
# sender=req.permission_owner,
# msg_type=DatedMessage.TYPE_SUCCESS)
post_message = "Request for %s approved." % str(req.requested_permission.target).capitalize()
permission_user_post = post_message
requesting_user_post = post_message
email_header = post_message
email_body = "%s." % post_message
message_type = DatedMessage.TYPE_SUCCESS
# ---------------------------------------
# Project will be created in a direct way
# ---------------------------------------
if req.requested_permission.permission.name == "can_create_project":
project_name = ""
try:
project = Project()
project.uuid = uuid.uuid4()
message = req.message.split("||")
# Removes "* Project name: "
project.name = message[0].strip()[16:]
project_name = project.name
# Removes "* Project description: "
project.description = message[3].strip()[23:]
post_message = "Successfully created project %s" % project.name
project.save()
create_project_roles(project, req.requesting_user)
project.save()
email_header = "Approved project request for '%s'" % project_name
email_body = "Your request for the creation of project '%s' has been approved." % project_name
except Exception as e:
# Any error when creating a project results into:
# 1. Denying the petition
# 2. Notifying user in their Expedient
# 3. Notifying user via e-mail
post_message = "Project '%s' could not be created" % project_name
permission_user_post = post_message
requesting_user_post = post_message
# Handle exception text for user
if "duplicate entry" in str(e).lower():
email_body = "There is already a project with name '%s'. Try using a different name" % project_name
requesting_user_post += ". Details: project '%s' already exists" % project_name
else:
email_body = "There might have been a problem when interpreting the information for project '%s'" % str(project_name)
requesting_user_post += ". Contact your Island Manager for further details"
# Handle exception text for admin
if "Details" not in post_message:
permission_user_post = "%s. Details: %s" % (post_message, str(e))
message_type = DatedMessage.TYPE_ERROR
# Email for requesting user
email_header = "Denied project request for '%s'" % project_name
email_body = "Your request for the creation of project '%s' has been denied because of the following causes:\n\n%s\n\n\nYou may want to get in contact with the Island Manager for further details." % (project_name, email_body)
# Notify requesting user
DatedMessage.objects.post_message_to_user(
requesting_user_post,
user = req.requesting_user,
sender = req.permission_owner,
msg_type = message_type)
try:
send_mail(
settings.EMAIL_SUBJECT_PREFIX + email_header,
email_body,
from_email = settings.DEFAULT_FROM_EMAIL,
recipient_list = [req.requesting_user.email],
)
except Exception as e:
print "[WARNING] User e-mail notification could not be sent. Details: %s" % str(e)
# Notify user with permission (e.g. root)
DatedMessage.objects.post_message_to_user(
permission_user_post,
user = request.user,
sender = req.permission_owner,
msg_type = message_type)
# After this post we will be done with all this information
del request.session["approved_req_ids"]
del request.session["delegatable_req_ids"]
del request.session["denied_req_ids"]
return HttpResponseRedirect(reverse("home"))
else:
return direct_to_template(
request=request,
template=TEMPLATE_PATH+"/confirm_requests.html",
extra_context={
"approved_reqs": approved_reqs,
"denied_reqs": denied_reqs,
}
)
0
Example 135
Project: mollyproject Source File: views.py
def initial_context(self, request, scheme, value):
context = super(ServiceDetailView, self).initial_context(request)
service_id = request.GET.get('id')
route_id = request.GET.get('route')
route_pk = request.GET.get('routeid')
journey = request.GET.get('journey')
if service_id or route_id or route_pk or journey:
entity = get_entity(scheme, value)
else:
raise Http404()
context.update({
'entity': entity,
})
if service_id:
# Add live information from the providers
for provider in reversed(self.conf.providers):
provider.augment_metadata((entity, ))
# If we have no way of getting further journey details, 404
if 'service_details' not in entity.metadata:
raise Http404
# Deal with train service data
if entity.metadata['service_type'] == 'ldb':
# LDB has + in URLs, but Django converts that to space
service = entity.metadata['service_details'](service_id.replace(' ', '+'))
else:
service = entity.metadata['service_details'](service_id)
if service is None:
raise Http404
if 'error' in service:
context.update({
'title': _('An error occurred'),
'service': {
'error': service['error'],
},
})
return context
context.update({
'service': service,
'title': service['title'],
'zoom_controls': False,
})
elif route_id or route_pk:
if route_id:
route = entity.route_set.filter(service_id=route_id).distinct()
if route.count() == 0:
raise Http404()
elif route.count() > 1:
context.update({
'title': _('Multiple routes found'),
'multiple_routes': route
})
return context
else:
route = route[0]
else:
route = get_object_or_404(Route, id=route_pk)
i = 1
calling_points = []
previous = True
for stop in route.stoponroute_set.all():
if stop.entity == entity:
previous = False
calling_point = {
'entity': stop.entity,
'at': previous,
#'activity': stop.activity
}
if stop.entity.location is not None:
calling_point['stop_num'] = i
i += 1
calling_points.append(calling_point)
service = {
'entities': route.stops.all().order_by('stoponroute__order'),
'operator': route.operator,
'has_timetable': False,
'has_realtime': False,
'calling_points': calling_points
}
if entity not in service['entities']:
raise Http404()
context.update({
'title': '%s: %s' % (route.service_id, route.service_name),
'service': service
})
elif journey:
journey = get_object_or_404(Journey, id=journey)
route = journey.route
entity_passed = False
i = 1
calling_points = []
for stop in journey.scheduledstop_set.all():
if stop.entity == entity:
entity_passed = True
if not entity_passed and stop.std < datetime.now().time():
calling_point = {
'entity': stop.entity,
'st': stop.std.strftime('%H:%M'),
'at': True,
'activity': stop.activity
}
else:
calling_point = {
'entity': stop.entity,
# Show arrival time (if it exists, else departure time)
# if this stop is AFTER where we currently are, otherwise
# show the time the bus left stops before this one (if
# it exists)
'st': ((stop.sta or stop.std) if entity_passed else (stop.std or stop.sta)).strftime('%H:%M'),
'at': False,
'activity': stop.activity
}
if stop.entity.location is not None:
calling_point['stop_num'] = i
i += 1
calling_points.append(calling_point)
service = {
'entities': [s.entity for s in journey.scheduledstop_set.all()],
'operator': journey.route.operator,
'has_timetable': True,
'has_realtime': False,
'calling_points': calling_points,
'notes': journey.notes
}
if entity not in service['entities']:
raise Http404()
context.update({
'title': '%s: %s' % (route.service_id, route.service_name),
'service': service
})
if entity.location or len(filter(lambda e: e.location is not None, service['entities'])):
map = Map(
centre_point = (entity.location[0], entity.location[1],
'green', entity.title) if entity.location else None,
points = [(e.location[0], e.location[1], 'red', e.title)
for e in service['entities'] if e.location is not None],
min_points = len(service['entities']),
zoom = None,
width = request.map_width,
height = request.map_height,
)
context.update({
'map': map
})
return context
0
Example 136
Project: django-uocLTI Source File: views.py
@csrf_exempt
def launch_lti(request):
""" Receives a request from the lti consumer and creates/authenticates user in django """
""" See post items in log by setting LTI_DEBUG=True in settings """
if settings.LTI_DEBUG:
for item in request.POST:
print ('%s: %s \r' % (item, request.POST[item]))
if 'oauth_consumer_key' not in request.POST:
raise PermissionDenied()
""" key/secret from settings """
consumer_key = settings.CONSUMER_KEY
secret = settings.LTI_SECRET
tool_provider = DjangoToolProvider(consumer_key, secret, request.POST)
""" Decode parameters - UOC LTI uses a custom param to indicate the encoding: utf-8, iso-latin, base64 """
encoding = None
utf8 = get_lti_value('custom_lti_message_encoded_utf8', tool_provider)
iso = get_lti_value('custom_lti_message_encoded_iso', tool_provider)
b64 = get_lti_value('custom_lti_message_encoded_base64', tool_provider)
if iso and int(iso) == 1: encoding = 'iso'
if utf8 and int(utf8) == 1: encoding = 'utf8'
if b64 and int(b64) == 1: encoding = 'base64'
try: # attempt to validate request, if fails raises 403 Forbidden
if tool_provider.valid_request(request) == False:
raise PermissionDenied()
except:
print "LTI Exception: Not a valid request."
raise PermissionDenied()
""" RETRIEVE username, names, email and roles. These may be specific to the consumer,
in order to change them from the default values: see README.txt """
first_name = get_lti_value(settings.LTI_FIRST_NAME, tool_provider, encoding=encoding)
last_name = get_lti_value(settings.LTI_LAST_NAME, tool_provider, encoding=encoding)
email = get_lti_value(settings.LTI_EMAIL, tool_provider, encoding=encoding)
# avatar = tool_provider.custom_params['custom_photo']
roles = get_lti_value(settings.LTI_ROLES, tool_provider, encoding=encoding)
uoc_roles = get_lti_value(settings.LTI_CUSTOM_UOC_ROLES, tool_provider, encoding=encoding)
user_id = get_lti_value('user_id', tool_provider, encoding=encoding)
test = get_lti_value('context_title', tool_provider, encoding=encoding)
if not email or not user_id:
if settings.LTI_DEBUG: print "Email and/or user_id wasn't found in post, return Permission Denied"
raise PermissionDenied()
""" CHECK IF USER'S ROLES ALLOW ENTRY, IF RESTRICTION SET BY VELVET_ROLES SETTING """
if settings.VELVET_ROLES:
""" Roles allowed for entry into the application. If these are not set in settings then we allow all roles to enter """
if not roles and not uoc_roles:
""" if roles is None, then setting for LTI_ROLES may be wrong, return 403 for user and print error to log """
if settings.LTI_DEBUG: print "VELVET_ROLES is set but the roles for the user were not found. Check that the setting for LTI_ROLES is correct."
raise PermissionDenied()
all_user_roles = []
if roles:
if not isinstance(roles, list): roles = (roles,)
all_user_roles += roles
if uoc_roles:
if not isinstance(uoc_roles, list): uoc_roles = (uoc_roles,)
all_user_roles += uoc_roles
is_role_allowed = [m for velvet_role in settings.VELVET_ROLES for m in all_user_roles if velvet_role.lower()==m.lower()]
if not is_role_allowed:
if settings.LTI_DEBUG: print "User does not have accepted role for entry, roles: %s" % roles
ctx = {'roles':roles, 'first_name':first_name, 'last_name':last_name, 'email':email, 'user_id':user_id}
return render_to_response('lti_role_denied.html', ctx, context_instance=RequestContext(request))
else:
if settings.LTI_DEBUG: print "User has accepted role for entry, roles: %s" % roles
""" GET OR CREATE NEW USER AND LTI_PROFILE """
lti_username = '%s:user_%s' % (request.POST['oauth_consumer_key'], user_id) #create username with consumer_key and user_id
try:
""" Check if user already exists using email, if not create new """
user = User.objects.get(email=email)
if user.username != lti_username:
""" If the username is not in the format user_id, change it and save. This could happen
if there was a previously populated User table. """
user.username = lti_username
user.save()
except User.DoesNotExist:
""" first time entry, create new user """
user = User.objects.create_user(lti_username, email)
user.set_unusable_password()
if first_name: user.first_name = first_name
if last_name: user.last_name = last_name
user.save()
except User.MultipleObjectsReturned:
""" If the application is not requiring unique emails, multiple users may be returned if there was an existing
User table before implementing this app with multiple users for the same email address. Could add code to merge them, but for now we return 404 if
the user with the lti_username does not exist """
user = get_object_or_404(User, username=lti_username)
""" CHECK IF ANY OF USER'S ROLES ARE IN THE VELVET_ADMIN_ROLES SETTING, IF SO MAKE SUPERUSER IF IS NOT ALREADY """
if not user.is_superuser and settings.VELVET_ADMIN_ROLES:
if [m for l in settings.VELVET_ADMIN_ROLES for m in roles if l.lower() in m.lower()]:
user.is_superuser = True
user.is_staff = True
user.save()
""" Save extra info to custom profile model (add/remove fields in models.py)"""
lti_userprofile = get_object_or_404(LTIProfile, user=user)
lti_userprofile.roles = (",").join(all_user_roles)
# lti_userprofile.avatar = avatar #TO BE ADDED: function to grab user profile image if exists
lti_userprofile.save()
""" Log in user and redirect to LOGIN_REDIRECT_URL defined in settings (default: accounts/profile) """
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
0
Example 137
Project: airmozilla Source File: suggestions.py
@staff_required
@permission_required('main.add_event')
@transaction.atomic
def suggestion_review(request, id):
event = get_object_or_404(SuggestedEvent, pk=id)
real_event_form = None
comment_form = forms.SuggestedEventCommentForm()
if request.method == 'POST':
if request.POST.get('unbounce'):
event.submitted = timezone.now()
event.save()
return redirect('manage:suggestion_review', event.pk)
if not event.submitted:
return http.HttpResponseBadRequest('Not submitted')
form = forms.AcceptSuggestedEventForm(
request.POST,
instance=event,
)
if request.POST.get('save_comment'):
comment_form = forms.SuggestedEventCommentForm(data=request.POST)
if comment_form.is_valid():
comment = SuggestedEventComment.objects.create(
comment=comment_form.cleaned_data['comment'].strip(),
user=request.user,
suggested_event=event
)
sending.email_about_suggestion_comment(
comment,
request.user,
request
)
messages.info(
request,
'Comment added and %s notified.' % comment.user.email
)
return redirect('manage:suggestion_review', event.pk)
reject = request.POST.get('reject')
if reject:
form.fields['review_comments'].required = True
if not request.POST.get('save_comment') and form.is_valid():
form.save()
if reject:
event.submitted = None
event.status = SuggestedEvent.STATUS_REJECTED
event.save()
sending.email_about_rejected_suggestion(
event,
request.user,
request
)
messages.info(
request,
'Suggested event bounced back and %s has been emailed'
% (event.user.email,)
)
url = reverse('manage:suggestions')
return redirect(url)
else:
dict_event = {
'title': event.title,
'description': event.description,
'short_description': event.short_description,
'start_time': event.start_time,
'timezone': event.location.timezone,
'location': event.location.pk,
'channels': [x.pk for x in event.channels.all()],
'call_info': event.call_info,
'privacy': event.privacy,
'estimated_duration': event.estimated_duration,
'topics': [x.pk for x in event.topics.all()],
}
curated_groups = SuggestedCuratedGroup.objects.none()
if event.privacy == SuggestedEvent.PRIVACY_SOME_CONTRIBUTORS:
dict_event['privacy'] = Event.PRIVACY_CONTRIBUTORS
curated_groups = SuggestedCuratedGroup.objects.filter(
event=event
)
real_event_form = forms.EventRequestForm(
data=dict_event,
)
real_event_form.fields['placeholder_img'].required = False
if real_event_form.is_valid():
real = real_event_form.save(commit=False)
real.placeholder_img = event.placeholder_img
real.picture = event.picture
real.slug = event.slug
real.additional_links = event.additional_links
real.remote_presenters = event.remote_presenters
real.creator = request.user
real.status = Event.STATUS_SUBMITTED
# perhaps we have a default location template
# environment
if real.location:
try:
default = (
LocationDefaultEnvironment.objects
.get(
location=real.location,
privacy=real.privacy
)
)
real.template = default.template
real.template_environment = (
default.template_environment
)
except LocationDefaultEnvironment.DoesNotExist:
pass
# If they selected "Some Contributors", set the
# privacy to "Contributors" and copy the
# curated groups.
real.save()
[real.tags.add(x) for x in event.tags.all()]
[real.channels.add(x) for x in event.channels.all()]
[real.topics.add(x) for x in event.topics.all()]
for curated_group in curated_groups:
CuratedGroup.objects.create(
event=real,
name=curated_group.name,
url=curated_group.url
)
event.accepted = real
event.save()
# create the necessary approval bits
if event.privacy == Event.PRIVACY_PUBLIC:
groups = []
for topic in real.topics.filter(is_active=True):
for group in topic.groups.all():
if group not in groups:
groups.append(group)
for group in groups:
Approval.objects.create(
event=real,
group=group,
)
sending.email_about_approval_requested(
real,
group,
request
)
try:
discussion = SuggestedDiscussion.objects.get(
event=event,
enabled=True
)
real_discussion = Discussion.objects.create(
enabled=True,
event=real,
notify_all=discussion.notify_all,
moderate_all=discussion.moderate_all,
)
for moderator in discussion.moderators.all():
real_discussion.moderators.add(moderator)
except SuggestedDiscussion.DoesNotExist:
pass
# if this is a popcorn event, and there is a default
# popcorn template, then assign that
if real.popcorn_url:
real.status = Event.STATUS_SCHEDULED
templates = Template.objects.filter(
default_popcorn_template=True
)
for template in templates[:1]:
real.template = template
real.save()
sending.email_about_accepted_suggestion(
event,
real,
request
)
messages.info(
request,
'New event created from suggestion.'
)
if real.popcorn_url or not event.upcoming:
url = reverse('manage:events')
else:
url = reverse('manage:event_edit', args=(real.pk,))
return redirect(url)
else:
print real_event_form.errors
else:
form = forms.AcceptSuggestedEventForm(instance=event)
# we don't need the label for this form layout
comment_form.fields['comment'].label = ''
comments = (
SuggestedEventComment.objects
.filter(suggested_event=event)
.select_related('user')
.order_by('created')
)
discussion = None
for each in SuggestedDiscussion.objects.filter(event=event):
discussion = each
curated_groups = SuggestedCuratedGroup.objects.none()
if event.privacy == SuggestedEvent.PRIVACY_SOME_CONTRIBUTORS:
curated_groups = SuggestedCuratedGroup.objects.filter(
event=event
).order_by('name')
context = {
'event': event,
'form': form,
'real_event_form': real_event_form,
'comment_form': comment_form,
'comments': comments,
'discussion': discussion,
'curated_groups': curated_groups,
}
return render(request, 'manage/suggestion_review.html', context)
0
Example 138
Project: mygpo Source File: __init__.py
@csrf_exempt
@require_valid_user
@check_username
@never_cache
@allowed_methods(['GET', 'POST'])
@cors_origin()
def episodes(request, username, version=1):
version = int(version)
now = datetime.utcnow()
now_ = get_timestamp(now)
ua_string = request.META.get('HTTP_USER_AGENT', '')
if request.method == 'POST':
try:
actions = parse_request_body(request)
except (UnicodeDecodeError, ValueError) as e:
msg = ('Could not decode episode update POST data for ' +
'user %s: %s') % (username,
request.body.decode('ascii', errors='replace'))
logger.warn(msg, exc_info=True)
return HttpResponseBadRequest(msg)
logger.info('start: user %s: %d actions from %s' % (request.user, len(actions), ua_string))
# handle in background
if len(actions) > dsettings.API_ACTIONS_MAX_NONBG:
bg_handler = dsettings.API_ACTIONS_BG_HANDLER
if bg_handler is not None:
modname, funname = bg_handler.rsplit('.', 1)
mod = import_module(modname)
fun = getattr(mod, funname)
fun(request.user, actions, now, ua_string)
# TODO: return 202 Accepted
return JsonResponse({'timestamp': now_, 'update_urls': []})
try:
update_urls = update_episodes(request.user, actions, now, ua_string)
except ValidationError as e:
logger.warn('Validation Error while uploading episode actions for user %s: %s', username, str(e))
return HttpResponseBadRequest(str(e))
except InvalidEpisodeActionAttributes as e:
msg = 'invalid episode action attributes while uploading episode actions for user %s' % (username,)
logger.warn(msg, exc_info=True)
return HttpResponseBadRequest(str(e))
logger.info('done: user %s: %d actions from %s' % (request.user, len(actions), ua_string))
return JsonResponse({'timestamp': now_, 'update_urls': update_urls})
elif request.method == 'GET':
podcast_url= request.GET.get('podcast', None)
device_uid = request.GET.get('device', None)
since_ = request.GET.get('since', None)
aggregated = parse_bool(request.GET.get('aggregated', False))
try:
since = int(since_) if since_ else None
if since is not None:
since = datetime.utcfromtimestamp(since)
except ValueError:
return HttpResponseBadRequest('since-value is not a valid timestamp')
if podcast_url:
podcast = get_object_or_404(Podcast, urls__url=podcast_url)
else:
podcast = None
if device_uid:
try:
user = request.user
device = user.client_set.get(uid=device_uid)
except Client.DoesNotExist as e:
return HttpResponseNotFound(str(e))
else:
device = None
changes = get_episode_changes(request.user, podcast, device, since,
now, aggregated, version)
return JsonResponse(changes)
0
Example 139
Project: inventory Source File: ip_choosing_utils.py
def calculate_filters(choice_type, choice_pk):
"""
Write three functions that given a list of present primary keys
('present_pks') that are in the UI will remove the correct pk's and
return a list of raised objects.
filter_network will return a list of Networks
filter_site will return a list of Sites
filter_vlan will return a list of Vlans
The 'present_pks' value is a list of integers that represent primary
keys of the type of objects the function returns.
"""
if choice_type == 'network':
network = get_object_or_404(Network, pk=choice_pk)
def filter_network(present_pks):
return [network]
def filter_site(present_pks):
return [network.site] if network.site else []
def filter_vlan(present_pks):
return [network.vlan] if network.vlan else []
elif choice_type == 'site':
def filter_network(present_pks):
"""
Remove any present network pk's that aren't in the network
"""
site_network_pks = get_object_or_404(
Site, pk=choice_pk
).network_set.filter(UN).values_list('pk', flat=True)
net_pks = set(present_pks).intersection(set(site_network_pks))
return pks_to_objs(net_pks, Network)
def filter_site(present_pks):
return [get_object_or_404(Site, pk=choice_pk)]
def filter_vlan(present_pks):
vlans = pks_to_objs(present_pks, Vlan)
def is_in_site(vlan):
return vlan.network_set.filter(
site__pk=choice_pk).filter(UN).exists()
return filter(is_in_site, vlans)
elif choice_type == 'vlan':
vlan = get_object_or_404(Vlan, pk=choice_pk)
def filter_network(present_pks):
net_pks = vlan.network_set.filter(UN).values_list('pk', flat=True)
net_pks = set(present_pks).intersection(set(net_pks))
return pks_to_objs(net_pks, Network)
def filter_site(present_pks):
networks = vlan.network_set.filter(UN).filter(~Q(site=None))
network_site_pks = networks.values_list('site', flat=True)
site_pks = set(present_pks).intersection(set(network_site_pks))
return pks_to_objs(site_pks, Site)
def filter_vlan(present_pks):
return [vlan]
else:
raise Exception("Not sure what to do here...")
return filter_network, filter_site, filter_vlan
0
Example 140
Project: dre Source File: views.py
def bookmark_display( request, userid ):
context = {}
user = get_object_or_404(User, pk=userid)
is_owner = user == request.user
# Bookmark Filter Form
f = context['filter_form'] = BookmarksFilterForm(request.GET, tags_user = user,
public_only = user != request.user )
##
# Select the bookmarks
if is_owner:
results = Docuement.objects.filter(bookmarks__user__exact = user)
else:
results = Docuement.objects.filter( Q(bookmarks__user__exact = user) &
Q(bookmarks__public__exact = True))
if f.is_valid():
# Filter the results
order = f.cleaned_data['order']
invert = f.cleaned_data['invert']
query = f.cleaned_data['query']
start_date = f.cleaned_data['start_date']
end_date = f.cleaned_data['end_date']
tags = [ Tag.objects.get(pk=int(tag_id)) for tag_id in f.cleaned_data['tags'] ]
# Date filter
if start_date:
results = results.filter(date__gte = start_date)
if end_date:
results = results.filter(date__lte = end_date)
# Query filter
if query:
results = results.filter(
Q(number__icontains = query ) |
Q(doc_type__icontains = query ) |
Q(emiting_body__icontains = query ) |
Q(source__icontains = query ) |
Q(dre_key__icontains = query ) |
Q(notes__icontains = query )
)
# Tag filter
if tags:
results = results.filter( tags__tag__in = tags )
# Order:
sign = '' if invert else '-'
if order:
results = results.order_by('%s%s' % ( sign,
'bookmarks__timestamp' if order == 1 else 'date') )
else:
results = results.order_by('-bookmarks__timestamp')
results = results.distinct()
##
# Pagination
page = request.GET.get('page', 1)
try:
page = int(page)
except:
page = 1
paginator = Paginator(results, settings.RESULTS_PER_PAGE, orphans=settings.ORPHANS)
if page < 1:
page = 1
if page > paginator.num_pages:
page = paginator.num_pages
# Get the bookmark objects:
results = list(paginator.page(page).object_list)
for doc in results:
doc.bm = doc.bookmark( user )
# Finish the context:
context['page'] = paginator.page(page)
context['results'] = results
context['query'] = re.sub(r'&page=\d+', '', '?%s' % request.META['QUERY_STRING'] )
context['bookmarks_user'] = user
context['is_owner'] = is_owner
return render_to_response('bookmark_display.html', context,
context_instance=RequestContext(request))
0
Example 141
Project: kuma Source File: edit.py
@newrelic.agent.function_trace()
@block_user_agents
@require_http_methods(['GET', 'POST'])
@login_required # TODO: Stop repeating this knowledge here and in Docuement.allows_editing_by.
@ratelimit(key='user', rate=limit_banned_ip_to_0, block=True)
@process_docuement_path
@check_readonly
@prevent_indexing
@never_cache
def edit(request, docuement_slug, docuement_locale, revision_id=None):
"""
Create a new revision of a wiki docuement, or edit docuement metadata.
"""
doc = get_object_or_404(Docuement,
locale=docuement_locale,
slug=docuement_slug)
# If this docuement has a parent, then the edit is handled by the
# translate view. Pass it on.
if doc.parent and doc.parent.id != doc.id:
return translate(request, doc.parent.slug, doc.locale, revision_id,
bypass_process_docuement_path=True)
if revision_id:
rev = get_object_or_404(Revision, pk=revision_id, docuement=doc)
else:
rev = doc.current_revision or doc.revisions.order_by('-created',
'-id')[0]
# Keep hold of the full post slug
slug_dict = split_slug(docuement_slug)
# Update the slug, removing the parent path, and
# *only* using the last piece.
# This is only for the edit form.
rev.slug = slug_dict['specific']
section_id = request.GET.get('section', None)
if section_id and not request.is_ajax():
return HttpResponse(ugettext("Sections may only be edited inline."))
disclose_description = bool(request.GET.get('opendescription'))
doc_form = rev_form = None
if doc.allows_revision_by(request.user):
rev_form = RevisionForm(request=request,
instance=rev,
initial={'based_on': rev.id,
'current_rev': rev.id,
'comment': ''},
section_id=section_id)
if doc.allows_editing_by(request.user):
doc_form = DocuementForm(initial=docuement_form_initial(doc))
# Need to make check *here* to see if this could have a translation parent
show_translation_parent_block = (
(docuement_locale != settings.WIKI_DEFAULT_LANGUAGE) and
(not doc.parent_id))
if request.method == 'GET':
if not (rev_form or doc_form):
# You can't do anything on this page, so get lost.
raise PermissionDenied
else: # POST
is_async_submit = request.is_ajax()
is_raw = request.GET.get('raw', False)
need_edit_links = request.GET.get('edit_links', False)
parent_id = request.POST.get('parent_id', '')
# Attempt to set a parent
if show_translation_parent_block and parent_id:
try:
parent_doc = get_object_or_404(Docuement, id=parent_id)
doc.parent = parent_doc
except Docuement.DoesNotExist:
pass
# Comparing against localized names for the Save button bothers me, so
# I embedded a hidden input:
which_form = request.POST.get('form-type')
if which_form == 'doc':
if doc.allows_editing_by(request.user):
post_data = request.POST.copy()
post_data.update({'locale': docuement_locale})
doc_form = DocuementForm(post_data, instance=doc)
if doc_form.is_valid():
# if must be here for section edits
if 'slug' in post_data:
post_data['slug'] = u'/'.join([slug_dict['parent'],
post_data['slug']])
# Get the possibly new slug for the imminent redirection:
doc = doc_form.save(parent=None)
return redirect(urlparams(doc.get_edit_url(),
opendescription=1))
disclose_description = True
else:
raise PermissionDenied
elif which_form == 'rev':
if not doc.allows_revision_by(request.user):
raise PermissionDenied
else:
post_data = request.POST.copy()
rev_form = RevisionForm(request=request,
data=post_data,
is_async_submit=is_async_submit,
section_id=section_id)
rev_form.instance.docuement = doc # for rev_form.clean()
# Come up with the original revision to which these changes
# would be applied.
orig_rev_id = request.POST.get('current_rev', False)
if orig_rev_id is False:
orig_rev = None
else:
orig_rev = Revision.objects.get(pk=orig_rev_id)
# Get the docuement's actual current revision.
curr_rev = doc.current_revision
if not rev_form.is_valid():
# If this was an Ajax POST, then return a JsonResponse
if is_async_submit:
# Was there a mid-air collision?
if 'current_rev' in rev_form._errors:
# Make the error message safe so the '<' and '>' don't
# get turned into '<' and '>', respectively
rev_form.errors['current_rev'][0] = mark_safe(
rev_form.errors['current_rev'][0])
errors = [rev_form.errors[key][0] for key in rev_form.errors.keys()]
data = {
"error": True,
"error_message": errors,
"new_revision_id": curr_rev.id,
}
return JsonResponse(data=data)
# Jump out to a function to escape indentation hell
return _edit_docuement_collision(
request, orig_rev, curr_rev, is_async_submit,
is_raw, rev_form, doc_form, section_id,
rev, doc)
# Was this an Ajax submission that was marked as spam?
if is_async_submit and '__all__' in rev_form._errors:
# Return a JsonResponse
data = {
"error": True,
"error_message": mark_safe(rev_form.errors['__all__'][0]),
"new_revision_id": curr_rev.id,
}
return JsonResponse(data=data)
if rev_form.is_valid():
rev_form.save(doc)
if (is_raw and orig_rev is not None and
curr_rev.id != orig_rev.id):
# If this is the raw view, and there was an original
# revision, but the original revision differed from the
# current revision at start of editing, we should tell
# the client to refresh the page.
response = HttpResponse('RESET')
response['X-Frame-Options'] = 'SAMEORIGIN'
response.status_code = 205
return response
# Is this an Ajax POST?
if is_async_submit:
# This is the most recent revision id
new_rev_id = rev.docuement.revisions.order_by('-id').first().id
data = {
"error": False,
"new_revision_id": new_rev_id
}
return JsonResponse(data)
if rev_form.instance.is_approved:
view = 'wiki.docuement'
else:
view = 'wiki.docuement_revisions'
# Construct the redirect URL, adding any needed parameters
url = reverse(view, args=[doc.slug], locale=doc.locale)
params = {}
if is_raw:
params['raw'] = 'true'
if need_edit_links:
# Only need to carry over ?edit_links with ?raw,
# because they're on by default in the normal UI
params['edit_links'] = 'true'
if section_id:
# If a section was edited, and we're using the raw
# content API, constrain to that section.
params['section'] = section_id
# Parameter for the docuement saved, so that we can delete the cached draft on load
params['docuement_saved'] = 'true'
url = '%s?%s' % (url, urlencode(params))
if not is_raw and section_id:
# If a section was edited, jump to the section anchor
# if we're not getting raw content.
url = '%s#%s' % (url, section_id)
return redirect(url)
parent_path = parent_slug = ''
if slug_dict['parent']:
parent_slug = slug_dict['parent']
if doc.parent_topic_id:
parent_doc = Docuement.objects.get(pk=doc.parent_topic_id)
parent_path = parent_doc.get_absolute_url()
parent_slug = parent_doc.slug
context = {
'revision_form': rev_form,
'docuement_form': doc_form,
'section_id': section_id,
'disclose_description': disclose_description,
'parent_slug': parent_slug,
'parent_path': parent_path,
'revision': rev,
'docuement': doc,
'attachment_form': AttachmentRevisionForm(),
}
return render(request, 'wiki/edit.html', context)
0
Example 142
Project: aemanager Source File: views.py
@settings_required
@subscription_required
@commit_on_success
def proposal_create_or_edit(request, id=None, project_id=None):
user = request.user
if id:
title = _('Edit a proposal')
proposal = get_object_or_404(Proposal, pk=id, owner=request.user)
old_file = proposal.contract_file
project = proposal.project
else:
title = _('Add a proposal')
proposal = None
old_file = None
project = get_object_or_404(Project, pk=project_id, owner=request.user)
ProposalRowFormSet = inlineformset_factory(Proposal,
ProposalRow,
form=ProposalRowForm,
fk_name="proposal",
extra=1)
proposals = Proposal.objects.filter(owner=request.user).exclude(contract_content='')
if request.method == 'POST':
proposalForm = ProposalForm(request.POST, request.FILES, instance=proposal, prefix="proposal")
proposalForm.fields['contract_model'].queryset = proposals
proposalrowformset = ProposalRowFormSet(request.POST, instance=proposal)
if proposalForm.is_valid() and proposalrowformset.is_valid():
if request.FILES:
try:
if old_file:
if os.path.exists(old_file.path):
os.remove(old_file.path)
except:
pass
try:
proposal = proposalForm.save(commit=False)
proposal.project = project
proposal.update_date = datetime.datetime.now()
proposal.save(user=user)
proposalForm.save_m2m()
for proposalrowform in proposalrowformset.forms:
if proposalrowform not in proposalrowformset.deleted_forms and proposalrowform.cleaned_data:
proposalrow = proposalrowform.save(commit=False)
proposalrow.proposal = proposal
proposalrow.save(user=user)
for deleted_proposalrowform in proposalrowformset.deleted_forms:
deleted_proposalrowform.instance.delete()
proposal.update_amount()
messages.success(request, _('The proposal has been saved successfully'))
if proposal.begin_date and proposal.end_date and proposal.begin_date > proposal.end_date:
messages.warning(request, _("Begin date is greater than end date, is this normal ?"))
if proposal.expiration_date and proposal.expiration_date < datetime.date.today() and proposal.state < PROPOSAL_STATE_SENT:
messages.warning(request, _("Expiration date is in the past while the proposal is not yet sent, is this normal ?"))
return redirect(reverse('proposal_detail', kwargs={'id': proposal.id}))
except ProposalAmountError:
rollback()
messages.error(request, _("Proposal amount can't be less than sum of invoices"))
else:
messages.error(request, _('Data provided are invalid'))
else:
proposalForm = ProposalForm(instance=proposal, prefix="proposal")
proposalForm.fields['contract_model'].queryset = proposals
proposalrowformset = ProposalRowFormSet(instance=proposal)
substitution_map = Proposal.get_substitution_map()
substitution_keys = substitution_map.keys()
keys = ''
if len(substitution_keys):
keys = "{{ " + " }}, {{ ".join(substitution_keys) + " }}"
return render_to_response('proposal/edit.html',
{'active': 'business',
'title': title,
'proposalForm': proposalForm,
'proposalrowformset': proposalrowformset,
'substitution_keys': keys},
context_instance=RequestContext(request))
0
Example 143
Project: mozillians Source File: views.py
@never_cache
def show(request, url, alias_model, template):
"""List all members in this group."""
group_alias = get_object_or_404(alias_model, url=url)
if group_alias.alias.url != url:
return redirect('groups:show_group', url=group_alias.alias.url)
is_curator = False
is_manager = request.user.userprofile.is_manager
is_pending = False
show_delete_group_button = False
membership_filter_form = forms.MembershipFilterForm(request.GET)
group = group_alias.alias
profile = request.user.userprofile
in_group = group.has_member(profile)
memberships = group.members.all()
data = {}
if isinstance(group, Group):
# Has the user accepted the group terms
if group.terms:
membership = get_object_or_none(GroupMembership, group=group, userprofile=profile,
status=GroupMembership.PENDING_TERMS)
if membership:
return redirect(reverse('groups:review_terms', args=[group.url]))
# Is this user's membership pending?
is_pending = group.has_pending_member(profile)
is_curator = is_manager or (request.user.userprofile in group.curators.all())
# initialize the form only when the group is moderated and user is curator of the group
if is_curator and group.accepting_new_members == 'by_request':
membership_filter_form = forms.MembershipFilterForm(request.GET)
else:
membership_filter_form = None
if is_curator:
statuses = [GroupMembership.MEMBER, GroupMembership.PENDING]
if membership_filter_form and membership_filter_form.is_valid():
filtr = membership_filter_form.cleaned_data['filtr']
if filtr == 'members':
statuses = [GroupMembership.MEMBER]
elif filtr == 'pending_members':
statuses = [GroupMembership.PENDING]
memberships = group.groupmembership_set.filter(status__in=statuses)
# Curators can delete their group if there are no other members.
show_delete_group_button = is_curator and group.members.all().count() == 1
else:
# only show full members, or this user
memberships = group.groupmembership_set.filter(
Q(status=GroupMembership.MEMBER) | Q(userprofile=profile))
invitation = get_object_or_none(Invite, redeemer=profile, group=group, accepted=False)
data.update(invitation=invitation)
# Order by UserProfile.Meta.ordering
memberships = memberships.order_by('userprofile')
# Find the most common skills of the group members.
# Order by popularity in the group.
shared_skill_ids = (group.members.filter(groupmembership__status=GroupMembership.MEMBER)
.values_list('skills', flat=True))
count_skills = defaultdict(int)
for skill_id in shared_skill_ids:
count_skills[skill_id] += 1
common_skills_ids = [k for k, v in sorted(count_skills.items(),
key=lambda x: x[1],
reverse=True)
if count_skills[k] > 1]
# Translate ids to Skills preserving order.
skills = [Skill.objects.get(id=skill_id) for skill_id in common_skills_ids if skill_id]
data.update(skills=skills, membership_filter_form=membership_filter_form)
page = request.GET.get('page', 1)
paginator = Paginator(memberships, settings.ITEMS_PER_PAGE)
try:
people = paginator.page(page)
except PageNotAnInteger:
people = paginator.page(1)
except EmptyPage:
people = paginator.page(paginator.num_pages)
show_pagination = paginator.count > settings.ITEMS_PER_PAGE
extra_data = dict(
people=people,
group=group,
in_group=in_group,
is_curator=is_curator,
is_pending=is_pending,
show_pagination=show_pagination,
show_delete_group_button=show_delete_group_button,
show_join_button=group.user_can_join(request.user.userprofile),
show_leave_button=group.user_can_leave(request.user.userprofile),
members=group.member_count,
)
data.update(extra_data)
return render(request, template, data)
0
Example 144
Project: hyperkitty Source File: thread.py
@check_mlist_private
def thread_index(request, mlist_fqdn, threadid, month=None, year=None):
''' Displays all the email for a given thread identifier '''
# pylint: disable=unused-argument
mlist = get_object_or_404(MailingList, name=mlist_fqdn)
thread = get_object_or_404(Thread, mailinglist=mlist, thread_id=threadid)
starting_email = thread.starting_email
sort_mode = request.GET.get("sort", "thread")
if request.user.is_authenticated():
starting_email.myvote = starting_email.votes.filter(
user=request.user).first()
else:
starting_email.myvote = None
# Tags
tag_form = AddTagForm()
# Favorites
fav_action = "add"
if request.user.is_authenticated() and Favorite.objects.filter(
thread=thread, user=request.user).exists():
fav_action = "rm"
# Category
categories = [ (c.name, c.name.upper())
for c in ThreadCategory.objects.all() ] \
+ [("", "no category")]
category, category_form = get_category_widget(
request, thread.category, categories)
# Extract relative dates
today = datetime.date.today()
days_old = today - starting_email.date.date()
days_inactive = today - thread.date_active.date()
subject = stripped_subject(mlist, starting_email.subject)
# Last view
last_view = None
if request.user.is_authenticated():
last_view_obj, created = LastView.objects.get_or_create(
thread=thread, user=request.user)
if not created:
last_view = last_view_obj.view_date
last_view_obj.save() # update timestamp
# get the number of unread messages
if last_view is None:
if request.user.is_authenticated():
unread_count = thread.emails_count
else:
unread_count = 0
else:
unread_count = thread.emails.filter(date__gt=last_view).count()
# Flash messages
flash_messages = []
flash_msg = request.GET.get("msg")
if flash_msg:
flash_msg = { "type": FLASH_MESSAGES[flash_msg][0],
"msg": FLASH_MESSAGES[flash_msg][1] }
flash_messages.append(flash_msg)
# TODO: eventually move to a middleware ?
# http://djangosnippets.org/snippets/1865/
user_agent = request.META.get('HTTP_USER_AGENT', None)
if user_agent:
is_bot = robot_detection.is_robot(user_agent)
else:
is_bot = True
context = {
'mlist': mlist,
'thread': thread,
'starting_email': starting_email,
'subject': subject,
'addtag_form': tag_form,
'month': thread.date_active,
'months_list': get_months(mlist),
'days_inactive': days_inactive.days,
'days_old': days_old.days,
'sort_mode': sort_mode,
'fav_action': fav_action,
'reply_form': ReplyForm(),
'is_bot': is_bot,
'num_comments': thread.emails_count - 1,
'last_view': last_view,
'unread_count': unread_count,
'category_form': category_form,
'category': category,
'flash_messages': flash_messages,
}
if is_bot:
# Don't rely on AJAX to load the replies
# The limit is a safety measure, don't let a bot kill the DB
context["replies"] = _get_thread_replies(request, thread, limit=1000)
return render(request, "hyperkitty/thread.html", context)
0
Example 145
Project: ganetimgr Source File: __init__.py
@permission_required("apply.change_instanceapplication")
def review_application(request, application_id=None):
applications = InstanceApplication.objects.filter(status__in=PENDING_CODES)
fast_clusters = Cluster.objects.filter(fast_create=True).exclude(
disable_instance_creation=True
).order_by('description')
# There is a chance that the administrator has just filled a form
# by himself, so the application does not actually exist (yet)
# import ipdb; ipdb.set_trace()
if application_id:
app = get_object_or_404(InstanceApplication, pk=application_id)
else:
# We set app to None because there is application instance yet
app = None
if request.method == "GET" and app:
form = InstanceApplicationReviewForm(
instance=app,
initial={
'operating_system': app.operating_system
}
)
if app.instance_params and 'cluster' in app.instance_params.keys():
form = InstanceApplicationReviewForm(
instance=app,
initial={
"cluster": Cluster.objects.get(
slug=app.instance_params['cluster']
).pk,
'operating_system': app.operating_system
})
return render(
request,
'apply/review.html',
{
'application': app,
'applications': applications,
'appform': form,
'fast_clusters': fast_clusters
}
)
elif request.method == "POST":
data = request.POST.dict()
if data.get('reject', ''):
if data.get('node_group'):
del data['node_group']
if data.get('netw'):
del data['netw']
if data.get('vgs'):
del data['vgs']
if data.get('disk_template'):
del data['disk_template']
nodegroup = data.get('node_group', '')
form_ngs = (('', ''),)
if nodegroup:
form_ngs = ((nodegroup, nodegroup),)
netw = data.get('netw', '')
form_netw = (('', ''),)
if netw:
form_netw = ((netw, netw),)
vgs = data.get('vgs', '')
form_vgs = (('', ''),)
if vgs:
form_vgs = ((vgs, vgs),)
dt = data.get('disk_template', '')
form_dt = (('', ''),)
if dt:
form_dt = ((dt, dt),)
form = InstanceApplicationReviewForm(data, instance=app)
# check if code is run in test mode
import sys
if sys.argv[1:2] == ['test']:
form.fields['cluster'].choices.append((100, 100))
form.fields['netw'].choices.append(('test::test', 'test::test'))
form.fields['disk_template'].choices.append(('test', 'test'))
form.fields['node_group'].choices.append(('test', 'test'))
form.fields['vgs'].choices.append(('test', 'test'))
else:
if not form.data.get('reject'):
form.fields['node_group'] = forms.ChoiceField(choices=form_ngs, label="Node Group")
form.fields['netw'] = forms.ChoiceField(choices=form_netw, label="Network")
form.fields['vgs'] = forms.ChoiceField(choices=form_vgs, label="Volume Groups",)
form.fields['disk_template'] = forms.ChoiceField(choices=form_dt, label="Disk Template",)
if form.is_valid():
application = form.save(commit=False)
# if the instance does not exist yet
if not app:
# we have to connect the user with this form
application.applicant = request.user
application.operating_system = form.cleaned_data['operating_system']
if "reject" in request.POST:
application.status = STATUS_REFUSED
application.save()
mail_body = render_to_string(
"apply/emails/application_rejected_mail.txt",
{"application": application, },
context_instance=RequestContext(request)
)
send_mail(
settings.EMAIL_SUBJECT_PREFIX + "Application for %s rejected" % (
application.hostname
),
mail_body,
settings.SERVER_EMAIL,
[application.applicant.email]
)
messages.add_message(
request,
messages.INFO,
"Application #%d rejected, user %s has"
" been notified" % (app.pk, application.applicant)
)
else:
application.status = STATUS_APPROVED
application.instance_params = {
'cluster': Cluster.objects.get(
pk=form.cleaned_data['cluster']
).slug,
'network': form.cleaned_data['netw'].split("::")[0],
'mode': form.cleaned_data['netw'].split("::")[1],
'node_group': form.cleaned_data['node_group'],
'vgs': form.cleaned_data['vgs'],
'disk_template': form.cleaned_data['disk_template'],
}
application.reviewer = request.user
application.save()
application.submit()
messages.add_message(request, messages.INFO,
"Application #%d accepted and submitted"
" to %s" % (application.pk, application.cluster))
cache.delete('pendingapplications')
return HttpResponseRedirect(reverse("application-list"))
else:
if app:
return render(
request,
'apply/review.html',
{
'application': app,
'applications': applications,
'appform': form,
'fast_clusters': fast_clusters
}
)
else:
return render(
request,
'apply/admin_apply.html',
{
'form': form
}
)
else:
# If the request method is GET, but there is no application given,
# then someone is trying to do stuff.
raise Http404
0
Example 146
Project: aemanager Source File: views.py
@csrf_exempt
@commit_on_success
def paypal_ipn(request):
# send back the response to paypal
data = dict(request.POST.items())
args = {'cmd': '_notify-validate'}
args.update(data)
params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in args.items()))
paypal_response = urllib2.urlopen(settings.PAYPAL_URL + '/cgi-bin/webscr', params).read()
# process the payment
receiver_id = data['receiver_id']
transaction_id = data['txn_id']
payment_status = data['payment_status']
payment_amount = data['mc_gross']
payment_currency = data['mc_currency']
fee = data['mc_fee']
item_name = data['item_name']
user_id = data['custom']
user = get_object_or_404(User, pk=user_id)
profile = user.get_profile()
last_subscription = profile.get_last_subscription()
subscription, created = Subscription.objects.get_or_create(transaction_id=transaction_id,
defaults={'owner': user,
'state': SUBSCRIPTION_STATE_NOT_PAID,
'expiration_date': profile.get_next_expiration_date(),
'transaction_id': transaction_id,
'error_message': ugettext('Not verified')})
if paypal_response == 'VERIFIED':
if receiver_id <> settings.PAYPAL_RECEIVER_ID:
subscription.error_message = ugettext('Receiver is not as defined in settings. Spoofing ?')
elif payment_status <> 'Completed':
subscription.error_message = ugettext('Payment not completed')
elif payment_amount <> settings.PAYPAL_APP_SUBSCRIPTION_AMOUNT:
subscription.error_message = ugettext('Amount altered. Bad guy ?')
elif payment_currency <> settings.PAYPAL_APP_SUBSCRIPTION_CURRENCY:
subscription.error_message = ugettext('Amount altered. Bad guy ?')
else:
subscription.error_message = ugettext('Paid')
subscription.state = SUBSCRIPTION_STATE_PAID
# create an invoice for this payment
# first, get the provider user
provider = User.objects.get(email=settings.SERVICE_PROVIDER_EMAIL)
if provider.get_profile().vat_number:
payment_amount = Decimal(payment_amount) / Decimal('1.196')
# look for a customer corresponding to user
address, created = Address.objects.get_or_create(contact__email=user.email,
owner=provider,
defaults={'street': profile.address.street,
'zipcode': profile.address.zipcode,
'city': profile.address.city,
'country': profile.address.country,
'owner': provider})
customer, created = Contact.objects.get_or_create(email=user.email,
defaults={'contact_type': CONTACT_TYPE_COMPANY,
'name': '%s %s' % (user.first_name, user.last_name),
'company_id': profile.company_id,
'legal_form': 'Auto-entrepreneur',
'email': user.email,
'address': address,
'owner': provider})
# create a related project if needed
# set it to finished to clear daily business
project, created = Project.objects.get_or_create(state=PROJECT_STATE_FINISHED,
customer=customer,
name='Subscription %s - %s %s' % (Site.objects.get_current().name, user.first_name, user.last_name),
defaults={'state': PROJECT_STATE_FINISHED,
'customer': customer,
'name': 'Subscription %s - %s %s' % (Site.objects.get_current().name, user.first_name, user.last_name),
'owner': provider})
# create proposal for this subscription
begin_date = datetime.date.today()
if begin_date < last_subscription.expiration_date:
begin_date = last_subscription.expiration_date
proposal = Proposal.objects.create(project=project,
reference='subscription%i%i%i' % (subscription.expiration_date.year,
subscription.expiration_date.month,
subscription.expiration_date.day),
state=PROPOSAL_STATE_BALANCED,
begin_date=begin_date,
end_date=subscription.expiration_date,
contract_content='',
update_date=datetime.date.today(),
expiration_date=None,
owner=provider)
unit_price = Decimal(settings.PAYPAL_APP_SUBSCRIPTION_AMOUNT)
if provider.get_profile().vat_number:
unit_price = Decimal(unit_price) / Decimal('1.196')
proposal_row = ProposalRow.objects.create(proposal=proposal,
label=item_name,
category=ROW_CATEGORY_SERVICE,
quantity=1,
unit_price='%s' % unit_price,
owner=provider)
# finally create invoice
invoice = Invoice.objects.create(customer=customer,
invoice_id=Invoice.objects.get_next_invoice_id(provider),
state=INVOICE_STATE_PAID,
amount=payment_amount,
edition_date=datetime.date.today(),
payment_date=datetime.date.today(),
paid_date=datetime.date.today(),
payment_type=PAYMENT_TYPE_BANK_CARD,
execution_begin_date=begin_date,
execution_end_date=subscription.expiration_date,
penalty_date=None,
penalty_rate=None,
discount_conditions=None,
owner=provider)
invoice_row = InvoiceRow.objects.create(proposal=proposal,
invoice=invoice,
label=item_name,
category=ROW_CATEGORY_SERVICE,
quantity=1,
unit_price=payment_amount,
balance_payments=True,
vat_rate=VAT_RATES_19_6,
owner=provider)
# create expense for paypal fee
expense = Expense.objects.create(date=datetime.date.today(),
reference=transaction_id,
supplier='Paypal',
amount=fee,
payment_type=PAYMENT_TYPE_BANK_CARD,
description='Commission paypal',
owner=provider)
# generate invoice in pdf
response = HttpResponse(mimetype='application/pdf')
invoice.to_pdf(provider, response)
subject_template = loader.get_template('core/subscription_paid_email_subject.html')
subject_context = {'site_name': Site.objects.get_current().name}
subject = subject_template.render(Context(subject_context))
body_template = loader.get_template('core/subscription_paid_email.html')
body_context = {'site_name': Site.objects.get_current().name,
'expiration_date': subscription.expiration_date}
body = body_template.render(Context(body_context))
email = EmailMessage(subject=subject,
body=body,
to=[user.email])
email.attach('facture_%i.pdf' % (invoice.invoice_id), response.content, 'application/pdf')
email.send(fail_silently=(not settings.DEBUG))
subscription.save()
return render_to_response('core/paypal_ipn.html',
{'active': 'account',
'title': _('Subscribe')},
context_instance=RequestContext(request))
0
Example 147
Project: ocf Source File: aggregate.py
def aggregate_crud(request, agg_id=None):
'''
Create/update a SampleResource Aggregate.
'''
if agg_id != None:
aggregate = get_object_or_404(SampleResourceAggregateModel, pk=agg_id)
client = aggregate.client
else:
aggregate = None
client = None
extra_context_dict = {}
errors = ""
if request.method == "GET":
agg_form = SampleResourceAggregateForm(instance=aggregate)
client_form = xmlrpcServerProxyForm(instance=client)
elif request.method == "POST":
agg_form = SampleResourceAggregateForm(
data=request.POST, instance=aggregate)
client_form = xmlrpcServerProxyForm(
data=request.POST, instance=client)
if client_form.is_valid() and agg_form.is_valid():
# Ping is tried after every field check
client = client_form.save(commit=False)
s = xmlrpclib.Server('https://'+client.username+':'+client.password+'@'+client.url[8:])
try:
s.ping('ping')
except:
errors = "Could not connect to server: username, password or url are not correct"
DatedMessage.objects.post_message_to_user(
errors, user=request.user, msg_type=DatedMessage.TYPE_ERROR,
)
extra_context_dict['errors'] = errors
if not errors:
client = client_form.save()
aggregate = agg_form.save(commit=False)
aggregate.client = client
aggregate.save()
agg_form.save_m2m()
aggregate.save()
# Update agg_id to sync its resources
agg_id = aggregate.pk
# Get resources from SampleResource AM's xmlrpc server every time the AM is updated
try:
do_sync = True
if agg_form.is_bound:
do_sync = agg_form.data.get("sync_resources")
else:
do_sync = agg_form.initial.get("sync_resources")
if do_sync:
failed_resources = sync_am_resources(agg_id, s)
if failed_resources:
DatedMessage.objects.post_message_to_user(
"Could not synchronize resources %s within Expedient" % str(failed_resources),
user=request.user, msg_type=DatedMessage.TYPE_WARNING,
)
except:
warning = "Could not synchronize AM resources within Expedient"
DatedMessage.objects.post_message_to_user(
errors, user=request.user, msg_type=DatedMessage.TYPE_WARNING,
)
extra_context_dict['errors'] = warning
give_permission_to(
"can_use_aggregate",
aggregate,
request.user,
can_delegate=True
)
give_permission_to(
"can_edit_aggregate",
aggregate,
request.user,
can_delegate=True
)
DatedMessage.objects.post_message_to_user(
"Successfully created/updated aggregate %s" % aggregate.name,
user=request.user, msg_type=DatedMessage.TYPE_SUCCESS,
)
return HttpResponseRedirect("/")
else:
return HttpResponseNotAllowed("GET", "POST")
if not errors:
extra_context_dict['available'] = aggregate.check_status() if agg_id else False
# Updates the dictionary with the common fields
extra_context_dict.update({
"agg_form": agg_form,
"client_form": client_form,
"create": not agg_id,
"aggregate": aggregate,
"breadcrumbs": (
('Home', reverse("home")),
("%s SampleResource Aggregate" % ("Update" if agg_id else "Create"),
request.path),
)
})
return simple.direct_to_template(
request,
template="sample_resource_aggregate_crud.html",
extra_context=extra_context_dict
)
0
Example 148
Project: courtlistener Source File: views.py
@never_cache
def show_results(request):
"""
This view can vary significantly, depending on how it is called:
- In its most simple form, it is called via GET and without any
parameters.
--> This loads the homepage.
- It might also be called with GET *with* parameters.
--> This loads search results.
- It might be called with a POST.
--> This attempts to save an alert.
It also has a few failure modes it needs to support:
- It must react properly to an invalid alert form.
- It must react properly to an invalid or failing search form.
All of these paths have tests.
"""
# Create a search string that does not contain the page numbers
get_string = make_get_string(request)
get_string_sans_alert = make_get_string(request, ['page', 'edit_alert'])
render_dict = {
'private': True,
'get_string': get_string,
'get_string_sans_alert': get_string_sans_alert,
}
if request.method == 'POST':
# The user is trying to save an alert.
alert_form = CreateAlertForm(request.POST, user=request.user)
if alert_form.is_valid():
cd = alert_form.cleaned_data
# save the alert
if request.POST.get('edit_alert'):
# check if the user can edit this, or if they are url hacking
alert = get_object_or_404(
Alert,
pk=request.POST.get('edit_alert'),
user=request.user,
)
alert_form = CreateAlertForm(cd, instance=alert,
user=request.user)
alert_form.save()
action = "edited"
else:
alert_form = CreateAlertForm(cd, user=request.user)
alert = alert_form.save(commit=False)
alert.user = request.user
alert.save()
action = "created"
messages.add_message(request, messages.SUCCESS,
'Your alert was %s successfully.' % action)
# and redirect to the alerts page
return HttpResponseRedirect(reverse("profile_alerts"))
else:
# Invalid form. Do the search again and show them the alert form
# with the errors
render_dict.update(do_search(request))
render_dict.update({'alert_form': alert_form})
return render_to_response(
'search.html',
render_dict,
RequestContext(request),
)
else:
# Either a search or the homepage
if len(request.GET) == 0:
# No parameters --> Homepage.
if not is_bot(request):
tally_stat('search.homepage_loaded')
# Load the render_dict with good results that can be shown in the
# "Latest Cases" section
render_dict.update(do_search(request, rows=5,
order_by='dateFiled desc',
facet=False))
# Get the results from the oral arguments as well
oa_dict = do_search(request, rows=5, order_by='dateArgued desc',
type='oa', facet=False)
render_dict.update({'results_oa': oa_dict['results']})
# But give it a fresh form for the advanced search section
render_dict.update({'search_form': SearchForm(request.GET)})
# Get a bunch of stats.
render_dict.update(get_homepage_stats())
return render_to_response(
'homepage.html',
render_dict,
RequestContext(request)
)
else:
# User placed a search or is trying to edit an alert
if request.GET.get('edit_alert'):
# They're editing an alert
if request.user.is_anonymous():
return HttpResponseRedirect(
"{path}?next={next}{encoded_params}".format(
path=reverse('sign-in'),
next=request.path,
encoded_params=quote("?" + request.GET.urlencode())
))
else:
alert = get_object_or_404(
Alert,
pk=request.GET.get('edit_alert'),
user=request.user
)
alert_form = CreateAlertForm(
instance=alert,
initial={'query': get_string_sans_alert},
user=request.user,
)
else:
# Just a regular search
if not is_bot(request):
tally_stat('search.results')
# Create bare-bones alert form.
alert_form = CreateAlertForm(
initial={'query': get_string,
'rate': "dly"},
user=request.user
)
render_dict.update(do_search(request))
render_dict.update({'alert_form': alert_form})
return render_to_response(
'search.html',
render_dict,
RequestContext(request),
)
0
Example 149
Project: synnefo Source File: projects.py
@project_view(post=True)
def project_or_app_detail(request, project_uuid, app_id=None):
project = get_object_or_404(Project, uuid=project_uuid)
application = None
if app_id:
application = get_object_or_404(ProjectApplication, id=app_id)
app_check_allowed(application, request.user)
if request.method == "POST":
raise PermissionDenied
if project.state in [Project.O_PENDING] and not application and \
project.last_application:
return redirect(reverse('project_app',
args=(project.uuid,
project.last_application.id,)))
members = project.projectmembership_set
# handle members form submission
if request.method == 'POST' and not application:
project_check_allowed(project, request.user)
addmembers_form = AddProjectMembersForm(
request.POST,
project_id=project.pk,
request_user=request.user)
with ExceptionHandler(request):
handle_valid_members_form(request, project.pk, addmembers_form)
if addmembers_form.is_valid():
addmembers_form = AddProjectMembersForm() # clear form data
else:
addmembers_form = AddProjectMembersForm() # initialize form
approved_members_count = project.members_count()
pending_members_count = project.count_pending_memberships()
_limit = project.limit_on_members_number
remaining_memberships_count = (max(0, _limit - approved_members_count)
if _limit is not None else None)
members = members.associated()
members = members.select_related()
members_table = tables.ProjectMembersTable(project,
members,
user=request.user,
prefix="members_")
paginate = {"per_page": settings.PAGINATE_BY}
RequestConfig(request, paginate=paginate).configure(members_table)
user = request.user
owns_base = False
if project and project.is_base and \
project.realname == "system:%s" % request.user.uuid:
owns_base = True
is_project_admin = user.is_project_admin()
is_owner = user.owns_project(project)
is_applicant = False
last_pending_app = project.last_pending_application()
if last_pending_app:
is_applicant = last_pending_app and \
last_pending_app.applicant.pk == user.pk
if not (is_owner or is_project_admin) and \
not user.non_owner_can_view(project):
m = _(astakos_messages.NOT_ALLOWED)
raise PermissionDenied(m)
if project and project.is_base and not (owns_base or is_project_admin):
m = _(astakos_messages.NOT_ALLOWED)
raise PermissionDenied(m)
membership = user.get_membership(project) if project else None
membership_id = membership.id if membership else None
mem_display = user.membership_display(project) if project else None
can_join_req = can_join_request(project, user) if project else False
can_leave_req = can_leave_request(project, user) if project else False
can_cancel_req = \
can_cancel_join_request(project, user) if project else False
is_modification = application.is_modification() if application else False
queryset = Project.objects.select_related()
object_id = project.pk
resources_set = project.resource_set
template_name = "im/projects/project_detail.html"
if application:
queryset = ProjectApplication.objects.select_related()
object_id = application.pk
is_applicant = application.applicant.pk == user.pk
resources_set = application.resource_set
template_name = "im/projects/project_application_detail.html"
display_usage = False
if (owns_base or is_owner or membership or is_project_admin) \
and not app_id:
display_usage = True
return DetailViewExtra.as_view(
queryset=queryset,
template_name=template_name,
extra_context={
'project': project,
'application': application,
'is_application': bool(application),
'display_usage': display_usage,
'is_modification': is_modification,
'addmembers_form': addmembers_form,
'approved_members_count': approved_members_count,
'pending_members_count': pending_members_count,
'members_table': members_table,
'owner_mode': is_owner,
'admin_mode': is_project_admin,
'applicant_mode': is_applicant,
'mem_display': mem_display,
'membership_id': membership_id,
'can_join_request': can_join_req,
'can_leave_request': can_leave_req,
'can_cancel_join_request': can_cancel_req,
'resources_set': resources_set,
'last_app': None if application else project.last_application,
'remaining_memberships_count': remaining_memberships_count
})(request, pk=object_id)
0
Example 150
Project: karaage Source File: views.py
@usage_required
def institute_usage(request, institute_id, machine_category_id):
result = progress(request)
if result is not None:
return result
machine_category = get_object_or_404(
MachineCategory, pk=machine_category_id)
institute = get_object_or_404(Institute, pk=institute_id)
start, end = get_date_range(request)
result = gen_cache_for_machine_category(
request, start, end, machine_category)
if result is not None:
return render(
template_name='kgusage/progress.html',
context={'task_id': result.task_id},
request=request)
result = gen_cache_for_institute(
request, start, end, institute, machine_category)
if result is not None:
return render(
template_name='kgusage/progress.html',
context={'task_id': result.task_id},
request=request)
project_list = []
institute_list = Institute.active.all()
if (not institute.can_view(request) and
not getattr(settings, 'USAGE_IS_PUBLIC', False)):
return HttpResponseForbidden('<h1>Access Denied</h1>')
mc_cache = usage.get_machine_category_usage(machine_category, start, end)
available_time = mc_cache.available_time
quota = get_object_or_404(
InstituteQuota, institute=institute, machine_category=machine_category)
i_usage, i_jobs = usage.get_institute_usage(
institute, start, end, machine_category)
for p_cache in models.ProjectCache.objects.filter(
project__institute=institute,
machine_category=machine_category,
date=datetime.date.today(), start=start, end=end):
p = p_cache.project
p_usage = p_cache.cpu_time
p_jobs = p_cache.no_jobs
try:
chunk = p.projectquota_set.get(machine_category=machine_category)
except ProjectQuota.DoesNotExist:
chunk = None
if chunk is None and p_usage == 0 and p_jobs == 0:
continue
if chunk is not None:
mpots = mc_cache.get_project_mpots(chunk, start, end)
percent = mc_cache.get_project_cap_percent(chunk, start, end)
else:
mpots = None
percent = None
if available_time > 0 and quota.quota > 0:
quota_percent = p_usage / (available_time * quota.quota) * 10000
else:
quota_percent = 0
project_list.append(
{'project': p,
'usage': p_usage,
'jobs': p_jobs,
'percent': percent,
'quota_percent': quota_percent,
})
person_list = []
person_total, person_total_jobs = 0, 0
query = models.PersonCache.objects.filter(
project__institute=institute,
machine_category=machine_category,
date=datetime.date.today(), start=start, end=end)
query = query.order_by('-cpu_time')
for u in query[:5]:
person_total += u.cpu_time
person_total_jobs += u.no_jobs
if i_usage > 0:
i_percent = (u.cpu_time / i_usage) * 100
else:
i_percent = None
if available_time > 0 and quota.quota > 0:
quota_percent = u.cpu_time / (available_time * quota.quota) * 10000
else:
quota_percent = 0
person_list.append(
{'person': u.person,
'project': u.project,
'usage': u.cpu_time,
'jobs': u.no_jobs,
'percent': i_percent,
'quota_percent': quota_percent,
})
if i_usage > 0:
person_percent = (person_total / i_usage) * 100
else:
person_percent = None
graph = graphs.get_institute_trend_graph_url(
institute, start, end, machine_category)
return render(
template_name='kgusage/usage_institute_detail.html',
context=locals(),
request=request)