Here are the examples of the python api django.contrib.messages.info taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
179 Examples
0
Example 101
def send_message(self, email_outbox_message):
"""
Creates a task for async sending an EmailOutboxMessage and sets messages for feedback.
Args:
email_outbox_message (instance): EmailOutboxMessage instance
Returns:
Task instance
"""
send_logger = logging.getLogger('email_errors_temp_logger')
send_logger.info('Begin creating task for email_outbox_message %d to %s' % (
email_outbox_message.id, email_outbox_message.to
))
task = send_message.apply_async(
args=(email_outbox_message.id,),
max_retries=1,
default_retry_delay=100,
)
send_logger.info('Task (%s) status %s for email_outbox_message %d' % (
task.id, task.status, email_outbox_message.id
))
if task.status is not FAILURE:
messages.info(
self.request,
_('Gonna deliver your email as fast as I can.')
)
self.request.session['tasks'].update({'send_message': task.id})
self.request.session.modified = True
else:
messages.error(
self.request,
_('Sorry, I couldn\'t send your email.')
)
send_logger.error(_('Failed to create send_message task (%s) outbox message id was %d. TRACE: %s') % (
task.id, email_outbox_message.id, task.traceback
))
return task
0
Example 102
Project: comics Source File: views.py
@login_required
def mycomics_edit_comics(request):
"""Change multiple comics in My comics"""
if request.method != 'POST':
response = HttpResponse(status=405)
response['Allowed'] = 'POST'
return response
my_comics = request.user.comics_profile.comics.all()
for comic in my_comics:
if comic.slug not in request.POST:
subscriptions = Subscription.objects.filter(
userprofile=request.user.comics_profile, comic=comic)
subscriptions.delete()
if not request.is_ajax():
messages.info(
request, 'Removed "%s" from my comics' % comic.name)
for comic in Comic.objects.all():
if comic.slug in request.POST and comic not in my_comics:
subscription = Subscription(
userprofile=request.user.comics_profile, comic=comic)
subscription.save()
if not request.is_ajax():
messages.info(request, 'Added "%s" to my comics' % comic.name)
if request.is_ajax():
return HttpResponse(status=204)
elif 'HTTP_REFERER' in request.META:
return HttpResponseRedirect(request.META['HTTP_REFERER'])
else:
return HttpResponseRedirect(reverse('mycomics_latest'))
0
Example 103
Project: 1flow Source File: preferences.py
def preferences(request):
""" Return preferences view. """
user = request.user
preferences = user.preferences
preferences.check()
if request.POST:
home_form = HomePreferencesForm(
request.POST, instance=preferences.home)
reading_form = ReadPreferencesForm(
request.POST, instance=preferences.read)
notifications_form = NotificationsPreferencesForm(
request.POST, instance=preferences.notifications)
sources_form = SelectorPreferencesForm(
request.POST, instance=preferences.selector)
if user.is_superuser:
staff_form = StaffPreferencesForm(
request.POST, instance=preferences.staff)
if home_form.is_valid() and reading_form.is_valid() \
and sources_form.is_valid() and notifications_form.is_valid() \
and (
(user.is_superuser or user.is_staff)
and staff_form.is_valid()
):
changed = home_form.instance.has_changed \
or reading_form.instance.has_changed \
or notifications_form.instance.has_changed \
or sources_form.instance.has_changed \
or (
(user.is_superuser or user.is_staff)
and staff_form.instance.has_changed)
# form.save() does nothing on an embedded docuement,
# which needs to be saved from the container.
preferences.home = home_form.save()
preferences.read = reading_form.save()
preferences.notifications = notifications_form.save()
preferences.selector = sources_form.save()
if user.is_superuser or user.is_staff:
preferences.staff = staff_form.save()
if changed:
messages.info(request, _(u'Preferences updated.'))
preferences.save()
return redirect('preferences')
else:
home_form = HomePreferencesForm(
instance=request.user.preferences.home)
reading_form = ReadPreferencesForm(
instance=request.user.preferences.read)
notifications_form = NotificationsPreferencesForm(
instance=request.user.preferences.notifications)
sources_form = SelectorPreferencesForm(
instance=request.user.preferences.selector)
if request.user.is_superuser:
staff_form = StaffPreferencesForm(
instance=request.user.preferences.staff)
else:
staff_form = None
return render(request, 'preferences.html', {
'home_form': home_form,
'reading_form': reading_form,
'sources_form': sources_form,
'notifications_form': notifications_form,
'staff_form': staff_form,
})
0
Example 104
Project: element43 Source File: views.py
def reset_password(request):
"""
View for resetting a user's password
"""
if request.method == 'POST':
form = ResetPasswordForm(request.POST)
if form.is_valid():
# Generate password
new_password = User.objects.make_random_password(length=16, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
user = User.objects.get(username__exact=form.cleaned_data.get('username'),
email__exact=form.cleaned_data.get('email'))
# Send password reset mail
text = get_template('mail/reset_password.txt')
html = get_template('mail/reset_password.haml')
mail_context = Context({'username': form.cleaned_data.get('username'), 'new_password': new_password})
text_content = text.render(mail_context)
html_content = html.render(mail_context)
message = EmailMultiAlternatives('Element43 password reset',
text_content, settings.DEFAULT_FROM_EMAIL,
[form.cleaned_data.get('email')])
message.attach_alternative(html_content, "text/html")
message.send()
# Save new password
user.set_password(new_password)
user.save()
# Add success message
messages.info(request, 'A new password has been sent to your e-mail address.')
# Redirect home
return HttpResponseRedirect(reverse('home'))
else:
form = ResetPasswordForm()
rcontext = RequestContext(request, {})
return render_to_response('reset_password.haml', {'form': form}, rcontext)
0
Example 105
def message_user(self, request, message):
# Copied from django.contrib.admin.options
# Included to mimic admin actions
messages.info(request, message)
0
Example 106
Project: cdr-stats Source File: admin.py
def rebilling(self, request):
"""
Re-billing successful VoIP Calls
"""
opts = VoIPPlan._meta
# default values for form
tday = datetime.today()
to_date = from_date = tday.strftime('%Y-%m-%d')
form = RebillForm(request.POST or None,
initial={'from_date': from_date, 'to_date': to_date,
'confirmation': CONFIRMATION_TYPE.NO})
call_rebill_count = 0
if request.method == 'POST':
form = RebillForm(request.POST)
if "from_date" in request.POST:
# From
from_date = request.POST['from_date']
start_date = ceil_strdate(from_date, 'start')
if "to_date" in request.POST:
# To
to_date = request.POST['to_date']
end_date = ceil_strdate(to_date, 'end')
call_kwargs = {}
daily_kwargs = {}
monthly_kwargs = {}
if start_date and end_date:
call_kwargs['start_uepoch'] = {'$gte': start_date, '$lt': end_date}
# get kwargs for aggregate
daily_kwargs['metadata.date'] = {'$gte': start_date.strftime('%Y-%m-%d'),
'$lt': end_date.strftime('%Y-%m-%d')}
monthly_kwargs['metadata.date'] = {'$gte': start_date.strftime('%Y-%m'),
'$lt': end_date.strftime('%Y-%m')}
if not request.user.is_superuser: # not superuser
call_kwargs['accountcode'] = request.user.userprofile.accountcode
monthly_kwargs['metadata.accountcode'] =\
daily_kwargs['metadata.accountcode'] = call_kwargs['accountcode']
# Get total no of calls which are going to rebill
# call_rebill_count = mongodb.cdr_common.find(call_kwargs).count()
if "confirmation" in request.POST:
confirmation = request.POST.get('confirmation')
# To confirm re-billing
if confirmation == CONFIRMATION_TYPE.NO:
request.POST['confirmation'] = CONFIRMATION_TYPE.YES
form.fields['from_date'].widget = form.fields['to_date'].widget = forms.HiddenInput()
ctx = RequestContext(request, {
'form': form,
'start_date': start_date,
'end_date': end_date,
'opts': opts,
'model_name': opts.object_name.lower(),
'title': _('Rebill VoIP Call'),
'call_rebill_count': call_rebill_count,
'CONFIRMATION_TYPE': CONFIRMATION_TYPE,
})
return render_to_response('admin/voip_billing/voipplan/rebilling.html', context_instance=ctx)
voipplan_id = request.user.userprofile.voipplan_id
# re-billing is confirmed by user
if confirmation == CONFIRMATION_TYPE.YES:
if call_rebill_count != 0:
# Rebill all calls
RebillingTask.delay(call_kwargs, voipplan_id)
msg = _('Re-billing is done')
messages.info(request, msg)
request.POST['confirmation'] = CONFIRMATION_TYPE.NO
call_rebill_count = 0
ctx = RequestContext(request, {
'form': form,
'opts': opts,
'model_name': opts.object_name.lower(),
'title': _('Rebill VoIP Call'),
'call_rebill_count': call_rebill_count,
})
return render_to_response('admin/voip_billing/voipplan/rebilling.html', context_instance=ctx)
0
Example 107
Project: hydroshare Source File: page_processors.py
@processor_for(TimeSeriesResource)
def landing_page(request, page):
"""
A typical Mezzanine page processor.
"""
content_model = page.get_content_model()
edit_resource = page_processors.check_resource_mode(request)
if content_model.metadata.is_dirty and content_model.can_update_sqlite_file:
messages.info(request, "SQLite file is out of sync with metadata changes.")
extended_metadata_exists = False
if content_model.metadata.sites or \
content_model.metadata.variables or \
content_model.metadata.methods or \
content_model.metadata.processing_levels or \
content_model.metadata.time_series_results:
extended_metadata_exists = True
series_ids = {}
if content_model.has_csv_file and content_model.metadata.series_names:
# this condition is true if the user has uploaded a csv file and the blank
# sqlite file (added by the system) has never been synced before with metadata changes
for index, series_name in enumerate(content_model.metadata.series_names):
series_ids[str(index)] = series_name
else:
for result in content_model.metadata.time_series_results:
series_id = result.series_ids[0]
series_ids[series_id] = _get_series_label(series_id, content_model)
# sort the dict on series names - item[1]
series_ids = OrderedDict(sorted(series_ids.items(), key=lambda item: item[1].lower()))
if 'series_id' in request.GET:
selected_series_id = request.GET['series_id']
if selected_series_id not in series_ids.keys():
# this will happen only in case of CSV file upload when data is written
# first time to the blank sqlite file as the series ids get changed to
# uuids
selected_series_id = series_ids.keys()[0]
if 'series_id' in request.session:
if selected_series_id != request.session['series_id']:
is_resource_specific_tab_active = True
request.session['series_id'] = selected_series_id
else:
is_resource_specific_tab_active = False
else:
request.session['series_id'] = selected_series_id
is_resource_specific_tab_active = False
else:
selected_series_id = series_ids.keys()[0] if series_ids.keys() else None
request.session['series_id'] = selected_series_id
is_resource_specific_tab_active = False
ts_result_value_count = None
if content_model.metadata.series_names and selected_series_id is not None:
sorted_series_names = sorted(content_model.metadata.series_names)
selected_series_name = sorted_series_names[int(selected_series_id)]
ts_result_value_count = int(content_model.metadata.value_counts[selected_series_name])
# view depends on whether the resource is being edited
if not edit_resource:
# resource in VIEW Mode
context = _get_resource_view_context(page, request, content_model, selected_series_id,
series_ids, extended_metadata_exists)
else:
# resource in EDIT Mode
context = _get_resource_edit_context(page, request, content_model, selected_series_id,
series_ids, ts_result_value_count,
extended_metadata_exists)
context['is_resource_specific_tab_active'] = is_resource_specific_tab_active
# TODO: can we refactor to make it impossible to skip adding the generic context
hs_core_context = add_generic_context(request, page)
context.update(hs_core_context)
return context
0
Example 108
Project: btb Source File: views.py
def post_detail(request, post_id=None, slug=None):
try:
post = Docuement.objects.public().get(type="post", pk=post_id)
except Docuement.DoesNotExist:
raise Http404
if post.get_slug() != slug:
return redirect(post.get_absolute_url())
#
# Comment processing
#
# Session pending_comment is set if an unauthenticated user tries to
# comment.
pending_comment = request.session.pop('pending_comment', None)
if pending_comment and pending_comment['comment'] and \
pending_comment['path'] == request.path:
form = CommentForm({
'comment': pending_comment['comment']
})
else:
form = CommentForm(request.POST or None)
if form.is_valid():
if post.author.profile.comments_disabled:
raise PermissionDenied
if request.user.is_authenticated():
# Use get_or_create to avoid duplicates
comment, created = Comment.objects.get_or_create(
docuement=post,
comment=form.cleaned_data['comment'],
user=request.user,
)
if created:
comment.docuement = post
#XXX: akismet?
return redirect("%s#c%s" % (request.path, comment.pk))
else:
request.session['pending_comment'] = {
'comment': form.cleaned_data['comment'],
'path': request.path,
}
messages.info(request,
"To post a reply, you need to log in or sign up.")
request.session['after_login'] = request.path
return redirect_to_login(request.path)
# Docuement pages
if post.body:
# No pages for textual posts. XXX This is largely untested, and
# should probably be removed.
docuementpages = []
remaining = None
docuementpage_count = 0
else:
# Pagination for long posts
try:
max_page = (int(request.GET.get('minorder', 0)) +
settings.SCAN_PAGES_PER_PAGE)
except ValueError:
max_page = settings.SCAN_PAGES_PER_PAGE
pages = post.docuementpage_set.all()
docuementpage_count = pages.count()
docuementpages = pages[0:max_page]
remaining = max(0, docuementpage_count - max_page)
related_items = list(DocuementPage.objects.filter(order=0,
docuement__author__pk=post.author_id,
docuement__status="published",
docuement__type="post",
).exclude(
docuement__pk=post.pk
).select_related(
'docuement'
).order_by('-docuement__created')[:6])
related = {
'more': post.author.profile.get_blog_url() if len(related_items) == 6 else None,
'title': "Other posts by this author",
'items': related_items,
}
context = get_nav_context()
context.update({
'post': post,
'org': post.author.organization_set.get(),
'docuementpages': docuementpages,
'docuementpage_count': docuementpage_count,
'remaining': remaining,
'comments': post.comments.with_mailed_annotation(),
'comment_form': form,
'related': related,
})
return render(request, "blogs/post_detail.html", context)
0
Example 109
Project: indextank-service Source File: views.py
@login_required
def heroku_dashboard(request):
# Possible statuses:
# - No index
# - Index but no docs
# - Index with docs
account_status = None
if request.user.get_profile().change_password:
messages.info(request, 'Your password was reset and you need to change it.')
return HttpResponseRedirect(reverse('change_password'))
account = request.user.get_profile().account
indexes = account.indexes.all()
has_indexes_left = (len(indexes) < account.package.max_indexes)
totals = dict(size=0, docs=0, qpd=0)
for index in indexes:
totals['docs'] += index.current_docs_number
totals['size'] += index.current_size
totals['qpd'] += index.queries_per_day
if len(indexes) == 0:
account_status = 'NOINDEX'
elif totals['docs'] == 0:
account_status = 'INDEXNODOCS'
else:
account_status = 'INDEXWITHDOCS'
percentages = {}
def add_percentage(k, max, t, p):
p[k] = 100.0 * t[k] / max
KB = 1024
MB = KB * KB
max_docs = account.package.index_max_size
max_size = account.package.max_size_mb()
max_qpd = account.package.searches_per_day
add_percentage('docs', max_docs, totals, percentages)
add_percentage('size', max_size, totals, percentages)
add_percentage('qpd', max_qpd, totals, percentages)
context = {
'account': account,
'indexes': indexes,
'has_indexes_left': has_indexes_left,
'account_status': account_status,
'totals': totals,
'percentages': percentages,
'navigation_pos': 'dashboard',
}
return render('heroku-dashboard.html', request, context_dict=context)
0
Example 110
Project: explorer Source File: views.py
@assert_valid_coin_symbol
@render_to('setup_address_forwarding.html')
def setup_address_forwarding(request, coin_symbol):
# kind of tricky because we have to deal with both logged in and new users
already_authenticated = request.user.is_authenticated()
initial = {'coin_symbol': coin_symbol}
if already_authenticated:
form = KnownUserAddressForwardingForm(initial=initial)
else:
form = NewUserAddressForwardingForm(initial=initial)
if request.method == 'POST':
if already_authenticated:
form = KnownUserAddressForwardingForm(data=request.POST)
else:
form = NewUserAddressForwardingForm(data=request.POST)
if form.is_valid():
coin_symbol = form.cleaned_data['coin_symbol']
destination_address = form.cleaned_data['coin_address']
user_email = form.cleaned_data.get('email')
# optional. null in case of KnownUserAddressForwardingForm
if already_authenticated:
auth_user = request.user
else:
auth_user = None
if user_email:
# Check for existing user with that email
existing_user = get_object_or_None(AuthUser, email=user_email)
if existing_user:
msg = _('Please first login to this account to create a notification')
messages.info(request, msg)
return HttpResponseRedirect(existing_user.get_login_uri())
else:
# Create user with unknown (random) password
auth_user = AuthUser.objects.create_user(
email=user_email,
password=None, # it will create a random pw
creation_ip=get_client_ip(request),
creation_user_agent=get_user_agent(request),
)
# Login the user
# http://stackoverflow.com/a/3807891/1754586
auth_user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, auth_user)
# Log the login
LoggedLogin.record_login(request)
else:
# No user email given, proceed anonymously
# FIXME: confirm this
pass
# Setup Payment Forwarding
forwarding_address_details = get_forwarding_address_details(
destination_address=destination_address,
api_key=BLOCKCYPHER_API_KEY,
callback_url=None, # notifications happen separately (and not always)
coin_symbol=coin_symbol,
)
if 'error' in forwarding_address_details:
# Display error message back to user
messages.warning(request, forwarding_address_details['error'], extra_tags='safe')
else:
initial_address = forwarding_address_details['input_address']
# create forwarding object
address_forwarding_obj = AddressForwarding.objects.create(
coin_symbol=coin_symbol,
initial_address=initial_address,
destination_address=destination_address,
auth_user=auth_user,
blockcypher_id=forwarding_address_details['id'],
)
subscribe_uri = reverse('subscribe_address', kwargs={'coin_symbol': coin_symbol})
uri_qs = {'a': initial_address}
if user_email:
uri_qs['e'] = user_email
if already_authenticated:
uri_qs['e'] = auth_user.email
subscribe_uri = '%s?%s' % (subscribe_uri, urlencode(uri_qs))
initial_addr_uri = reverse('address_overview', kwargs={
'coin_symbol': coin_symbol,
'address': initial_address,
})
destination_addr_uri = reverse('address_overview', kwargs={
'coin_symbol': coin_symbol,
'address': destination_address,
})
msg_merge_dict = {
'initial_address': initial_address,
'initial_addr_uri': initial_addr_uri,
'destination_address': destination_address,
'destination_addr_uri': destination_addr_uri,
'subscribe_uri': subscribe_uri,
'small_payments_msg': SMALL_PAYMENTS_MSG,
}
if auth_user:
msg_merge_dict['user_email'] = auth_user.email
if user_email or (already_authenticated and form.cleaned_data['wants_email_notification']):
# Create an address subscription for all of these cases
# Hit blockcypher and return subscription id
callback_uri = reverse('address_webhook', kwargs={
'secret_key': WEBHOOK_SECRET_KEY,
# hack for rare case of two webhooks requested on same address:
'ignored_key': simple_pw_generator(num_chars=10),
})
callback_url = uri_to_url(callback_uri)
bcy_id = subscribe_to_address_webhook(
subscription_address=initial_address,
callback_url=callback_url,
coin_symbol=coin_symbol,
api_key=BLOCKCYPHER_API_KEY,
)
# only notify for deposits
AddressSubscription.objects.create(
coin_symbol=coin_symbol,
b58_address=initial_address,
auth_user=auth_user,
blockcypher_id=bcy_id,
notify_on_deposit=True,
notify_on_withdrawal=False,
address_forwarding_obj=address_forwarding_obj,
)
if user_email:
# New signup
msg = _('''
Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>,
but you must confirm your email to receive notifications.
<br /><br /> <i>%(small_payments_msg)s</i>
''' % msg_merge_dict)
messages.success(request, msg, extra_tags='safe')
address_forwarding_obj.send_forwarding_welcome_email()
return HttpResponseRedirect(reverse('unconfirmed_email'))
else:
if auth_user.email_verified:
msg = _('''
Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>,
and you will immediately receive an email notification at <b>%(user_email)s</b>.
<br /><br /> <i>%(small_payments_msg)s</i>
''' % msg_merge_dict)
messages.success(request, msg, extra_tags='safe')
return HttpResponseRedirect(reverse('dashboard'))
else:
# existing unconfirmed user
msg = _('''
Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>,
but you must confirm your email to receive notifications.
<br /><br /> <i>%(small_payments_msg)s</i>
''' % msg_merge_dict)
messages.success(request, msg, extra_tags='safe')
address_forwarding_obj.send_forwarding_welcome_email()
return HttpResponseRedirect(reverse('unconfirmed_email'))
elif already_authenticated:
# already authenticated and doesn't want subscriptions
msg = _('''
Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>.
You will not receive email notifications (<a href="%(subscribe_uri)s">subscribe</a>).
<br /><br /> <i>%(small_payments_msg)s</i>
''' % msg_merge_dict)
messages.success(request, msg, extra_tags='safe')
return HttpResponseRedirect(reverse('dashboard'))
else:
# New signup sans email
msg = _('''
Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>.
You will not receive email notifications (<a href="%(subscribe_uri)s">subscribe</a>).
<br /><br /> <i>%(small_payments_msg)s</i>
''' % msg_merge_dict)
messages.success(request, msg, extra_tags='safe')
return HttpResponseRedirect(destination_addr_uri)
elif request.method == 'GET':
coin_address = request.GET.get('a')
subscriber_email = request.GET.get('e')
if coin_address:
initial['coin_address'] = coin_address
if subscriber_email and not already_authenticated:
initial['email'] = subscriber_email
if coin_address or subscriber_email:
if already_authenticated:
form = KnownUserAddressForwardingForm(initial=initial)
else:
form = NewUserAddressForwardingForm(initial=initial)
return {
'form': form,
'coin_symbol': coin_symbol,
'is_input_page': True,
}
0
Example 111
Project: djiki Source File: views.py
def view(request, title, revision_pk=None):
url_title = utils.urlize_title(title)
if title != url_title:
if revision_pk:
return HttpResponseRedirect(reverse('djiki-page-revision',
kwargs={'title': url_title, 'revision_pk': revision_pk}))
return HttpResponseRedirect(reverse('djiki-page-view', kwargs={'title': url_title}))
page_title = utils.deurlize_title(title)
auth = utils.get_auth_backend()
try:
page = models.Page.objects.get(title=page_title)
except models.Page.DoesNotExist:
html = _templating.render_to_string('djiki/not_found.html', {'title': page_title}, request)
return HttpResponseNotFound(html)
if not auth.can_view(request, page):
raise PermissionDenied
if revision_pk:
if not auth.can_view_history(request, page):
raise PermissionDenied
try:
revision = page.revisions.get(pk=revision_pk)
except models.PageRevision.DoesNotExist:
return HttpResponseNotFound()
messages.info(request, mark_safe(_("The version you are viewing is not the latest one, "
"but represents an older revision of this page, which may have been "
"significantly modified. If it is not what you intended to view, "
"<a href=\"%(url)s\">proceed to the latest version</a>.") % {
'url': reverse('djiki-page-view', kwargs={'title': url_title})}))
else:
revision = page.last_revision()
if request.POST.get('raw', request.GET.get('raw','')):
response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename=%s.txt' % quote(title.encode('utf-8'))
response.write(revision.content)
return response
return _templating.render_to_response(request, 'djiki/view.html',
{'page': page, 'revision': revision})
0
Example 112
Project: django-pki Source File: views.py
@login_required
def admin_delete(request, model, id):
"""Overwite the default admin delete view"""
deleted_objects = []
parent_object_name = CertificateAuthority._meta.verbose_name
title = 'Are you sure?'
if model == 'certificateauthority':
## Get the list of objects to delete as list of lists
item = get_object_or_404(CertificateAuthority, pk=id)
chain_recursion(item.id, deleted_objects, id_dict={ 'cert': [], 'ca': [], })
## Fill the required data for delete_confirmation.html template
opts = CertificateAuthority._meta
object = item.name
initial_id = False
## Set the CA to verify the passphrase against
if item.parent_id:
initial_id = item.parent_id
auth_object = CertificateAuthority.objects.get(pk=item.parent_id).name
else:
initial_id = item.pk
auth_object = item.name
elif model == 'certificate':
## Fetch the certificate data
try:
item = Certificate.objects.select_related().get(pk=id)
except:
raise Http404
if not item.parent_id:
parent_object_name = "self-signed certificate"
initial_id = item.id
authentication_obj = item.name
else:
initial_id = item.parent_id
authentication_obj = item.parent.name
div_content = build_delete_item(item)
deleted_objects.append( mark_safe('Certificate: <a href="%s">%s</a> <img src="%spki/img/plus.png" class="switch" /><div class="details">%s</div>' % \
(urlresolvers.reverse('admin:pki_certificate_change', args=(item.pk,)), item.name, MEDIA_URL, div_content)) )
## Fill the required data for delete_confirmation.html template
opts = Certificate._meta
object = item.name
## Set the CA to verify the passphrase against
auth_object = authentication_obj
if request.method == 'POST':
form = DeleteForm(request.POST)
if form.is_valid():
item.delete(request.POST['passphrase'])
messages.info(request, 'The %s "%s" was deleted successfully.' % (opts.verbose_name, object))
return HttpResponseRedirect(urlresolvers.reverse('admin:pki_%s_changelist' % model))
else:
form = DeleteForm()
form.fields['_model'].initial = model
form.fields['_id'].initial = id
return render_to_response('admin/pki/delete_confirmation.html', { 'deleted_objects': deleted_objects, 'object_name': opts.verbose_name,
'app_label': opts.app_label, 'opts': opts, 'object': object, 'form': form,
'auth_object': auth_object, 'parent_object_name': parent_object_name,
'title': title,
}, RequestContext(request))
0
Example 113
Project: cdr-stats Source File: admin.py
def blacklist_by_country(self, request):
"""Add custom method in django admin view to import CSV file of
Contacts
**Attributes**:
* ``form`` - BWCountryForm()
* ``template`` - admin/cdr_alert/blacklist/blacklist_by_country.html
**Logic Description**:
**Important variable**:
"""
opts = Blacklist._meta
form = BWCountryForm('blacklist', request.POST or None)
prefix_list = []
if form.is_valid():
country = int(request.POST['country'])
prefix_list = Prefix.objects.values('prefix').filter(country_id=country)
msg = _("successfully added prefix into blacklist")
if request.POST.getlist('blacklist_country'):
# blacklist whole country
Blacklist.objects.create(
phonenumber_prefix=int(prefix_list[0]['prefix']),
country=Country.objects.get(pk=country),
user=request.user)
messages.info(request, msg)
return HttpResponseRedirect(reverse("admin:cdr_alert_blacklist_changelist"))
else:
values = request.POST.getlist('select')
if values:
for i in values:
Blacklist.objects.create(
phonenumber_prefix=int(i),
country=Country.objects.get(pk=country),
user=request.user)
messages.info(request, msg)
return HttpResponseRedirect(reverse("admin:cdr_alert_blacklist_changelist"))
ctx = RequestContext(request, {
'title': _('blacklist by country'),
'form': form,
'opts': opts,
'model_name': opts.object_name.lower(),
'prefix_list': prefix_list,
})
return render_to_response('admin/cdr_alert/blacklist/blacklist_by_country.html', context_instance=ctx)
0
Example 114
Project: synnefo Source File: ldap.py
@requires_auth_provider('ldap')
@require_http_methods(["GET", "POST"])
@csrf_exempt
@requires_anonymous
@cookie_fix
@ratelimit(field='username', method='POST', rate=rate)
def login(request, template_name="im/login.html", on_failure='im/login.html',
signup_template="/im/third_party_check_local.html",
extra_context=None):
"""
on_failure: the template name to render on login failure
"""
if request.method == 'GET':
return handle_get_to_login_view(request,
primary_provider=LDAP_PROVIDER,
login_form=LDAPLoginForm(request),
template_name=template_name,
extra_context=extra_context)
# 'limited' attribute is used by recapatcha
was_limited = getattr(request, 'limited', False)
next = get_query(request).get('next', '')
third_party_token = get_query(request).get('key', False)
form = LDAPLoginForm(data=request.POST,
was_limited=was_limited,
request=request)
provider = LDAP_PROVIDER
if not form.is_valid():
if third_party_token:
messages.info(request, provider.get_login_to_add_msg)
return render_to_response(
on_failure,
{'login_form': form,
'next': next,
'key': third_party_token},
context_instance=get_context(request,
primary_provider=LDAP_PROVIDER))
# get the user from the cache
user = form.ldap_user_cache
provider = auth.get_provider('ldap', user)
affiliation = 'LDAP'
provider_info = dict(user.ldap_user.attrs)
try:
user_info = populate_user_attributes(provider, provider_info)
user_id = user_info.pop('identifier')
except (ValueError, KeyError):
logger.exception("Failed to map attributes from LDAP provider."
" Provider attributes: %s", provider_info)
msg = 'Invalid LDAP response. Please contact support.'
messages.error(request, msg)
return HttpResponseRedirect(reverse('login'))
provider_info = dict([(k, smart_unicode(v, errors="ignore"))
for k, v in provider_info.items()
if k in provider.get_provider_info_attributes()])
user_info['affiliation'] = affiliation
if hasattr(user, 'group_names') and provider.get_policy('mirror_groups'):
groups = [Group.objects.get_or_create(name=group_name)[0]
for group_name in user.group_names]
user_info['groups'] = groups
try:
return handle_third_party_login(request, provider_module="ldap",
identifier=user_id,
provider_info=provider_info,
affiliation=affiliation,
user_info=user_info)
except AstakosUser.DoesNotExist:
third_party_key = get_pending_key(request)
return handle_third_party_signup(request, user_id, 'ldap',
third_party_key,
provider_info,
user_info,
signup_template,
extra_context)
0
Example 115
Project: transifex Source File: views.py
def add_permission_or_request(request, obj, view_name, approved=False,
template_name = 'authority/permission_form.html',
extra_context={}):
"""
View for adding either a permission or a permission request for a user.
This view is a centralized place for adding permissions/requests for any
kind of object through the whole Transifex.
Following the upstream django-authority app, all the entries are considered
requests until the field approved be set to True.
For the extra_context, this view expect a key called 'notice' that MUST
have a determinate dictionary structure to be able to send notifications
and save action logs. See the `_send_notice_save_action` function docstring
for more information.
Example of `extra_context` with `notice` key:
# See `_send_notice_save_action` docstring for the `notice` var below
notice = {}
extra_context.update({'notice': notice})
If the key 'notice' is not found in the extra_context parameter, nothing is
executed about notification and action log.
"""
codename = request.POST.get('codename', None)
next = get_next(request, obj)
if request.method == 'POST':
# POST method requires a permission codename
if codename is None:
return HttpResponseForbidden(next)
form = UserAjaxPermissionForm(data=request.POST, obj=obj,
approved=approved, perm=codename,
initial=dict(codename=codename))
if not approved:
# Limit permission request to current user
form.data['user'] = request.user
if form.is_valid():
permission = form.save(request)
if extra_context.has_key('notice'):
# ActionLog & Notification
_send_notice_save_action(request, extra_context['notice'])
if approved:
msg = _('You added a permission.')
else:
msg = _('You added a permission request.')
messages.info(request, msg)
return HttpResponseRedirect(next)
else:
form = None
context = {
'form': form,
'form_url': txurl_for_obj(view_name, obj),
'next': next,
'perm': codename,
'approved': approved,
}
extra_context.update({'notice':None})
context.update(extra_context)
return render_to_response(template_name, context,
context_instance=RequestContext(request))
0
Example 116
def send_message(self, email_outbox_message):
"""
Creates a task to asynchronously reply on an email message.
Args:
email_outbox_message (instance): EmailOutboxMessage instance
Returns:
Task instance
"""
send_logger = logging.getLogger('email_errors_temp_logger')
send_logger.info('Begin creating reply/forward task for email_outbox_message %d to %s' % (
email_outbox_message.id, email_outbox_message.to
))
task = send_message.apply_async(
args=(email_outbox_message.id, self.object.id),
max_retries=1,
default_retry_delay=100,
)
send_logger.info('Reply/forward Task (%s) status %s for email_outbox_message %d' % (
task.id, task.status, email_outbox_message.id
))
if task:
messages.info(
self.request,
_('Sending email as fast as I can.')
)
self.request.session['tasks'].update({'send_message': task.id})
self.request.session.modified = True
else:
messages.error(
self.request,
_('Sorry, I couldn\'t send your email.')
)
logging.error(_('Failed to create %s task for email account %d. Outbox message id was %d.') % (
self.action,
email_outbox_message.send_from,
email_outbox_message.id,
))
return task
0
Example 117
Project: coding-events Source File: events.py
@login_required
@never_cache
def add_event(request):
if request.method == 'POST':
event_form = AddEventForm(data=request.POST, files=request.FILES)
if event_form.is_valid():
picture = request.FILES.get('picture', None)
event_data = {}
try:
if picture:
if picture.size > (256 * 1024):
raise ImageSizeTooLargeException(
'Image size too large.')
event_data['picture'] = process_image(picture)
event_data.update(event_form.cleaned_data)
event_data['creator'] = request.user
# checking if user entered a different email than in her
# profile
if request.user.email != event_data['user_email']:
update_user_email(
request.user.id, event_data['user_email'])
event_data.pop('user_email')
event = create_or_update_event(**event_data)
t = loader.get_template('alerts/thank_you.html')
c = Context({'event': event, })
messages.info(request, t.render(c))
return HttpResponseRedirect(
reverse(
'web.view_event',
args=[
event.pk,
event.slug]))
except ImageSizeTooLargeException:
messages.error(
request, 'The image is just a bit too big for us. '
'Please reduce your image size and try agin.')
except UploadImageError as e:
messages.error(request, e.message)
else:
event_form = AddEventForm(initial={
'user_email': request.user.email,
'contact_person': request.user.email,
})
return render_to_response("pages/add_event.html", {
'form': event_form,
}, context_instance=RequestContext(request))
0
Example 118
Project: django-markupwiki Source File: views.py
@title_check
@user_passes_test(EDITOR_TEST_FUNC)
def edit_article(request, title):
''' edit (or create) an article
Context:
title - title of article being edited
article - article being edited (potentially None)
form - form to edit article
Templates:
edit_article.html - Default template for editing the article.
locked_article.html - Template shown if editing is locked.
'''
try:
article = Article.objects.get(title=title)
except Article.DoesNotExist:
article = None
# check for staff lock
if article and not article.is_editable_by_user(request.user):
return HttpResponseForbidden('not authorized to edit')
if request.method == 'GET':
# either get an empty ArticleForm or one based on latest version
if article:
if not article.get_write_lock(request.user):
# set message and redirect
messages.info(request, 'Someone else is currently editing this page, please wait and try again.')
return redirect(article)
version = article.versions.latest()
form = ArticleForm(data={'body':version.body,
'body_markup_type':version.body_markup_type})
else:
form = ArticleForm()
elif request.method == 'POST':
form = ArticleForm(request.POST)
user = None if request.user.is_anonymous() else request.user
if form.is_valid():
if not article:
# if article doesn't exist create it and start num at 0
article = Article.objects.create(title=title,
creator=user)
num = 0
else:
if not article.get_write_lock(request.user):
# set message and redirect
messages.error(request, 'Your session timed out and someone else is now editing this page.')
return redirect(article)
# otherwise get latest num
num = article.versions.latest().number + 1
# create a new version attached to article specified in name
version = form.save(False)
version.article = article
version.author = user
version.number = num
version.save()
article.get_write_lock(user or request, release=True)
# redirect to view article on save
return redirect(article)
return render_to_response('markupwiki/edit_article.html',
{'title':title, 'article':article, 'form': form},
context_instance=RequestContext(request))
0
Example 119
def info(request, message, buttons=None):
return messages.info(request, render(message, buttons))
0
Example 120
Project: indextank-service Source File: views.py
@login_required
def dashboard(request):
# Possible statuses:
# - No index
# - Index but no docs
# - Index with docs
account_status = None
if request.user.get_profile().change_password:
messages.info(request, 'Your password was reset and you need to change it.')
return HttpResponseRedirect(reverse('change_password'))
account = request.user.get_profile().account
#if not account.package:
# return HttpResponseRedirect(reverse('select_package'))
if not account.status == Account.Statuses.operational and not account.payment_informations.count():
if account.package.base_price > 0:
messages.info(request, 'Before accessing your dashboard you need to enter your payment information')
return HttpResponseRedirect(reverse('enter_payment'))
elif account.status == Account.Statuses.creating:
account.status = Account.Statuses.operational
mail.report_new_account(account)
account.save()
else:
return HttpResponseRedirect(reverse('logout'))
indexes = account.indexes.filter(deleted=False)
has_indexes_left = (len(indexes) < account.package.max_indexes)
totals = dict(size=0, docs=0, qpd=0)
for index in indexes:
totals['docs'] += index.current_docs_number
totals['size'] += index.current_size
totals['qpd'] += index.queries_per_day
if len(indexes) == 0:
account_status = 'NOINDEX'
elif totals['docs'] == 0:
account_status = 'INDEXNODOCS'
else:
account_status = 'INDEXWITHDOCS'
percentages = {}
def add_percentage(k, max, t, p):
p[k] = 100.0 * t[k] / max
KB = 1024
MB = KB * KB
max_docs = account.package.index_max_size
max_size = account.package.max_size_mb()
max_qpd = account.package.searches_per_day
add_percentage('docs', max_docs, totals, percentages)
add_percentage('size', max_size, totals, percentages)
add_percentage('qpd', max_qpd, totals, percentages)
for index in indexes:
insights = {}
insights_update = {}
#for i in index.insights.all():
# try:
# insights[i.code] = json.loads(i.data)
# insights_update[i.code] = i.last_update
# except:
# print 'Failed to load insight %s for %s' % (i.code, index.code)
#index.insights_map = insights
#index.insights_update = insights_update
context = {
'account': account,
'indexes': indexes,
'has_indexes_left': has_indexes_left,
'account_status': account_status,
'totals': totals,
'percentages': percentages,
'navigation_pos': 'dashboard',
}
return render('dashboard.html', request, context_dict=context)
0
Example 121
def message_info(self, message):
info(self.request, message)
0
Example 122
Project: djangosnippets.org Source File: snippets.py
@login_required
def flag_snippet(request, snippet_id, template_name='cab/flag_snippet.html'):
snippet = get_object_or_404(Snippet, id=snippet_id)
snippet_flag = SnippetFlag(snippet=snippet, user=request.user)
if request.method == 'POST':
form = SnippetFlagForm(request.POST, instance=snippet_flag)
if form.is_valid():
snippet_flag = form.save()
admin_link = request.build_absolute_uri(
reverse('admin:cab_snippetflag_changelist')
)
mail_admins(
'Snippet flagged: "%s"' % (snippet.title),
'%s\n\nAdmin link: %s' % (snippet_flag, admin_link),
fail_silently=True,
)
messages.info(request, 'Thank you for helping improve the site!')
return redirect(snippet)
else:
if request.is_ajax():
return redirect(snippet)
messages.error(request, 'Invalid form submission')
else:
form = SnippetFlagForm(instance=snippet_flag)
return render(request, template_name, {
'form': form,
'snippet': snippet,
})
0
Example 123
def get(self, request):
auth_logout(request)
messages.info(request, 'You have been logged out. See you soon.')
return HttpResponseRedirect(reverse('home'))
0
Example 124
Project: django-linkcheck Source File: listeners.py
def handle_rename(sender, path=None, **kwargs):
def isdir(filename):
if filename.count('.'):
return False
else:
return True
old_url = os.path.join(get_relative_media_url(), DIRECTORY, path, kwargs['filename'])
new_url = os.path.join(get_relative_media_url(), DIRECTORY, path, kwargs['new_filename'])
# Renaming a file will cause it's urls to become invalid
# Renaming a directory will cause the urls of all it's contents to become invalid
old_url_qs = Url.objects.filter(url=old_url).filter(status=True)
if isdir(kwargs['filename']):
old_url_qs = Url.objects.filter(url__startswith=old_url).filter(status=True)
old_count = old_url_qs.count()
if old_count:
old_url_qs.update(status=False, message='Missing Docuement')
msg = "Warning. Renaming %s has caused %s link%s to break. Please use the Link Manager to fix them" % (old_url, old_count, old_count>1 and 's' or '')
messages.info(sender, msg)
# The new directory may fix some invalid links, so we also check for that
if isdir(kwargs['new_filename']):
new_count = 0
new_url_qs = Url.objects.filter(url__startswith=new_url).filter(status=False)
for url in new_url_qs:
if url.check_url():
new_count += 1
else:
new_url_qs = Url.objects.filter(url=new_url).filter(status=False)
new_count = new_url_qs.count()
if new_count:
new_url_qs.update(status=True, message='Working docuement link')
if new_count:
msg = "Please note. Renaming %s has corrected %s broken link%s. See the Link Manager for more details" % (new_url, new_count, new_count>1 and 's' or '')
messages.info(sender, msg)
0
Example 125
Project: explorer Source File: views.py
def block_ordered_tx(request, coin_symbol, block_num, tx_num):
block_overview = get_block_overview(
block_representation=block_num,
coin_symbol=coin_symbol,
txn_limit=1,
txn_offset=int(tx_num),
api_key=BLOCKCYPHER_API_KEY,
)
txids = block_overview.get('txids')
if txids:
tx_hash = txids[0]
msg = _('This is transaction <strong>%(tx_num)s</strong> in block <strong>%(block_num)s</strong> (<a href="%(permalink)s">permalink</a>).' % {
'tx_num': tx_num,
'block_num': block_num,
'permalink': reverse('block_ordered_tx', kwargs={
'coin_symbol': coin_symbol,
'block_num': block_num,
'tx_num': tx_num,
}),
})
messages.info(request, msg, extra_tags='safe')
kwargs = {
'coin_symbol': coin_symbol,
'tx_hash': tx_hash,
}
redir_uri = reverse('transaction_overview', kwargs=kwargs) + '#advanced-details'
return HttpResponseRedirect(redir_uri)
else:
msg = _('Sorry, block <strong>%(block_num)s</strong> only has <strong>%(n_tx)s</strong> transactions' % {
'block_num': block_num,
'n_tx': block_overview['n_tx'],
})
messages.warning(request, msg, extra_tags='safe')
kwargs = {
'coin_symbol': coin_symbol,
'block_representation': block_num,
}
return HttpResponseRedirect(reverse('block_overview', kwargs=kwargs))
0
Example 126
Project: 2buntu-blog Source File: views.py
@require_POST
@login_required
@transaction.atomic
def modify(request, action, id):
"""
Attempt to modify the specified article.
"""
article = get_object_or_404(Article, pk=id)
if action == 'submit':
if article.author != request.user or article.status != Article.DRAFT:
raise Http404
article.status = Article.UNAPPROVED
article.save()
template = render_to_string('articles/emails/submit.txt', {
'article': request.build_absolute_uri(article.get_absolute_url()),
})
mail_admins('2buntu Article Submitted', template)
messages.info(request, "The article has been submitted for approval by a staff member.")
elif action == 'publish':
if not request.user.is_staff:
raise Http404
article.status = Article.PUBLISHED
article.save()
messages.info(request, "The article has been published.")
elif action == 'release':
if article.author != request.user or article.cc_license:
raise Http404
article.cc_license = True
article.save()
messages.info(request, "The article is now available under a CC BY-SA 4.0 license.")
return redirect(article)
0
Example 127
Project: django-mongoadmin Source File: views.py
@method_decorator(never_cache)
def change_view(self, request, collection, object_id=None):
cls, admin = self.verify_collection(collection)
if object_id:
docuement = get_docuement_or_404(cls, id=object_id)
form = admin.get_form(request.POST or None, instance=docuement)
add, change = False, True
else:
docuement = None
form = admin.get_form(request.POST or None)
add, change = True, False
if form.is_valid():
docuement = form.save()
msg = _('The %(name)s "%(obj)s" was saved successfully.') % {'name': force_unicode(admin.verbose_name), 'obj': force_unicode(docuement)}
if '_continue' in request.POST:
redirect_url = reverse('mongoadmin:change', args=(collection, str(docuement.pk)))
msg += ' ' + _('You may edit it again below.')
elif '_addanother' in request.POST:
redirect_url = reverse('mongoadmin:add', args=(collection,))
msg += ' ' + (_('You may add another %s below.') % force_unicode(admin.verbose_name))
else:
redirect_url = reverse('mongoadmin:changelist', args=(collection,))
messages.info(request, msg)
return HttpResponseRedirect(redirect_url)
return render_to_response('mongoadmin/change_form.html', {
'docuement': docuement,
'form': form,
'collection': collection,
'admin': admin,
'add': add,
'change': change,
'title': _('Change %s') % admin.verbose_name
}, context_instance=RequestContext(request))
0
Example 128
Project: django-timepiece Source File: views.py
@permission_required('entries.delete_entry')
def delete_entry(request, entry_id):
"""
Give the user the ability to delete a log entry, with a confirmation
beforehand. If this method is invoked via a GET request, a form asking
for a confirmation of intent will be presented to the user. If this method
is invoked via a POST request, the entry will be deleted.
"""
try:
entry = Entry.no_join.get(pk=entry_id, user=request.user)
except Entry.DoesNotExist:
message = 'No such entry found.'
messages.info(request, message)
url = request.GET.get('next', reverse('dashboard'))
return HttpResponseRedirect(url)
if request.method == 'POST':
key = request.POST.get('key', None)
if key and key == entry.delete_key:
entry.delete()
message = 'Deleted {0} for {1}.'.format(entry.activity.name, entry.project)
messages.info(request, message)
url = request.GET.get('next', reverse('dashboard'))
return HttpResponseRedirect(url)
else:
message = 'You are not authorized to delete this entry!'
messages.error(request, message)
return render(request, 'timepiece/entry/delete.html', {
'entry': entry,
})
0
Example 129
def publish(self, request, obj, inline_obj):
inline_obj.status = Article.PUBLISHED
inline_obj.save()
messages.info(request, _("Article published."))
0
Example 130
Project: transifex Source File: views.py
@access_off(team_off)
@login_required
@one_perm_required_or_403(pr_team_deny_member_perm,
(Project, "slug__exact", "project_slug"),
(Language, "code__exact", "language_code"))
@transaction.commit_on_success
def team_join_deny(request, project_slug, language_code, username):
team = get_object_or_404(Team, project__slug=project_slug,
language__code=language_code)
project = team.project
user = get_object_or_404(User, username=username)
access_request = get_object_or_404(TeamAccessRequest, team__pk=team.pk,
user__pk=user.pk)
if request.POST:
try:
access_request.delete()
messages.info(request,_(
"You rejected the request by user '%(user)s' to join the "
"'%(team)s' team."
) % {'user':user, 'team':team.language.name})
# ActionLog & Notification
# TODO: Use signals
nt = 'project_team_join_denied'
context = {'access_request': access_request,
'performer': request.user,
'sender': request.user}
# Logging action
action_logging(request.user, [project, team], nt, context=context)
if settings.ENABLE_NOTICES:
# Send notification for those that are observing this project
txnotification.send_observation_notices_for(project,
signal=nt, extra_context=context)
# Send notification for maintainers, coordinators and the user
notification.send(set(itertools.chain(project.maintainers.all(),
team.coordinators.all(), [access_request.user])), nt, context)
except IntegrityError, e:
transaction.rollback()
logger.error("Something weird happened: %s" % str(e))
return HttpResponseRedirect(reverse("team_detail",
args=[project_slug, language_code]))
0
Example 131
Project: zipfelchappe Source File: views.py
def backer_create_view(request, slug):
""" The main form to back a project. A lot of the magic here comes from
BackProjectForm including all validation. The main job of this view is
to save the pledge_id in the session and redirect to backer_authenticate.
A pledge is created but a user is not yet assigned.
"""
project = get_object_or_404(Project, slug=slug)
ExtraForm = project.extraform()
if project.is_over:
messages.info(request, _('This project has ended and does not accept'
' pledges anymore.'))
return redirect(
'zipfelchappe_project_detail', slug=project.slug)
session_pledge = get_session_pledge(request)
form_kwargs = {'project': project}
# If the session pledge has already been paid for, ignore it.
if session_pledge and session_pledge.project == project:
if session_pledge.status >= session_pledge.FAILED: # Force a new payment-ID.
del request.session['pledge_id']
else:
form_kwargs.update({'instance': session_pledge})
if request.method == 'POST':
form = forms.BackProjectForm(request.POST, **form_kwargs)
extraform = ExtraForm(request.POST, prefix="extra")
if form.is_valid() and extraform.is_valid():
pledge = form.save(commit=False)
pledge.extradata = extraform.clean()
pledge.save()
request.session['pledge_id'] = pledge.id
return redirect('zipfelchappe_backer_authenticate')
else:
form = forms.BackProjectForm(**form_kwargs)
extraform = ExtraForm(prefix="extra")
if request.session.get('pledge_id'):
del request.session['pledge_id']
return ('zipfelchappe/project_back_form.html', {
'project': project,
'form': form,
'extraform': extraform,
})
0
Example 132
Project: cdr-stats Source File: admin.py
def whitelist_by_country(self, request):
"""Add custom method in django admin view to import CSV file of
Contacts
**Attributes**:
* ``form`` - BWCountryForm()
* ``template`` - admin/cdr_alert/whitelist/whitelist_by_country.html
**Logic Description**:
**Important variable**:
"""
opts = Whitelist._meta
form = BWCountryForm('whitelist', request.POST or None)
prefix_list = []
if form.is_valid():
country = int(request.POST['country'])
prefix_list = Prefix.objects.values('prefix').filter(country_id=country)
msg = _("successfully added prefix into whitelist")
if request.POST.getlist('whitelist_country'):
# whitelist whole country
Whitelist.objects.create(
phonenumber_prefix=int(prefix_list[0]['prefix']),
country=Country.objects.get(pk=country),
user=request.user)
messages.info(request, msg)
return HttpResponseRedirect(reverse("admin:cdr_alert_whitelist_changelist"))
else:
values = request.POST.getlist('select')
if values:
for i in values:
Whitelist.objects.create(
phonenumber_prefix=int(i),
country=Country.objects.get(pk=country),
user=request.user)
messages.info(request, msg)
return HttpResponseRedirect(reverse("admin:cdr_alert_whitelist_changelist"))
ctx = RequestContext(request, {
'title': _('whitelist by country'),
'form': form,
'opts': opts,
'model_name': opts.object_name.lower(),
'prefix_list': prefix_list,
})
return render_to_response('admin/cdr_alert/whitelist/whitelist_by_country.html', context_instance=ctx)
0
Example 133
Project: synnefo Source File: local.py
@requires_auth_provider('local')
@require_http_methods(["GET", "POST"])
@csrf_exempt
@requires_anonymous
@cookie_fix
@ratelimit(field='username', method='POST', rate=rate)
def login(request, template_name="im/login.html", on_failure='im/login.html',
extra_context=None):
"""
on_failure: the template name to render on login failure
"""
if request.method == 'GET':
extra_context = extra_context or {}
third_party_token = request.GET.get('key', False)
if third_party_token:
messages.info(request, astakos_messages.AUTH_PROVIDER_LOGIN_TO_ADD)
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('landing'))
extra_context["primary_provider"] = LOCAL_PROVIDER
return render_response(
template_name,
login_form=LoginForm(request=request),
context_instance=get_context(request, extra_context)
)
was_limited = getattr(request, 'limited', False)
form = LoginForm(data=request.POST,
was_limited=was_limited,
request=request)
next = get_query(request).get('next', '')
third_party_token = get_query(request).get('key', False)
provider = auth.get_provider('local')
if not form.is_valid():
if third_party_token:
messages.info(request, provider.get_login_to_add_msg)
return render_to_response(
on_failure,
{'login_form': form,
'next': next,
'key': third_party_token},
context_instance=get_context(request,
primary_provider=LOCAL_PROVIDER))
# get the user from the cache
user = form.user_cache
provider = auth.get_provider('local', user)
if not provider.get_login_policy:
message = provider.get_login_disabled_msg
messages.error(request, message)
return HttpResponseRedirect(reverse('login'))
message = None
if not user:
message = provider.get_authentication_failed_msg
elif not user.is_active:
message = user.get_inactive_message('local')
elif not user.has_auth_provider('local'):
# valid user logged in with no auth providers set, add local provider
# and let him log in
if not user.get_available_auth_providers():
user.add_auth_provider('local')
else:
message = _(astakos_messages.NO_LOCAL_AUTH)
if message:
messages.error(request, message)
return render_to_response(on_failure,
{'login_form': form},
context_instance=RequestContext(request))
response = prepare_response(request, user, next)
if third_party_token:
# use requests to assign the account he just authenticated with with
# a third party provider account
try:
request.user.add_pending_auth_provider(third_party_token)
except PendingThirdPartyUser.DoesNotExist:
provider = auth.get_provider('local', request.user)
messages.error(request, provider.get_add_failed_msg)
provider = user.get_auth_provider('local')
messages.success(request, provider.get_login_success_msg)
response.set_cookie('astakos_last_login_method', 'local')
provider.update_last_login_at()
return response
0
Example 134
def user_passes_test(test_func, login_url=None, message=None):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the user object and returns True if the user passes.
"""
if not login_url:
from .utils import get_login_url
login_url = get_login_url()
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
if message is not None:
messages.info(request, message, fail_silently=True)
response = HttpResponseRedirect(login_url)
if request.method != 'GET':
from .helpers import save_next_action
data = {
'action': request.META.get('PATH_INFO'),
'args': args,
'kwargs': kwargs,
'method': request.method,
'parameters': {
'POST': request.POST.urlencode() if request.POST else None,
}
}
save_next_action(request, response, data)
return response
return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
return decorator
0
Example 135
Project: hellolily Source File: views.py
def draft_message(self, email_outbox_message):
"""
Creates a task for async creating a draft and sets messages for feedback.
Args:
email_outbox_message (instance): EmailOutboxMessage instance
Returns:
Task instance
"""
current_draft_pk = self.kwargs.get('pk', None)
if current_draft_pk:
task = update_draft_email_message.apply_async(
args=(email_outbox_message.id, current_draft_pk,),
max_retries=1,
default_retry_delay=100,
)
else:
task = create_draft_email_message.apply_async(
args=(email_outbox_message.id,),
max_retries=1,
default_retry_delay=100,
)
if task:
messages.info(
self.request,
_('Creating a draft as fast as I can.')
)
self.request.session['tasks'].update({'create_draft_email_message': task.id})
self.request.session.modified = True
else:
messages.error(
self.request,
_('Sorry, I couldn\'t save you email as a draft.')
)
logging.error(
_('Failed to create create_draft_email_message task for email account %d. '
'Outbox message id was %d.') % (
email_outbox_message.send_from, email_outbox_message.id
)
)
return task
0
Example 136
Project: teerace Source File: views.py
@render_to('home.html')
def homepage(request):
try:
latest_entries = Entry.objects.filter(status=Entry.PUBLISHED_STATUS) \
.order_by('-created_at').select_related()[:2]
if latest_entries.count() > 1:
if not latest_entries[0].is_micro and not latest_entries[1].is_micro:
latest_entries = latest_entries[:1]
except Entry.DoesNotExist:
latest_entries = None
user_base = User.objects.exclude(is_active=False)
try:
latest_user = user_base.latest('id')
except User.DoesNotExist:
latest_user = None
user_count = user_base.count()
try:
latest_map = Map.objects.latest('id')
except Map.DoesNotExist:
latest_map = None
map_count = Map.objects.count()
user_actions = Action.objects.order_by('-timestamp')[:10]
today = date.today()
runs_today = Run.objects.filter(created_at__range=
(datetime.combine(today, time.min),
datetime.combine(today, time.max)))
runs_yesterday = cache.get('runs_yesterday')
if runs_yesterday is None:
tasks.update_yesterday_runs.apply()
runs_yesterday = cache.get('runs_yesterday')
total_runs = cache.get('total_runs')
if total_runs is None:
tasks.update_totals.apply()
total_runs = cache.get('total_runs')
total_runtime = cache.get('total_runtime')
if total_runtime is None:
tasks.update_totals.apply()
total_runtime = cache.get('total_runtime')
total_playtime = cache.get('total_playtime')
if total_playtime is None:
tasks.update_totals.apply()
total_playtime = cache.get('total_playtime')
total_downloads = Map.objects.aggregate(
Sum('download_count')
)['download_count__sum']
messages.info(request, "Please enable Javascript.", extra_tags="javascript")
return {
'latest_entries': latest_entries,
'latest_user': latest_user,
'user_count': user_count,
'latest_map': latest_map,
'map_count': map_count,
'user_actions': user_actions,
'run_count': total_runs,
'runs_today': runs_today,
'runs_yesterday': runs_yesterday,
'total_runtime': total_runtime,
'total_playtime': total_playtime,
'total_downloads': total_downloads,
}
0
Example 137
def save_file(request):
"""
The POST endpoint to save a file in the file editor.
Does the save and then redirects back to the edit page.
"""
form = EditorForm(request.POST)
is_valid = form.is_valid()
path = form.cleaned_data.get('path')
if request.POST.get('save') == "Save As":
if not is_valid:
return edit(request, path, form=form)
else:
data = dict(form=form)
return render("saveas.mako", request, data)
if not path:
raise PopupException("No path specified")
if not is_valid:
return edit(request, path, form=form)
if request.fs.exists(path):
_do_overwrite_save(request.fs, path,
form.cleaned_data['contents'],
form.cleaned_data['encoding'])
else:
_do_newfile_save(request.fs, path,
form.cleaned_data['contents'],
form.cleaned_data['encoding'])
messages.info(request, _('Saved %(path)s.') % {'path': os.path.basename(path)})
""" Changing path to reflect the request path of the JFrame that will actually be returned."""
request.path = urlresolvers.reverse("filebrowser.views.edit", kwargs=dict(path=path))
return edit(request, path, form)
0
Example 138
Project: Django-facebook Source File: views.py
def _connect(request, graph):
'''
Handles the view logic around connect user
- (if authenticated) connect the user
- login
- register
We are already covered by the facebook_required_lazy decorator
So we know we either have a graph and permissions, or the user denied
the oAuth dialog
'''
backend = get_registration_backend()
connect_facebook = to_bool(
request.POST.get(
'connect_facebook',
request.GET.get('connect_facebook'))
)
logger.info('trying to connect using Facebook')
if graph:
logger.info('found a graph object')
converter = get_instance_for('user_conversion', graph)
authenticated = converter.is_authenticated()
# Defensive programming :)
if not authenticated:
raise ValueError('didnt expect this flow')
logger.info('Facebook is authenticated')
facebook_data = converter.facebook_profile_data()
# either, login register or connect the user
try:
action, user = connect_user(
request, connect_facebook=connect_facebook)
logger.info('Django facebook performed action: %s', action)
except facebook_exceptions.IncompleteProfileError as e:
# show them a registration form to add additional data
warning_format = u'Incomplete profile data encountered with error %s'
warn_message = warning_format % unicode(e)
send_warning(warn_message, e=e,
facebook_data=facebook_data)
context = {'facebook_mode': True, 'form': e.form}
return render(request, backend.get_registration_template(), context)
except facebook_exceptions.AlreadyConnectedError as e:
user_ids = [u.get_user_id() for u in e.users]
ids_string = ','.join(map(str, user_ids))
additional_params = dict(already_connected=ids_string)
return backend.post_error(request, additional_params)
response = backend.post_connect(request, user, action)
if action is CONNECT_ACTIONS.LOGIN:
pass
elif action is CONNECT_ACTIONS.CONNECT:
# connect means an existing account was attached to facebook
messages.info(request, _("You have connected your account "
"to %s's facebook profile") % facebook_data['name'])
elif action is CONNECT_ACTIONS.REGISTER:
# hook for tying in specific post registration functionality
response.set_cookie('fresh_registration', user.id)
else:
# the user denied the request
additional_params = dict(fb_error_or_cancel='1')
response = backend.post_error(request, additional_params)
return response
0
Example 139
Project: Mturk-Tracker Source File: views.py
@never_cache
def hit_group_details(request, hit_group_id):
try:
hit_group = HitGroupContent.objects.get(group_id=hit_group_id)
if RequesterProfile.objects.filter(requester_id=hit_group.requester_id,
is_public=False):
raise HitGroupContent.DoesNotExist()
except HitGroupContent.DoesNotExist:
messages.info(request, 'Hitgroup with id "{0}" was not found!'.format(
hit_group_id))
return redirect('haystack_search')
try:
hit_group_class = HitGroupClass.objects.get(group_id=hit_group_id)
except ObjectDoesNotExist:
# TODO classification should be done on all models.
hit_group_class = None
try:
with open(settings.CLASSIFIER_PATH, "r") as file:
classifier = NaiveBayesClassifier(
probabilities=json.load(file)
)
classified = classifier.classify(hit_group)
most_likely = classifier.most_likely(classified)
docuement = classified["docuement"]
hit_group_class = HitGroupClass(
group_id=docuement.group_id,
classes=most_likely,
probabilities=classified["probabilities"])
hit_group_class.save()
except IOError:
# We do not want make hit group details page unavailable when
# classifier file does not exist.
pass
if hit_group_class is not None:
hit_group_class_label = NaiveBayesClassifier.label(
hit_group_class.classes
)
else:
hit_group_class_label = NaiveBayesClassifier.label()
params = {
'multichart': False,
'columns': HIT_DETAILS_COLUMNS,
'title': '#Hits',
'class': hit_group_class_label,
}
def hit_group_details_data_formater(input):
for cc in input:
yield {
'date': cc['start_time'],
'row': (str(cc['hits_available']),),
}
dicts = query_to_dicts(
""" select start_time, hits_available from hits_mv
where group_id = '{}' order by start_time asc """
.format(hit_group_id))
data = hit_group_details_data_formater(dicts)
params['date_from'] = hit_group.occurrence_date
params['date_to'] = datetime.datetime.utcnow()
params['data'] = data
params['hit_group'] = hit_group
return direct_to_template(request, 'main/hit_group_details.html', params)
0
Example 140
Project: 1flow Source File: google_reader.py
def google_reader_import(request, user_id=None):
if user_id is None:
user_id = request.user.id
fallback_url = reverse('profile')
else:
if request.user.is_superuser or request.user.is_staff:
fallback_url = reverse('admin:index')
else:
return HttpResponseForbidden("Access Denied")
redirect_url = request.META.get('HTTP_REFERER', fallback_url)
def info(text):
messages.info(request, text)
gri = GoogleReaderImport(user_id)
if gri.running():
info(_(u'An import is already running for your Google Reader data.'))
return HttpResponseRedirect(redirect_url)
if not gri.is_active:
info(_(u'Google Reader import deactivated.'))
return HttpResponseRedirect(redirect_url)
if not gri.can_import:
info(_(u'Your beta invite has not yet been accepted, sorry.'))
return HttpResponseRedirect(redirect_url)
try:
import_google_reader_trigger(user_id)
except ObjectDoesNotExist:
info(_(u'You are not logged into Google Oauth or you have no token.'))
return HttpResponseRedirect(redirect_url)
except:
info(_(u'Error parsing Google Oauth tokens. '
u'Please try signout and re-signin.'))
return HttpResponseRedirect(redirect_url)
else:
if request.user.is_staff or request.user.is_superuser:
info(_(u'Google Reader import started for user ID %s.') % user_id)
else:
info(_(u'Google Reader import started.'))
return HttpResponseRedirect(redirect_url)
0
Example 141
def form_valid(self, form):
messages.info(self.request, "Project added")
return super(ProjectCreateView, self).form_valid(form)
0
Example 142
def info(request, msg):
logger.info(msg)
messages.info(request, msg)
0
Example 143
Project: comics Source File: views.py
def feedback(request):
"""Mail feedback to ADMINS"""
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
subject = 'Feedback from %s' % settings.COMICS_SITE_TITLE
metadata = 'Client IP address: %s\n' % request.META['REMOTE_ADDR']
metadata += 'User agent: %s\n' % request.META['HTTP_USER_AGENT']
if request.user.is_authenticated():
metadata += 'User: %s <%s>\n' % (
request.user.username, request.user.email)
else:
metadata += 'User: anonymous\n'
message = '%s\n\n-- \n%s' % (
form.cleaned_data['message'], metadata)
headers = {}
if request.user.is_authenticated():
headers['Reply-To'] = request.user.email
mail = EmailMessage(
subject=subject, body=message,
to=[email for name, email in settings.ADMINS],
headers=headers)
mail.send()
messages.info(
request,
'Thank you for taking the time to help improve the site! :-)')
return HttpResponseRedirect(reverse('help_feedback'))
else:
form = FeedbackForm()
return render(request, 'help/feedback.html', {
'active': {
'help': True,
'feedback': True,
},
'feedback_form': form,
})
0
Example 144
Project: 1flow Source File: subscription.py
def add_subscription(request, **kwargs):
""" Subscribe current user to a feed. """
if request.POST:
form = AddSubscriptionForm(request.POST, owner=request.user)
if form.is_valid():
added = form.save()
if added:
messages.info(request,
_(u'Successfully subscribed to {0} '
u'streams. Articles are being added '
u'progressively, thanks for your '
u'patience.').format(len(added)))
else:
messages.warning(request,
_(u'No feed subscribed to.'))
return HttpResponseRedirect(reverse('source_selector')
+ u'#' + __(u'unclassified-streams'))
else:
form = AddSubscriptionForm(owner=request.user)
context = {'form': form}
#
# HEADS UP: the non `in_modal` form is used during the first-connection
# wizard. It will help the user add feeds / subscriptions, while
# his/her selector is empty.
#
if request.is_ajax():
context['in_modal'] = True
template = 'snippets/selector/add-subscription.html'
else:
template = 'add-subscription.html'
return render(request, template, context)
0
Example 145
Project: explorer Source File: views.py
@assert_valid_coin_symbol
@render_to('subscribe_address.html')
def subscribe_address(request, coin_symbol):
already_authenticated = request.user.is_authenticated()
# kind of tricky because we have to deal with both logged in and new users
initial = {'coin_symbol': coin_symbol}
if already_authenticated:
form = KnownUserAddressSubscriptionForm(initial=initial)
else:
form = NewUserAddressSubscriptionForm(initial=initial)
if request.method == 'POST':
if already_authenticated:
form = KnownUserAddressSubscriptionForm(data=request.POST)
else:
form = NewUserAddressSubscriptionForm(data=request.POST)
if form.is_valid():
coin_symbol = form.cleaned_data['coin_symbol']
coin_address = form.cleaned_data['coin_address']
if already_authenticated:
auth_user = request.user
else:
user_email = form.cleaned_data['email']
# Check for existing user with that email
existing_user = get_object_or_None(AuthUser, email=user_email)
if existing_user:
msg = _('Please first login to this account to create a notification')
messages.info(request, msg)
return HttpResponseRedirect(existing_user.get_login_uri())
else:
# Create user with unknown (random) password
auth_user = AuthUser.objects.create_user(
email=user_email,
password=None, # it will create a random pw
creation_ip=get_client_ip(request),
creation_user_agent=get_user_agent(request),
)
# Login the user
# http://stackoverflow.com/a/3807891/1754586
auth_user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, auth_user)
# Log the login
LoggedLogin.record_login(request)
existing_subscription_cnt = AddressSubscription.objects.filter(
auth_user=auth_user,
b58_address=coin_address,
unsubscribed_at=None,
disabled_at=None,
).count()
if existing_subscription_cnt:
msg = _("You're already subscribed to that address. Please choose another address.")
messages.warning(request, msg)
else:
# TODO: this is inefficiently happening before email verification
# Hit blockcypher and return subscription id
callback_uri = reverse('address_webhook', kwargs={
'secret_key': WEBHOOK_SECRET_KEY,
# hack for rare case of two webhooks requested on same address:
'ignored_key': simple_pw_generator(num_chars=10),
})
callback_url = uri_to_url(callback_uri)
bcy_id = subscribe_to_address_webhook(
subscription_address=coin_address,
callback_url=callback_url,
coin_symbol=coin_symbol,
api_key=BLOCKCYPHER_API_KEY,
)
address_subscription = AddressSubscription.objects.create(
coin_symbol=coin_symbol,
b58_address=coin_address,
auth_user=auth_user,
blockcypher_id=bcy_id,
)
address_uri = reverse('address_overview', kwargs={
'coin_symbol': coin_symbol,
'address': coin_address,
})
if already_authenticated and auth_user.email_verified:
msg = _('You will now be emailed notifications for <a href="%(address_uri)s">%(coin_address)s</a>' % {
'coin_address': coin_address,
'address_uri': address_uri,
})
messages.success(request, msg, extra_tags='safe')
return HttpResponseRedirect(reverse('dashboard'))
else:
address_subscription.send_notifications_welcome_email()
return HttpResponseRedirect(reverse('unconfirmed_email'))
elif request.method == 'GET':
coin_address = request.GET.get('a')
subscriber_email = request.GET.get('e')
if coin_address:
initial['coin_address'] = coin_address
if subscriber_email and not already_authenticated:
initial['email'] = subscriber_email
if coin_address or subscriber_email:
if already_authenticated:
form = KnownUserAddressSubscriptionForm(initial=initial)
else:
form = NewUserAddressSubscriptionForm(initial=initial)
return {
'form': form,
'coin_symbol': coin_symbol,
'is_input_page': True,
}
0
Example 146
def entries_view(self, request, form_id):
"""
Displays the form entries in a HTML table with option to
export as CSV file.
"""
if request.POST.get("back"):
change_url = admin_url(Form, "change", form_id)
return HttpResponseRedirect(change_url)
form = get_object_or_404(Form, id=form_id)
entries_form = EntriesForm(form, request, request.POST or None)
delete_entries_perm = "%s.delete_formentry" % FormEntry._meta.app_label
can_delete_entries = request.user.has_perm(delete_entries_perm)
submitted = entries_form.is_valid()
if submitted:
if request.POST.get("export"):
response = HttpResponse(content_type="text/csv")
timestamp = slugify(datetime.now().ctime())
fname = "%s-%s.csv" % (form.slug, timestamp)
header = "attachment; filename=%s" % fname
response["Content-Disposition"] = header
queue = StringIO()
delimiter = settings.FORMS_CSV_DELIMITER
try:
csv = writer(queue, delimiter=delimiter)
writerow = csv.writerow
except TypeError:
queue = BytesIO()
delimiter = bytes(delimiter, encoding="utf-8")
csv = writer(queue, delimiter=delimiter)
writerow = lambda row: csv.writerow([c.encode("utf-8")
if hasattr(c, "encode") else c for c in row])
writerow(entries_form.columns())
for row in entries_form.rows(csv=True):
writerow(row)
data = queue.getvalue()
response.write(data)
return response
elif request.POST.get("delete") and can_delete_entries:
selected = request.POST.getlist("selected")
if selected:
entries = FormEntry.objects.filter(id__in=selected)
count = entries.count()
if count > 0:
entries.delete()
message = ungettext("1 entry deleted",
"%(count)s entries deleted", count)
info(request, message % {"count": count})
template = "admin/forms/entries.html"
context = {"title": _("View Entries"), "entries_form": entries_form,
"opts": self.model._meta, "original": form,
"can_delete_entries": can_delete_entries,
"submitted": submitted}
return render(request, template, context)
0
Example 147
Project: volontulo Source File: offers.py
@staticmethod
@correct_slug(Offer, 'offers_join', 'title')
def post(request, slug, id_): # pylint: disable=unused-argument
"""View responsible for saving join for particular offer."""
form = OfferApplyForm(request.POST)
offer = Offer.objects.get(id=id_)
if form.is_valid():
if request.user.is_authenticated():
user = request.user
else:
user = User.objects.filter(
email=request.POST.get('email')
).exists()
if user:
messages.info(
request,
'Zaloguj się, aby zapisać się do oferty.'
)
return redirect(
reverse('login') + '?next={}'.format(request.path)
)
else:
messages.info(
request,
'Zarejestruj się, aby zapisać się do oferty.'
)
return redirect('register')
has_applied = Offer.objects.filter(
volunteers=user,
volunteers__offer=id_,
).count()
if has_applied:
messages.error(
request,
u'Już wyraziłeś chęć uczestnictwa w tej ofercie.'
)
return redirect('offers_list')
offer.volunteers.add(user)
offer.save()
send_mail(
request,
'offer_application',
[
user.email,
request.POST.get('email'),
],
dict(
email=request.POST.get('email'),
phone_no=request.POST.get('phone_no'),
fullname=request.POST.get('fullname'),
comments=request.POST.get('comments'),
offer=offer,
)
)
messages.success(
request,
u'Zgłoszenie chęci uczestnictwa zostało wysłane.'
)
return redirect(
'offers_view',
slug=slugify(offer.title),
id_=offer.id,
)
else:
errors = '<br />'.join(form.errors)
messages.error(
request,
u'Formularz zawiera nieprawidłowe dane' + errors
)
volunteer_user = UserProfile()
if request.user.is_authenticated():
volunteer_user = request.user.userprofile
return render(
request,
'offers/offer_apply.html',
{
'offer': offer,
'form': form,
'volunteer_user': volunteer_user,
}
)
0
Example 148
Project: transifex Source File: views.py
@login_required
def translate(request, project_slug, lang_code, resource_slug=None,
*args, **kwargs):
"""
Main lotte view.
"""
# Permissions handling
# Project should always be available
project = get_object_or_404(Project, slug=project_slug)
team = Team.objects.get_or_none(project, lang_code)
check = ProjectPermission(request.user)
if not check.submit_translations(team or project) and not\
check.maintain(project):
return permission_denied(request)
resources = []
if resource_slug:
resource_list = [get_object_or_404(Resource, slug=resource_slug,
project=project)]
else:
resource_list = Resource.objects.filter(project=project)
# Return a page explaining that the project has multiple source langs and
# cannot be translated as a whole.
if resource_list.values('source_language').distinct().count() > 1:
messages.info(request,_(
"There are multiple source languages for this project. "
"You will only be able to translate resources for one "
"source language at a time."))
return HttpResponseRedirect(reverse('project_detail',
args=[project_slug]),)
# Filter resources that are not accepting translations
for resource in resource_list:
if resource.accept_translations:
resources.append(resource)
# If no resource accepting translations, raise a 403
if not resources:
return permission_denied(request)
target_language = Language.objects.by_code_or_alias_or_404(lang_code)
# If it is an attempt to edit the source language, redirect the user to
# resource_detail and show him a message explaining the reason.
if target_language == get_source_language(resources):
messages.error(request,_(
"Cannot edit the source language because this would "
"result in translation mismatches! If you want to "
"update the source strings consider using the transifex "
"command-line client."))
if resource_slug:
return HttpResponseRedirect(reverse('resource_detail',
args=[project_slug,
resource_slug]),)
else:
return HttpResponseRedirect(reverse('project_detail',
args=[project_slug]),)
total_strings = SourceEntity.objects.filter(
resource__in = resources).count()
translated_strings = Translation.objects.filter(
resource__in=resources,
language=target_language,
source_entity__pluralized=False,
rule=5).count()
reviewed_strings = Translation.objects.filter(
resource__in=resources,
language=target_language,
source_entity__pluralized=False,
rule=5,
reviewed=True).count()
# Include counting of pluralized entities
for pluralized_entity in SourceEntity.objects.filter(resource__in = resources,
pluralized=True):
plurals_translated = Translation.objects.filter(
language=target_language,
source_entity=pluralized_entity).count()
if plurals_translated == len(target_language.get_pluralrules()):
translated_strings += 1
if len(resources) > 1:
translation_resource = None
else:
translation_resource = resources[0]
contributors = User.objects.filter(pk__in=Translation.objects.filter(
resource__in = resources,
language = target_language,
rule = 5).values_list("user", flat=True))
lotte_init.send(None, request=request, resources=resources,
language=target_language)
if target_language in [team.language for team in project.available_teams]:
team_language = True
else:
team_language = False
GtModel = get_model('gtranslate', 'Gtranslate')
try:
auto_translate = GtModel.objects.get(project=project)
except GtModel.DoesNotExist:
auto_translate = None
"""
if cache.get('lotte_%s' % request.session.session_key, None):
cache.delete('lotte_%s' % request.session.session_key)
"""
#Set rtl to True if target_language is an RTL language
rtl = False
if target_language.code in settings.RTL_LANGUAGE_CODES:
rtl = True
return render_to_response("translate.html", {
'project': project,
'resource': translation_resource,
'target_language': target_language,
'translated_strings': translated_strings,
'reviewed_strings': reviewed_strings,
'untranslated_strings': total_strings - translated_strings,
'contributors': contributors,
'resources': resources,
'resource_slug': resource_slug,
'languages': Language.objects.all(),
'auto_translate': auto_translate,
'spellcheck_supported_langs': SPELLCHECK_SUPPORTED_LANGS,
'team_language': team_language,
'RTL': rtl,
}, context_instance = RequestContext(request))
0
Example 149
Project: django-timepiece Source File: views.py
@permission_required('entries.change_entry')
def create_edit_entry(request, entry_id=None):
if entry_id:
try:
entry = Entry.no_join.get(pk=entry_id)
except Entry.DoesNotExist:
entry = None
else:
if not (entry.is_editable or request.user.has_perm('entries.view_payroll_summary')):
raise Http404
else:
entry = None
entry_user = entry.user if entry else request.user
if request.method == 'POST':
form = AddUpdateEntryForm(data=request.POST,
instance=entry,
user=entry_user,
acting_user=request.user)
if form.is_valid():
entry = form.save()
if entry_id:
message = 'The entry has been updated successfully.'
else:
message = 'The entry has been created successfully.'
messages.info(request, message)
url = request.GET.get('next', reverse('dashboard'))
return HttpResponseRedirect(url)
else:
message = 'Please fix the errors below.'
messages.error(request, message)
else:
initial = dict([(k, request.GET[k]) for k in request.GET.keys()])
form = AddUpdateEntryForm(instance=entry,
user=entry_user,
initial=initial,
acting_user=request.user)
return render(request, 'timepiece/entry/create_edit.html', {
'form': form,
'entry': entry,
})
0
Example 150
Project: django-newsletter Source File: views.py
def get_formset(self):
"""
Return a formset with newsletters for logged in users, or None.
"""
# Short-hand variable names
newsletters = self.get_queryset()
request = self.request
user = request.user
SubscriptionFormSet = modelformset_factory(
Subscription, form=UserUpdateForm, extra=0
)
# Before rendering the formset, subscription objects should
# already exist.
for n in newsletters:
Subscription.objects.get_or_create(
newsletter=n, user=user
)
# Get all subscriptions for use in the formset
qs = Subscription.objects.filter(
newsletter__in=newsletters, user=user
)
if request.method == 'POST':
try:
formset = SubscriptionFormSet(request.POST, queryset=qs)
if not formset.is_valid():
raise ValidationError('Update form invalid.')
# Everything's allright, let's save
formset.save()
messages.info(
request,
ugettext("Your changes have been saved.")
)
except ValidationError:
# Invalid form posted. As there is no way for a user to
# enter data - invalid forms should be ignored from the UI.
# However, we log them for debugging purposes.
logger.warning(
'Invalid form post received',
exc_info=True, extra={'request': request}
)
# Present a pristine form
formset = SubscriptionFormSet(queryset=qs)
else:
formset = SubscriptionFormSet(queryset=qs)
return formset