Here are the examples of the python api django.http.Http404 taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
156 Examples
2
Example 1
Project: autotest Source File: feed.py
def feed_view(request, url, feed_dict=None):
"""
View a feed.
Copied from django/contrib/syndication/views.py. The default view doesn't
give the feed any way to access the request object, and we need to access it
to get the server hostname. So we're forced to copy the code here and
modify it to pass in the request.
"""
if not feed_dict:
raise django.http.Http404("No feeds are registered.")
try:
slug, param = url.split('/', 1)
except ValueError:
slug, param = url, ''
try:
f = feed_dict[slug]
except KeyError:
raise django.http.Http404("Slug %r isn't registered." % slug)
try:
# this line is changed from the Django library version to pass
# in request instead of request.path
feedgen = f(slug, request).get_feed(param)
except views.FeedDoesNotExist:
raise django.http.Http404("Invalid feed parameters. Slug %r is valid, "
"but other parameters, or lack thereof, "
"are not." % slug)
response = django.http.HttpResponse(mimetype=feedgen.mime_type)
feedgen.write(response, 'utf-8')
return response
1
Example 2
Project: talk.org Source File: main.py
def add_stage(request, app_label, model_name, show_delete=False, form_url='', post_url=None, post_url_continue='../%s/', object_id_override=None):
model = models.get_model(app_label, model_name)
if model is None:
raise Http404("App %r, model %r, not found" % (app_label, model_name))
opts = model._meta
if not request.user.has_perm(app_label + '.' + opts.get_add_permission()):
raise PermissionDenied
if post_url is None:
if request.user.has_perm(app_label + '.' + opts.get_change_permission()):
# redirect to list view
post_url = '../'
else:
# Object list will give 'Permission Denied', so go back to admin home
post_url = '../../../'
manipulator = model.AddManipulator()
if request.POST:
new_data = request.POST.copy()
if opts.has_field_type(models.FileField):
new_data.update(request.FILES)
errors = manipulator.get_validation_errors(new_data)
manipulator.do_html2python(new_data)
if not errors:
new_object = manipulator.save(new_data)
pk_value = new_object._get_pk_val()
LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, force_unicode(new_object), ADDITION)
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(new_object)}
# Here, we distinguish between different save types by checking for
# the presence of keys in request.POST.
if "_continue" in request.POST:
request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
if "_popup" in request.POST:
post_url_continue += "?_popup=1"
return HttpResponseRedirect(post_url_continue % pk_value)
if "_popup" in request.POST:
return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
# escape() calls force_unicode.
(escape(pk_value), escape(new_object)))
elif "_addanother" in request.POST:
request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
return HttpResponseRedirect(request.path)
else:
request.user.message_set.create(message=msg)
return HttpResponseRedirect(post_url)
else:
# Add default data.
new_data = manipulator.flatten_data()
# Override the defaults with GET params, if they exist.
new_data.update(dict(request.GET.items()))
errors = {}
# Populate the FormWrapper.
form = oldforms.FormWrapper(manipulator, new_data, errors)
c = template.RequestContext(request, {
'title': _('Add %s') % force_unicode(opts.verbose_name),
'form': form,
'is_popup': '_popup' in request.REQUEST,
'show_delete': show_delete,
})
if object_id_override is not None:
c['object_id'] = object_id_override
return render_change_form(model, manipulator, c, add=True)
0
Example 3
Project: ion Source File: attendance.py
@attendance_taker_required
def take_attendance_view(request, scheduled_activity_id):
try:
scheduled_activity = (EighthScheduledActivity.objects.select_related("activity", "block").get(activity__deleted=False,
id=scheduled_activity_id))
except EighthScheduledActivity.DoesNotExist:
raise http.Http404
if request.user.is_eighth_admin or scheduled_activity.user_is_sponsor(request.user):
logger.debug("User has permission to edit")
edit_perm = True
else:
logger.debug("User does not have permission to edit")
edit_perm = False
edit_perm_cancelled = False
if scheduled_activity.cancelled and not request.user.is_eighth_admin:
logger.debug("Non-admin user does not have permission to edit cancelled activity")
edit_perm = False
edit_perm_cancelled = True
if request.method == "POST":
if not edit_perm:
if edit_perm_cancelled:
return render(request, "error/403.html",
{"reason": "You do not have permission to take attendance for this activity. The activity was cancelled."}, status=403)
else:
return render(request, "error/403.html",
{"reason": "You do not have permission to take attendance for this activity. You are not a sponsor."}, status=403)
if "admin" in request.path:
url_name = "eighth_admin_take_attendance"
else:
url_name = "eighth_take_attendance"
if "clear_attendance_bit" in request.POST:
scheduled_activity.attendance_taken = False
scheduled_activity.save()
invalidate_obj(scheduled_activity)
messages.success(request, "Attendance bit cleared for {}".format(scheduled_activity))
redirect_url = reverse(url_name, args=[scheduled_activity.id])
if "no_attendance" in request.GET:
redirect_url += "?no_attendance={}".format(request.GET["no_attendance"])
return redirect(redirect_url)
if not scheduled_activity.block.locked and not request.user.is_eighth_admin:
return render(request, "error/403.html",
{"reason":
"You do not have permission to take attendance for this activity. The block has not been locked yet."}, status=403)
if not scheduled_activity.block.locked and request.user.is_eighth_admin:
messages.success(request, "Note: Taking attendance on an unlocked block.")
present_user_ids = list(request.POST.keys())
csrf = "csrfmiddlewaretoken"
if csrf in present_user_ids:
present_user_ids.remove(csrf)
absent_signups = (EighthSignup.objects.filter(scheduled_activity=scheduled_activity).exclude(user__in=present_user_ids))
absent_signups.update(was_absent=True)
for s in absent_signups:
invalidate_obj(s)
present_signups = (EighthSignup.objects.filter(scheduled_activity=scheduled_activity, user__in=present_user_ids))
present_signups.update(was_absent=False)
for s in present_signups:
invalidate_obj(s)
passes = (EighthSignup.objects.filter(scheduled_activity=scheduled_activity, after_deadline=True, pass_accepted=False))
passes.update(was_absent=True)
for s in passes:
invalidate_obj(s)
scheduled_activity.attendance_taken = True
scheduled_activity.save()
invalidate_obj(scheduled_activity)
messages.success(request, "Attendance updated.")
redirect_url = reverse(url_name, args=[scheduled_activity.id])
if "no_attendance" in request.GET:
redirect_url += "?no_attendance={}".format(request.GET["no_attendance"])
return redirect(redirect_url)
else:
passes = (EighthSignup.objects.select_related("user").filter(scheduled_activity=scheduled_activity, after_deadline=True,
pass_accepted=False))
users = scheduled_activity.members.exclude(eighthsignup__in=passes)
members = []
absent_user_ids = (EighthSignup.objects.select_related("user").filter(scheduled_activity=scheduled_activity, was_absent=True).values_list(
"user__id", flat=True))
pass_users = (EighthSignup.objects.select_related("user").filter(scheduled_activity=scheduled_activity, after_deadline=True,
pass_accepted=True).values_list("user__id", flat=True))
for user in users:
members.append({
"id": user.id,
"name": user.last_first, # includes nickname
"grade": user.grade.number if user.grade else None,
"present": (scheduled_activity.attendance_taken and (user.id not in absent_user_ids)),
"had_pass": user.id in pass_users,
"pass_present": (not scheduled_activity.attendance_taken and user.id in pass_users and user.id not in absent_user_ids),
"email": user.tj_email
})
invalidate_obj(user)
members.sort(key=lambda m: m["name"])
context = {
"scheduled_activity": scheduled_activity,
"passes": passes,
"members": members,
"p": pass_users,
"no_edit_perm": not edit_perm,
"edit_perm_cancelled": edit_perm_cancelled,
"show_checkboxes": (scheduled_activity.block.locked or request.user.is_eighth_admin),
"show_icons": (scheduled_activity.block.locked and scheduled_activity.block.attendance_locked() and not request.user.is_eighth_admin)
}
if request.user.is_eighth_admin:
context["scheduled_activities"] = (EighthScheduledActivity.objects.filter(block__id=scheduled_activity.block.id))
logger.debug(context["scheduled_activities"])
context["blocks"] = (EighthBlock.objects
# .filter(date__gte=get_start_date(request))
.order_by("date"))
if request.resolver_match.url_name == "eighth_admin_export_attendance_csv":
response = http.HttpResponse(content_type="text/csv")
response["Content-Disposition"] = "attachment; filename=\"attendance.csv\""
writer = csv.writer(response)
writer.writerow(["Block", "Activity", "Name", "Student ID", "Grade", "Email", "Locked", "Rooms", "Sponsors", "Attendance Taken",
"Present", "Had Pass"])
for member in members:
row = []
logger.debug(member)
row.append(str(scheduled_activity.block))
row.append(str(scheduled_activity.activity))
row.append(member["name"])
row.append(member["id"])
row.append(member["grade"])
row.append(member["email"])
row.append(scheduled_activity.block.locked)
rooms = scheduled_activity.get_true_rooms()
row.append(", ".join(["{} ({})".format(room.name, room.capacity) for room in rooms]))
sponsors = scheduled_activity.get_true_sponsors()
row.append(" ,".join([sponsor.name for sponsor in sponsors]))
row.append(scheduled_activity.attendance_taken)
row.append(member["present"] if scheduled_activity.block.locked else "N/A")
row.append(member["had_pass"] if scheduled_activity.block.locked else "N/A")
writer.writerow(row)
return response
else:
return render(request, "eighth/take_attendance.html", context)
0
Example 4
Project: django-hashtags Source File: views.py
def hashtagged_item_list(request, hashtag, paginate_by=None, page=None,
allow_empty=True, template_loader=loader,
template_name="hashtags/hashtagged_item_list.html",
extra_context={}, context_processors=None,
template_object_name='hashtagged_item_list',
mimetype=None):
"""
A page representing a list of objects hastagged with ``hashtag``.
Works like ``django.views.generic.list_detail.object_list`.
Templates: ``hashtags/hashtagged_item_list.html``
Context:
hashtag
The hashtag object in question
hashtagged_item_list
The list of objects hashtagged with ``hastag``
paginator
An instance of ``django.core.paginator.Paginator``
page_obj
An instance of ``django.core.paginator.Page``
"""
try:
hashtag = Hashtag.objects.get(name=hashtag)
except ObjectDoesNotExist:
raise Http404("Hashtag %s doesn't exist." % hashtag)
queryset = HashtaggedItem.objects.filter(hashtag=hashtag)
if paginate_by:
paginator = Paginator(queryset, paginate_by,
allow_empty_first_page=allow_empty)
if not page:
page = request.GET.get('page', 1)
try:
page_number = int(page)
except ValueError:
if page == 'last':
page_number = paginator.num_pages
else:
# Page is not 'last', nor can it be converted to an int.
raise Http404
try:
page_obj = paginator.page(page_number)
except InvalidPage:
raise Http404
c = RequestContext(request, {
'hashtag': hashtag,
template_object_name: queryset,
'paginator': paginator,
'page_obj': page_obj,
}, context_processors)
else:
c = RequestContext(request, {
'hashtag': hashtag,
template_object_name: queryset,
'paginator': None,
'page_obj': None,
}, context_processors)
if not allow_empty and len(queryset) == 0:
raise Http404
for key, value in extra_context.items():
if callable(value):
c[key] = value()
else:
c[key] = value
t = template_loader.get_template(template_name)
return HttpResponse(t.render(c), mimetype=mimetype)
0
Example 5
Project: zorna Source File: views.py
def search(request):
results_articles = None
results_faqs = None
results = {}
query = ''
if request.GET.get('q'):
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['q']
query = "*"+query+"*" if query else query
what = request.GET.get('what', None)
if what == 'articles' or what is None:
ao = get_allowed_objects(
request.user, ArticleCategory, 'reader')
ao = [str(p) for p in ao]
results_articles = SearchQuerySet().filter(
content=query).filter(categories__in=ao).models(ArticleStory)
if results_articles:
paginator = Paginator(results_articles, RESULTS_PER_PAGE)
try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
raise Http404("No such page of results!")
results['articles'] = {
'results': results_articles, 'page': page, 'paginator': paginator}
if what == 'faqs' or what is None:
ao = get_allowed_objects(request.user, Faq, 'reader')
ao = [str(p) for p in ao]
results_faqs = SearchQuerySet().filter(
content=query).filter(faq__in=ao).models(FaqQuestion)
if results_faqs:
paginator = Paginator(results_faqs, RESULTS_PER_PAGE)
try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
raise Http404("No such page of results!")
results['faqs'] = {
'results': results_faqs, 'page': page, 'paginator': paginator}
if what == 'files' or what is None:
folders = get_allowed_folders(request)
results_files = SearchQuerySet().filter(
content=query).filter(folder__in=folders).models(ZornaFile)
if results_files:
paginator = Paginator(results_files, RESULTS_PER_PAGE)
try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
raise Http404("No such page of results!")
results['files'] = {
'results': results_files, 'page': page, 'paginator': paginator}
if what == 'pages' or what is None:
from whoosh.index import open_dir
from whoosh.qparser import QueryParser
ix = open_dir(settings.HAYSTACK_WHOOSH_PATH, indexname="ZORNA_PAGES")
with ix.searcher() as searcher:
qp = QueryParser("content", schema=ix.schema)
q = qp.parse(query)
pages = searcher.search(q)
if len(pages):
pages_result = []
for p in pages:
doc = os.path.splitext(p['url'])[0]
pages_result.append({'title': p['title'], 'url': '/content/%s/' % doc, 'highlights': p.highlights("content") })
paginator = Paginator(pages_result, RESULTS_PER_PAGE)
try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
raise Http404("No such page of results!")
results['pages'] = {
'results': pages_result, 'page': page, 'paginator': paginator}
else:
form = SearchForm()
context = RequestContext(request)
extra_context = {
'form': form,
'results': results,
'query': query,
}
return render_to_response(['search.html', 'search/search.html'], extra_context, context_instance=context)
0
Example 6
Project: django-bulbs Source File: views.py
def list(self, request):
content_id = get_query_params(self.request).get("content_id")
if content_id:
content = get_object_or_404(Content, pk=content_id)
# Find special coverage via percolator
special_coverage_filter = {
"filter": {
"prefix": {"_id": "specialcoverage"}
}
}
search_objects = type(content).search_objects
results = search_objects.client.percolate(
index=search_objects.mapping.index,
doc_type=search_objects.mapping.doc_type,
id=content.id,
body=special_coverage_filter,
)
# Translate perocolator results into SpecialCoverage objects
if results["total"]:
special_coverage_ids = [int(m["_id"].split(".")[-1]) for m in results["matches"]]
qs = SpecialCoverage.objects.filter(id__in=special_coverage_ids)
# Active Filter
active = get_query_params(self.request).get('active', '').lower()
now = timezone.now()
if active == 'true':
qs = qs.filter(
start_date__lte=now, end_date__gte=now
) | qs.filter(
start_date__lte=now, end_date__isnull=True
)
elif active == 'false':
qs = qs.exclude(
start_date__lte=now, end_date__gte=now
) | qs.exclude(
start_date__lte=now, end_date__isnull=False
)
# Sponsored Filter
sponsored = get_query_params(self.request).get('sponsored', '').lower()
if sponsored == 'true':
qs = qs.filter(tunic_campaign_id__isnull=False)
elif sponsored == 'false':
qs = qs.exclude(tunic_campaign_id__isnull=False)
serializer = SpecialCoverageSerializer(qs, many=True)
return Response(serializer.data)
else:
return Response(status=status.HTTP_204_NO_CONTENT)
else:
raise Http404('Must specify "content_id" param')
0
Example 7
Project: django-cloud-browser Source File: views.py
@settings_view_decorator
def browser(request, path='', template="cloud_browser/browser.html"):
"""View files in a file path.
:param request: The request.
:param path: Path to resource, including container as first part of path.
:param template: Template to render.
"""
from itertools import ifilter, islice
# Inputs.
container_path, object_path = path_parts(path)
incoming = request.POST or request.GET or {}
marker = incoming.get('marker', None)
marker_part = incoming.get('marker_part', None)
if marker_part:
marker = path_join(object_path, marker_part)
# Get and adjust listing limit.
limit_default = settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT
def limit_test(num):
return num > 0 and (MAX_LIMIT is None or num <= MAX_LIMIT - 1)
limit = get_int(incoming.get('limit', limit_default),
limit_default,
limit_test)
# Q1: Get all containers.
# We optimize here by not individually looking up containers later,
# instead going through this in-memory list.
# TODO: Should page listed containers with a ``limit`` and ``marker``.
conn = get_connection()
containers = conn.get_containers()
marker_part = None
container = None
objects = None
if container_path != '':
# Find marked container from list.
def cont_eq(container):
return container.name == container_path
cont_list = list(islice(ifilter(cont_eq, containers), 1))
if not cont_list:
raise Http404("No container at: %s" % container_path)
# Q2: Get objects for instant list, plus one to check "next".
container = cont_list[0]
objects = container.get_objects(object_path, marker, limit + 1)
marker = None
# If over limit, strip last item and set marker.
if len(objects) == limit + 1:
objects = objects[:limit]
marker = objects[-1].name
marker_part = relpath(marker, object_path)
return render_to_response(template,
{'path': path,
'marker': marker,
'marker_part': marker_part,
'limit': limit,
'breadcrumbs': _breadcrumbs(path),
'container_path': container_path,
'containers': containers,
'container': container,
'object_path': object_path,
'objects': objects},
context_instance=RequestContext(request))
0
Example 8
Project: treeio Source File: views.py
def ajax_popup(request, popup_id='', url='/'):
"Handles pop up forms and requests, by extracting only the required content from response content"
view, args, kwargs = resolve(url)
if not request.user.username:
return HttpResponseRedirect('/accounts/login')
modules = Module.objects.all()
active = None
for module in modules:
try:
import_name = module.name + "." + \
settings.HARDTREE_MODULE_IDENTIFIER
hmodule = __import__(import_name, fromlist=[str(module.name)])
urls = hmodule.URL_PATTERNS
for regexp in urls:
if re.match(regexp, url):
active = module
except ImportError:
pass
except AttributeError:
pass
response = None
if active:
if not request.user.profile.has_permission(active):
response = user_denied(request, "You do not have access to the %s module" % unicode(active),
response_format='ajax')
if not response:
if view == ajax_popup:
raise Http404("OMG, I see myself!")
kwargs['request'] = request
kwargs['response_format'] = 'ajax'
response = view(*args, **kwargs)
# response = csrf().process_response(request, response)
module_inner = ""
regexp = r"<!-- module_content_inner -->(?P<module_inner>.*?)<!-- /module_content_inner -->"
blocks = re.finditer(regexp, response.content, re.DOTALL)
for block in blocks:
module_inner += block.group('module_inner').strip()
title = ""
regexp = r"<div class=\\\"title\\\">(?P<title>.*?)</div>"
blocks = re.finditer(regexp, response.content, re.DOTALL)
for block in blocks:
title += block.group('title').replace('\\n', '').strip()
if not title:
blocks = re.finditer(
r"<title>(?P<title>.*?)</title>", response.content, re.DOTALL)
for block in blocks:
title += block.group('title').replace('\\n', '').strip()
subtitle = ""
regexp = r"<div class=\\\"subtitle-block\\\">(?P<subtitle>.*?)</div>"
blocks = re.finditer(regexp, response.content, re.DOTALL)
for block in blocks:
subtitle += block.group('subtitle').replace('\\n', '').strip()
context = {'content': module_inner, 'title': title, 'subtitle': subtitle, 'popup_id': popup_id, 'url': request.path}
if settings.HARDTREE_RESPONSE_FORMATS['json'] in response.get('Content-Type', 'text/html'):
new_response = render_to_response('core/ajax_popup', context,
context_instance=RequestContext(request), response_format='json')
else:
new_response = HttpResponse(json.dumps({'popup': context}))
new_response.mimetype = settings.HARDTREE_RESPONSE_FORMATS['json']
try:
jsonresponse = json.loads(response.content)
if 'redirect' in jsonresponse:
new_response.status_code = 302
except Exception:
new_response.status_code = response.status_code
return new_response
0
Example 9
Project: PyClassLessons Source File: base.py
def get_response(self, request):
"Returns an HttpResponse object for the given HttpRequest"
# Setup default url resolver for this thread, this code is outside
# the try/except so we don't get a spurious "unbound local
# variable" exception in the event an exception is raised before
# resolver is set
urlconf = settings.ROOT_URLCONF
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
try:
response = None
# Apply request middleware
for middleware_method in self._request_middleware:
response = middleware_method(request)
if response:
break
if response is None:
if hasattr(request, 'urlconf'):
# Reset url resolver with a custom urlconf.
urlconf = request.urlconf
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
resolver_match = resolver.resolve(request.path_info)
callback, callback_args, callback_kwargs = resolver_match
request.resolver_match = resolver_match
# Apply view middleware
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
break
if response is None:
wrapped_callback = self.make_view_atomic(callback)
try:
response = wrapped_callback(request, *callback_args, **callback_kwargs)
except Exception as e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
if response:
break
if response is None:
raise
# Complain if the view returned None (a common error).
if response is None:
if isinstance(callback, types.FunctionType): # FBV
view_name = callback.__name__
else: # CBV
view_name = callback.__class__.__name__ + '.__call__'
raise ValueError("The view %s.%s didn't return an HttpResponse object. It returned None instead."
% (callback.__module__, view_name))
# If the response supports deferred rendering, apply template
# response middleware and then render the response
if hasattr(response, 'render') and callable(response.render):
for middleware_method in self._template_response_middleware:
response = middleware_method(request, response)
response = response.render()
except http.Http404 as e:
logger.warning('Not Found: %s', request.path,
extra={
'status_code': 404,
'request': request
})
if settings.DEBUG:
response = debug.technical_404_response(request, e)
else:
try:
callback, param_dict = resolver.resolve404()
response = callback(request, **param_dict)
except:
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
except PermissionDenied:
logger.warning(
'Forbidden (Permission denied): %s', request.path,
extra={
'status_code': 403,
'request': request
})
try:
callback, param_dict = resolver.resolve403()
response = callback(request, **param_dict)
except:
signals.got_request_exception.send(
sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request,
resolver, sys.exc_info())
except SuspiciousOperation as e:
# The request logger receives events for any problematic request
# The security logger receives events for all SuspiciousOperations
security_logger = logging.getLogger('django.security.%s' %
e.__class__.__name__)
security_logger.error(
force_text(e),
extra={
'status_code': 400,
'request': request
})
try:
callback, param_dict = resolver.resolve400()
response = callback(request, **param_dict)
except:
signals.got_request_exception.send(
sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request,
resolver, sys.exc_info())
except SystemExit:
# Allow sys.exit() to actually exit. See tickets #1023 and #4701
raise
except: # Handle everything else.
# Get the exception info now, in case another exception is thrown later.
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
try:
# Apply response middleware, regardless of the response
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
response = self.apply_response_fixes(request, response)
except: # Any exception should be gathered and handled
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
response._closable_objects.append(request)
return response
0
Example 10
Project: plan Source File: views.py
def schedule(request, year, semester_type, slug, advanced=False,
week=None, all=False):
'''Page that handels showing schedules'''
current_week = get_current_week()
if week:
week = int(week)
max_week = utils.max_number_of_weeks(year)
if week is not None:
if (week <= 0 or week > max_week):
raise http.Http404
# Color mapping for the courses
color_map = utils.ColorMap(hex=True)
try:
semester = Semester.objects.get(year=year, type=semester_type)
except Semester.DoesNotExist:
raise http.Http404
try:
student = Student.objects.distinct().get(slug=slug, subscription__course__semester=semester)
except Student.DoesNotExist:
student = None
# Start setting up queries
courses = Course.objects.get_courses(year, semester.type, slug)
lectures = Lecture.objects.get_lectures(year, semester.type, slug, week)
exams = {}
for exam in Exam.objects.get_exams(year, semester.type, slug):
exams.setdefault(exam.course_id, []).append(exam)
# Use get_related to cut query counts
lecturers = Lecture.get_related(Lecturer, lectures)
groups = Lecture.get_related(Group, lectures, fields=['code'])
rooms = Lecture.get_related(Room, lectures, fields=['name', 'url'])
weeks = Lecture.get_related(Week, lectures, fields=['number'], use_extra=False)
schedule_weeks = set()
for lecture_week_set in weeks.values():
for lecture_week in lecture_week_set:
schedule_weeks.add(lecture_week)
schedule_weeks = list(schedule_weeks)
schedule_weeks.sort()
if schedule_weeks:
schedule_weeks = range(schedule_weeks[0], schedule_weeks[-1]+1)
next_week = None
prev_week = None
# TODO(adamcik): lookup actuall valid weeks.
if week and week < max_week:
next_week = week+1
if week and week > 1:
prev_week = week-1
# Init colors in predictable maner
for c in courses:
color_map[c.id]
# Create Timetable
table = timetable.Timetable(lectures)
if week:
table.set_week(semester.year, week)
if lectures:
table.place_lectures()
table.do_expansion()
table.insert_times()
table.add_markers()
if advanced:
subscriptions = Subscription.objects.get_subscriptions(year, semester.type, slug)
# Set up and course name forms
for course in courses:
alias = course.alias or ''
course.alias_form = forms.CourseAliasForm(
initial={'alias': alias}, prefix=course.id)
try:
next_semester = Semester.objects.next()
next_message = Subscription.objects.get_subscriptions(
next_semester.year, next_semester.type, slug).count() == 0
except Semester.DoesNotExist:
next_semester = None
next_message = False
week_is_current = semester.year == today().year and week == current_week
return shortcuts.render(request, 'schedule.html', {
'advanced': advanced,
'all': all,
'color_map': color_map,
'courses': courses,
'current': (week == current_week),
'current_week': current_week,
'exams': exams,
'next_message': next_message,
'lectures': lectures,
'semester': semester,
'week_is_current': week_is_current,
'next_semester': next_semester,
'slug': slug,
'timetable': table,
'week': week,
'next_week': next_week,
'prev_week': prev_week,
'rooms': rooms,
'weeks': schedule_weeks,
'groups': groups,
'lecturers': lecturers,
'lecture_weeks': weeks,
'student': student,
})
0
Example 11
Project: myks-gallery Source File: views.py
def serve_private_media(request, path):
"""Serve a private media file with the webserver's "sendfile" if possible.
Here's an example of how to use this function. The 'Docuement' model tracks
files. It provides a 'get_file_path' method returning the absolute path to
the actual file. The following view serves file only to users having the
'can_download' permission::
@permission_required('docuements.can_download')
def download_docuement(request, docuement_id):
path = Docuement.objects.get(pk=docuement_id).get_file_path()
return serve_private_media(request, path)
If ``DEBUG`` is ``False`` and ``settings.GALLERY_SENDFILE_HEADER`` is set,
this function sets a header and doesn't send the actual contents of the
file. Use ``'X-Accel-Redirect'`` for nginx and ``'X-SendFile'`` for Apache
with mod_xsendfile. Otherwise, this function behaves like Django's static
serve view.
``path`` must be an absolute path. Depending on your webserver's
configuration, you might want a full path or a relative path in the
header's value. ``settings.GALLERY_SENDFILE_ROOT`` will be stripped from
the beginning of the path to create the header's value.
"""
if not os.path.exists(path):
# Don't reveal the file name on the filesystem.
raise Http404("Requested file doesn't exist.")
# begin copy-paste from django.views.static.serve
statobj = os.stat(path)
content_type, encoding = mimetypes.guess_type(path)
content_type = content_type or 'application/octet-stream'
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj.st_mtime, statobj.st_size): # pragma: no cover
return HttpResponseNotModified()
# pause copy-paste from django.views.static.serve
sendfile_header = getattr(settings, 'GALLERY_SENDFILE_HEADER', '')
sendfile_root = getattr(settings, 'GALLERY_SENDFILE_ROOT', '')
if settings.DEBUG or not sendfile_header:
response = StreamingHttpResponse(open(path, 'rb'), content_type=content_type)
else:
response = HttpResponse('', content_type=content_type)
if sendfile_root:
if not path.startswith(sendfile_root):
raise ValueError("Requested file isn't under GALLERY_SENDFILE_ROOT.")
path = path[len(sendfile_root):]
response[sendfile_header] = path.encode(sys.getfilesystemencoding())
# resume copy-paste from django.views.static.serve
response["Last-Modified"] = http_date(statobj.st_mtime)
if stat.S_ISREG(statobj.st_mode): # pragma: no cover
response["Content-Length"] = statobj.st_size
if encoding: # pragma: no cover
response["Content-Encoding"] = encoding
# end copy-paste from django.views.static.serve
return response
0
Example 12
Project: splunk-webframework Source File: views.py
@staff_member_required
def model_detail(request, app_label, model_name):
if not utils.docutils_is_available:
return missing_docutils_page(request)
# Get the model class.
try:
app_mod = models.get_app(app_label)
except ImproperlyConfigured:
raise Http404(_("App %r not found") % app_label)
model = None
for m in models.get_models(app_mod):
if m._meta.object_name.lower() == model_name:
model = m
break
if model is None:
raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % {'model_name': model_name, 'app_label': app_label})
opts = model._meta
# Gather fields/field descriptions.
fields = []
for field in opts.fields:
# ForeignKey is a special case since the field will actually be a
# descriptor that returns the other object
if isinstance(field, models.ForeignKey):
data_type = field.rel.to.__name__
app_label = field.rel.to._meta.app_label
verbose = utils.parse_rst((_("the related `%(app_label)s.%(data_type)s` object") % {'app_label': app_label, 'data_type': data_type}), 'model', _('model:') + data_type)
else:
data_type = get_readable_field_data_type(field)
verbose = field.verbose_name
fields.append({
'name': field.name,
'data_type': data_type,
'verbose': verbose,
'help_text': field.help_text,
})
# Gather many-to-many fields.
for field in opts.many_to_many:
data_type = field.rel.to.__name__
app_label = field.rel.to._meta.app_label
verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': app_label, 'object_name': data_type}
fields.append({
'name': "%s.all" % field.name,
"data_type": 'List',
'verbose': utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
})
fields.append({
'name' : "%s.count" % field.name,
'data_type' : 'Integer',
'verbose' : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
})
# Gather model methods.
for func_name, func in model.__dict__.items():
if (inspect.isfunction(func) and len(inspect.getargspec(func)[0]) == 1):
try:
for exclude in MODEL_METHODS_EXCLUDE:
if func_name.startswith(exclude):
raise StopIteration
except StopIteration:
continue
verbose = func.__doc__
if verbose:
verbose = utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.module_name)
fields.append({
'name': func_name,
'data_type': get_return_data_type(func_name),
'verbose': verbose,
})
# Gather related objects
for rel in opts.get_all_related_objects() + opts.get_all_related_many_to_many_objects():
verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': rel.opts.app_label, 'object_name': rel.opts.object_name}
accessor = rel.get_accessor_name()
fields.append({
'name' : "%s.all" % accessor,
'data_type' : 'List',
'verbose' : utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name),
})
fields.append({
'name' : "%s.count" % accessor,
'data_type' : 'Integer',
'verbose' : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name),
})
return render_to_response('admin_doc/model_detail.html', {
'root_path': urlresolvers.reverse('admin:index'),
'name': '%s.%s' % (opts.app_label, opts.object_name),
'summary': _("Fields on %s objects") % opts.object_name,
'description': model.__doc__,
'fields': fields,
}, context_instance=RequestContext(request))
0
Example 13
Project: hubplus Source File: views.py
@secure_resource(TgGroup)
def group(request, group, template_name="plus_groups/group.html", current_app='plus_groups', **kwargs):
if not group :
raise Http404(_('There is no group with this id'))
user = request.user
can_join = False
apply = False
leave = False
invite = False
can_comment = False
message = False
add_link = False
can_tag = False
can_change_avatar = False
has_accept = False
can_delete = False
is_following = Following.objects.is_following(request.user, group.get_inner())
editable_group_type = group.group_type != settings.GROUP_HUB_TYPE
if user.is_authenticated():
if user.is_direct_member_of(group.get_inner()):
# can now leave group if you aren't the last one out
if group.get_no_members() > 1 :
leave = True
try :
group.invite_member
invite = True
except Exception, e :# user doesn't have invite permission
pass
else :
try :
group.join
can_join = True
except Exception, e: # user doesn't have join permission
pass
try :
if not can_join :
group.apply
apply = True
except Exception, e : # user doesn't have apply permission
pass
try :
group.comment
can_comment = True
can_tag = True # XXX commentor interface governs who can tag. Do we need a special tag interface?
except :
pass
try :
group.message_members
message = True
except :
pass
try :
group.create_Link
add_link = True
except Exception, e :
print e
pass
try :
group.change_avatar
can_change_avatar = True
except Exception, e:
pass
try :
dummy = group.delete
can_delete = True
except :
pass
if has_access(request.user, None, 'Application.Accept', group._inner.get_security_context()):
has_accept = True
else:
has_accept = False
tweets = FeedItem.feed_manager.get_from_permissioned(group, request.user)
try:
group.get_all_sliders
perms_bool = True
except PlusPermissionsNoAccessException:
perms_bool = False
if kwargs['type'] == 'hub':
type_name = hub_name()
else:
type_name = "Group"
search_types = narrow_search_types(type_name)
side_search = side_search_args(current_app + ':groups', search_types[0][1][2])
search = request.GET.get('search', '')
order = request.GET.get('order', '')
resource_search = resources(group=group, search=search, order=order)
resource_listing_args = listing_args(current_app + ':group_resources', current_app + ':group_resources_tag', tag_string='', search_terms=search, multitabbed=False, order=order, template_base='plus_lib/listing_frag.html', search_type_label='resources')
resource_listing_args['group_id'] = group.id
##############Here we should use the "plus_search" function from plus_explore as above########
member_search = a_member_search(group=group, search=search, order=order,
member_profile_ids=[x.get_profile().get_ref().id for x in group.users.all()])
host_search = a_member_search(group=group.get_admin_group(), search=search, order=order,
member_profile_ids=[x.get_profile().get_ref().id for x in group.get_admin_group().users.all()])
member_listing_args = listing_args(current_app+':group_members', current_app+':group_members_tag', tag_string='', search_terms=search, multitabbed=False, order=order, template_base='plus_lib/listing_frag.html', search_type_label='members', group_id=group.id)
host_listing_args = listing_args(current_app+':group_hosts', current_app+':group_hosts_tag', tag_string='', search_terms=search, multitabbed=False, order=order, template_base='plus_lib/listing_frag.html', search_type_label='hosts', group_id=group.id)
member_count = group.users.all().count()
host_count = group.get_admin_group().users.all().count()
##############################################################################################
return render_to_response(template_name, {
"head_title" : "%s" % group.get_display_name(),
"status_type" : 'group',
#"status_since" : status_since,
"group" : TemplateSecureWrapper(group),
"target_class" : ContentType.objects.get_for_model(group.get_inner()).id,
"target_id" : group.get_inner().id,
#"members" : members,
"member_count" : member_count,
"leave": leave,
"can_join" : can_join,
"apply" : apply,
"invite" : invite,
"can_comment" : can_comment,
"message" : message,
"add_link" : add_link,
"can_tag" : can_tag,
"can_change_avatar" : can_change_avatar,
"can_delete" : can_delete,
"is_following" : is_following,
#"hosts": hosts,
"host_group_id":group.get_admin_group().id,
"host_group_app_label":group.get_admin_group().group_app_label() + ':group',
"is_host":user.is_admin_of(group.get_inner()),
"host_count": host_count,
"tweets" : tweets,
"permissions": perms_bool,
'side_search_args':side_search,
'resource_search':resource_search,
'resource_listing_args':resource_listing_args,
'member_search':member_search,
'member_listing_args':member_listing_args,
'host_search':host_search,
'host_listing_args':host_listing_args,
'group_id':group.id,
'search_types':search_types,
'tagged_url':current_app + ':groups_tag',
'has_accept':has_accept,
'editable_group_type':editable_group_type,
}, context_instance=RequestContext(request, current_app=current_app)
)
0
Example 14
Project: wagtailplus Source File: chooser.py
def chosen_view_factory(chooser_cls):
"""
Returns a ChosenView class that extends specified chooser class.
:param chooser_cls: the class to extend.
:rtype: class.
"""
class ChosenView(chooser_cls):
#noinspection PyUnusedLocal
def get(self, request, *args, **kwargs):
"""
Returns GET response.
:param request: the request instance.
:rtype: django.http.HttpResponse.
"""
#noinspection PyAttributeOutsideInit
self.object = self.get_object()
return render_modal_workflow(
self.request,
None,
'{0}/chosen.js'.format(self.template_dir),
{'obj': self.get_json(self.object)}
)
def get_object(self, queryset=None):
"""
Returns chosen object instance.
:param queryset: the queryset instance.
:rtype: django.db.models.Model.
"""
if queryset is None:
queryset = self.get_queryset()
pk = self.kwargs.get('pk', None)
try:
return queryset.get(pk=pk)
except self.models.DoesNotExist:
raise Http404()
def post(self, request, *args, **kwargs):
"""
Returns POST response.
:param request: the request instance.
:rtype: django.http.HttpResponse.
"""
return self.get(request, *args, **kwargs)
return ChosenView
0
Example 15
Project: ion Source File: activities.py
@eighth_admin_required
def edit_activity_view(request, activity_id):
try:
activity = EighthActivity.objects.get(id=activity_id) # include deleted
except EighthActivity.DoesNotExist:
raise http.Http404
if request.method == "POST":
form = ActivityForm(request.POST, instance=activity)
if form.is_valid():
try:
# Check if sponsor change
old_sponsors = activity.sponsors.all()
old_sponsor_ids = old_sponsors.values_list("id", flat=True)
new_sponsor_ids = [s.id for s in form.cleaned_data["sponsors"]]
if set(old_sponsor_ids) != set(new_sponsor_ids) and len(old_sponsor_ids) > 0:
start_date = get_start_date(request)
sched_acts_default = EighthScheduledActivity.objects.filter(activity=activity, sponsors=None, block__date__lt=start_date)
if sched_acts_default.count() > 0:
# This will change scheduled activities that used overrides in the past.
# Thus, by looping through the scheduled activities that didn't have any
# custom sponsors specified, we *could* prevent anything from visibly
# changing by making an override with the value of the previous default.
# Yes: Save History => Override old values
# No: Change Globally => Don't override old values, they will change to new default
if "change_sponsor_history" in request.POST:
change = request.POST.get("change_sponsor_history")
if change == "yes":
# Override old entries
for sa in sched_acts_default:
for sponsor in old_sponsors:
sa.sponsors.add(sponsor)
sa.save()
messages.success(request,
"Overrode {} scheduled activities to old sponsor default".format(sched_acts_default.count()))
elif change == "no":
# Don't override
messages.success(request, "Changing default sponsors globally")
# Continues to form.save()
else:
# show message, asking whether to change history
context = {
"admin_page_title": "Keep Sponsor History?",
"activity": activity,
"sched_acts_count": sched_acts_default.count(),
"start_date": start_date,
"old_sponsors": EighthSponsor.objects.filter(id__in=old_sponsor_ids),
"new_sponsors": EighthSponsor.objects.filter(id__in=new_sponsor_ids),
"form": form
}
return render(request, "eighth/admin/keep_sponsor_history.html", context)
else:
messages.success(request, "You modified the default sponsors, but those changes will not affect any scheduled activities.")
# Check if room change
old_rooms = activity.rooms.all()
old_room_ids = old_rooms.values_list("id", flat=True)
new_room_ids = [r.id for r in form.cleaned_data["rooms"]]
if set(old_room_ids) != set(new_room_ids) and len(old_room_ids) > 0:
start_date = get_start_date(request)
sched_acts_default = EighthScheduledActivity.objects.filter(activity=activity, rooms=None, block__date__lt=start_date)
if sched_acts_default.count() > 0:
# This will change scheduled activities that used overrides in the past.
# Thus, by looping through the scheduled activities that didn't have any
# custom rooms specified, we *could* prevent anything from visibly
# changing by making an override with the value of the previous default.
# Yes: Save History => Override old values
# No: Change Globally => Don't override old values, they will change to new default
if "change_room_history" in request.POST:
change = request.POST.get("change_room_history")
if change == "yes":
# Override old entries
for sa in sched_acts_default:
for room in old_rooms:
sa.rooms.add(room)
sa.save()
messages.success(request, "Overrode {} scheduled activities to old room default".format(sched_acts_default.count()))
elif change == "no":
# Don't override
messages.success(request, "Changing default rooms globally")
# Continues to form.save()
else:
# show message, asking whether to change history
context = {
"admin_page_title": "Keep Room History?",
"activity": activity,
"sched_acts_count": sched_acts_default.count(),
"start_date": start_date,
"old_rooms": EighthRoom.objects.filter(id__in=old_room_ids),
"new_rooms": EighthRoom.objects.filter(id__in=new_room_ids),
"form": form
}
return render(request, "eighth/admin/keep_room_history.html", context)
else:
messages.success(request, "You modified the default rooms, but those changes will not affect any scheduled activities.")
form.save()
except forms.ValidationError as error:
error = str(error)
messages.error(request, error)
else:
messages.success(request, "Successfully edited activity.")
if "add_group" in request.POST:
grp_name = "Activity: {}".format(activity.name)
grp, status = Group.objects.get_or_create(name=grp_name)
logger.debug(grp)
activity.restricted = True
activity.groups_allowed.add(grp)
activity.save()
invalidate_obj(activity)
messages.success(request, "{} to '{}' group".format("Created and added" if status else "Added", grp_name))
return redirect("eighth_admin_edit_group", grp.id)
return redirect("eighth_admin_edit_activity", activity_id)
else:
messages.error(request, "Error adding activity.")
else:
form = ActivityForm(instance=activity)
activities = EighthActivity.undeleted_objects.order_by("name")
activity_groups = []
for g in activity.groups_allowed.all():
group = {}
group["id"] = g.id
group["name"] = "{}".format(g)
group["members_alpha"] = sorted(g.user_set.all(), key=lambda x: (x.last_name, x.first_name))
group["members_alpha_count"] = len(group["members_alpha"])
activity_groups.append(group)
activity_members = sorted(activity.users_allowed.all(), key=lambda x: (x.last_name, x.first_name))
context = {
"form": form,
"admin_page_title": "Edit Activity",
"delete_url": reverse("eighth_admin_delete_activity", args=[activity_id]),
"activity": activity,
"activity_groups": activity_groups,
"activities": activities,
"activity_members": activity_members
}
return render(request, "eighth/admin/edit_activity.html", context)
0
Example 16
Project: PyClassLessons Source File: views.py
def get_context_data(self, **kwargs):
# Get the model class.
try:
app_config = apps.get_app_config(self.kwargs['app_label'])
except LookupError:
raise Http404(_("App %(app_label)r not found") % self.kwargs)
try:
model = app_config.get_model(self.kwargs['model_name'])
except LookupError:
raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % self.kwargs)
opts = model._meta
# Gather fields/field descriptions.
fields = []
for field in opts.fields:
# ForeignKey is a special case since the field will actually be a
# descriptor that returns the other object
if isinstance(field, models.ForeignKey):
data_type = field.rel.to.__name__
app_label = field.rel.to._meta.app_label
verbose = utils.parse_rst(
(_("the related `%(app_label)s.%(data_type)s` object") % {
'app_label': app_label, 'data_type': data_type,
}),
'model',
_('model:') + data_type,
)
else:
data_type = get_readable_field_data_type(field)
verbose = field.verbose_name
fields.append({
'name': field.name,
'data_type': data_type,
'verbose': verbose,
'help_text': field.help_text,
})
# Gather many-to-many fields.
for field in opts.many_to_many:
data_type = field.rel.to.__name__
app_label = field.rel.to._meta.app_label
verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': app_label, 'object_name': data_type}
fields.append({
'name': "%s.all" % field.name,
"data_type": 'List',
'verbose': utils.parse_rst(_("all %s") % verbose, 'model', _('model:') + opts.model_name),
})
fields.append({
'name': "%s.count" % field.name,
'data_type': 'Integer',
'verbose': utils.parse_rst(_("number of %s") % verbose, 'model', _('model:') + opts.model_name),
})
# Gather model methods.
for func_name, func in model.__dict__.items():
if (inspect.isfunction(func) and len(inspect.getargspec(func)[0]) == 1):
try:
for exclude in MODEL_METHODS_EXCLUDE:
if func_name.startswith(exclude):
raise StopIteration
except StopIteration:
continue
verbose = func.__doc__
if verbose:
verbose = utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.model_name)
fields.append({
'name': func_name,
'data_type': get_return_data_type(func_name),
'verbose': verbose,
})
# Gather related objects
for rel in opts.get_all_related_objects() + opts.get_all_related_many_to_many_objects():
verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': rel.opts.app_label, 'object_name': rel.opts.object_name}
accessor = rel.get_accessor_name()
fields.append({
'name': "%s.all" % accessor,
'data_type': 'List',
'verbose': utils.parse_rst(_("all %s") % verbose, 'model', _('model:') + opts.model_name),
})
fields.append({
'name': "%s.count" % accessor,
'data_type': 'Integer',
'verbose': utils.parse_rst(_("number of %s") % verbose, 'model', _('model:') + opts.model_name),
})
kwargs.update({
'name': '%s.%s' % (opts.app_label, opts.object_name),
# Translators: %s is an object type name
'summary': _("Attributes on %s objects") % opts.object_name,
'description': model.__doc__,
'fields': fields,
})
return super(ModelDetailView, self).get_context_data(**kwargs)
0
Example 17
Project: ion Source File: views.py
@login_required
def poll_vote_view(request, poll_id):
try:
poll = Poll.objects.get(id=poll_id)
except Poll.DoesNotExist:
raise http.Http404
user = request.user
is_polls_admin = user.has_admin_permission("polls")
if is_polls_admin and "user" in request.GET:
try:
user = User.objects.get(id=request.GET.get("user"))
except (User.DoesNotExist, ValueError):
user = request.user
if request.method == "POST":
questions = poll.question_set.all()
entries = request.POST
for name in entries:
if name.startswith("question-"):
logger.debug(name)
question_num = name.split("question-", 2)[1]
logger.debug(question_num)
try:
question_obj = questions.get(num=question_num)
except Question.DoesNotExist:
messages.error(request, "Invalid question passes with num {}".format(question_num))
continue
logger.debug(question_obj)
choice_num = entries[name]
logger.debug(choice_num)
if question_obj.is_choice():
choices = question_obj.choice_set.all()
if question_obj.is_single_choice():
if choice_num and choice_num == "CLEAR":
Answer.objects.filter(user=user, question=question_obj).delete()
Answer.objects.create(user=user, question=question_obj, clear_vote=True)
messages.success(request, "Clear Vote for {}".format(question_obj))
else:
try:
choice_obj = choices.get(num=choice_num)
except Choice.DoesNotExist:
messages.error(request, "Invalid answer choice with num {}".format(choice_num))
continue
else:
logger.debug(choice_obj)
Answer.objects.filter(user=user, question=question_obj).delete()
Answer.objects.create(user=user, question=question_obj, choice=choice_obj)
messages.success(request, "Voted for {} on {}".format(choice_obj, question_obj))
elif question_obj.is_many_choice():
total_choices = request.POST.getlist(name)
logger.debug("total choices: {}".format(total_choices))
if len(total_choices) == 1 and total_choices[0] == "CLEAR":
Answer.objects.filter(user=user, question=question_obj).delete()
Answer.objects.create(user=user, question=question_obj, clear_vote=True)
messages.success(request, "Clear Vote for {}".format(question_obj))
else:
current_choices = Answer.objects.filter(user=user, question=question_obj)
logger.debug("current choices: {}".format(current_choices))
current_choices_nums = [c.choice.num if c.choice else None for c in current_choices]
# delete entries that weren't checked but in db
for c in current_choices_nums:
if c and c not in total_choices:
ch = choices.get(num=c)
logger.info("Deleting choice for {}".format(ch))
Answer.objects.filter(user=user, question=question_obj, choice=ch).delete()
for c in total_choices:
# gets re-checked on each loop
current_choices = Answer.objects.filter(user=user, question=question_obj)
try:
choice_obj = choices.get(num=c)
except Choice.DoesNotExist:
messages.error(request, "Invalid answer choice with num {}".format(choice_num))
continue
else:
if (current_choices.count() + 1) <= question_obj.max_choices:
Answer.objects.filter(user=user, question=question_obj, clear_vote=True).delete()
Answer.objects.get_or_create(user=user, question=question_obj, choice=choice_obj)
messages.success(request, "Voted for {} on {}".format(choice_obj, question_obj))
else:
messages.error(request, "You have voted on too many options for {}".format(question_obj))
current_choices.delete()
elif question_obj.is_writing():
Answer.objects.filter(user=user, question=question_obj).delete()
Answer.objects.create(user=user, question=question_obj, answer=choice_num)
messages.success(request, "Answer saved for {}".format(question_obj))
questions = []
for q in poll.question_set.all():
current_votes = Answer.objects.filter(user=user, question=q)
if q.type == Question.ELECTION:
choices = q.random_choice_set
else:
choices = q.choice_set.all()
question = {
"num": q.num,
"type": q.type,
"question": q.question,
"choices": choices,
"is_single_choice": q.is_single_choice(),
"is_many_choice": q.is_many_choice(),
"is_writing": q.is_writing(),
"max_choices": q.max_choices,
"current_votes": current_votes,
"current_vote": current_votes[0] if len(current_votes) > 0 else None,
"current_choices": [v.choice for v in current_votes],
"current_vote_none": (len(current_votes) < 1),
"current_vote_clear": (len(current_votes) == 1 and current_votes[0].clear_vote)
}
questions.append(question)
logger.debug(questions)
can_vote = poll.can_vote(user)
context = {"poll": poll, "can_vote": can_vote, "user": user, "questions": questions, "question_types": Question.get_question_types()}
return render(request, "polls/vote.html", context)
0
Example 18
def shortcut(request, content_type_id, object_id):
"""
Redirect to an object's page based on a content-type ID and an object ID.
"""
# Look up the object, making sure it's got a get_absolute_url() function.
try:
content_type = ContentType.objects.get(pk=content_type_id)
if not content_type.model_class():
raise http.Http404(_("Content type %(ct_id)s object has no associated model") %
{'ct_id': content_type_id})
obj = content_type.get_object_for_this_type(pk=object_id)
except (ObjectDoesNotExist, ValueError):
raise http.Http404(_("Content type %(ct_id)s object %(obj_id)s doesn't exist") %
{'ct_id': content_type_id, 'obj_id': object_id})
try:
get_absolute_url = obj.get_absolute_url
except AttributeError:
raise http.Http404(_("%(ct_name)s objects don't have a get_absolute_url() method") %
{'ct_name': content_type.name})
absurl = get_absolute_url()
# Try to figure out the object's domain, so we can do a cross-site redirect
# if necessary.
# If the object actually defines a domain, we're done.
if absurl.startswith(('http://', 'https://', '//')):
return http.HttpResponseRedirect(absurl)
# Otherwise, we need to introspect the object's relationships for a
# relation to the Site object
object_domain = None
if apps.is_installed('django.contrib.sites'):
Site = apps.get_model('sites.Site')
opts = obj._meta
# First, look for an many-to-many relationship to Site.
for field in opts.many_to_many:
if field.rel.to is Site:
try:
# Caveat: In the case of multiple related Sites, this just
# selects the *first* one, which is arbitrary.
object_domain = getattr(obj, field.name).all()[0].domain
except IndexError:
pass
if object_domain is not None:
break
# Next, look for a many-to-one relationship to Site.
if object_domain is None:
for field in obj._meta.fields:
if field.rel and field.rel.to is Site:
try:
object_domain = getattr(obj, field.name).domain
except Site.DoesNotExist:
pass
if object_domain is not None:
break
# Fall back to the current site (if possible).
if object_domain is None:
try:
object_domain = Site.objects.get_current(request).domain
except Site.DoesNotExist:
pass
else:
# Fall back to the current request's site.
object_domain = RequestSite(request).domain
# If all that malarkey found an object domain, use it. Otherwise, fall back
# to whatever get_absolute_url() returned.
if object_domain is not None:
protocol = request.scheme
return http.HttpResponseRedirect('%s://%s%s'
% (protocol, object_domain, absurl))
else:
return http.HttpResponseRedirect(absurl)
0
Example 19
@login_required
def check_connection(request):
if request.method != 'POST':
raise Http404()
# Check VPN connectivity
# Get log lines with TLS-auth error before connection
try:
with open(settings.OPENVPN_LOGFILE) as f:
log_lines_before = f.readlines()
except IOError:
return HttpResponse('{"status": "error", "msg": "openvpn.log konnte nicht geöffnet werden."}')
# Send request to upribox API
try:
r = requests.get("https://api.upribox.org/connectivity/", timeout=7, verify=settings.SSL_PINNING_PATH)
except:
return HttpResponse('{"status": "error", "msg": "Verbindung zu api.upribox.org fehlgeschlagen."}')
# Get log lines with TLS-auth error after connection
try:
with open(settings.OPENVPN_LOGFILE) as f:
log_lines_after = f.readlines()
except IOError:
return HttpResponse('{"status": "error", "msg": "openvpn.log konnte nicht geöffnet werden."}')
# Count error messages in logs
count_errors_before = 0
for ll in log_lines_before:
if ll.find("TLS Error") and ll.find(r.text):
count_errors_before += 1
count_errors_after = 0
for ll in log_lines_after:
if ll.find("TLS Error") and ll.find(r.text):
count_errors_after += 1
# Check if error messages occurred
if count_errors_before < count_errors_after:
# Connection succeeded
return HttpResponse('{"status": "success", "msg": "That was great!"}')
else:
# Connection failed
return HttpResponse('{"status": "failure", "msg": "It obviously could not connect!"}')
0
Example 20
Project: symposion Source File: views.py
@login_required
def proposal_speaker_manage(request, pk):
queryset = ProposalBase.objects.select_related("speaker")
proposal = get_object_or_404(queryset, pk=pk)
proposal = ProposalBase.objects.get_subclass(pk=proposal.pk)
if proposal.speaker != request.user.speaker_profile:
raise Http404()
if request.method == "POST":
add_speaker_form = AddSpeakerForm(request.POST, proposal=proposal)
if add_speaker_form.is_valid():
message_ctx = {
"proposal": proposal,
}
def create_speaker_token(email_address):
# create token and look for an existing speaker to prevent
# duplicate tokens and confusing the pending speaker
try:
pending = Speaker.objects.get(
Q(user=None, invite_email=email_address)
)
except Speaker.DoesNotExist:
salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
token = hashlib.sha1(salt + email_address).hexdigest()
pending = Speaker.objects.create(
invite_email=email_address,
invite_token=token,
)
else:
token = pending.invite_token
return pending, token
email_address = add_speaker_form.cleaned_data["email"]
# check if email is on the site now
users = EmailAddress.objects.get_users_for(email_address)
if users:
# should only be one since we enforce unique email
user = users[0]
message_ctx["user"] = user
# look for speaker profile
try:
speaker = user.speaker_profile
except ObjectDoesNotExist:
speaker, token = create_speaker_token(email_address)
message_ctx["token"] = token
# fire off email to user to create profile
send_email(
[email_address], "speaker_no_profile",
context=message_ctx
)
else:
# fire off email to user letting them they are loved.
send_email(
[email_address], "speaker_addition",
context=message_ctx
)
else:
speaker, token = create_speaker_token(email_address)
message_ctx["token"] = token
# fire off email letting user know about site and to create
# account and speaker profile
send_email(
[email_address], "speaker_invite",
context=message_ctx
)
invitation, created = AdditionalSpeaker.objects.get_or_create(
proposalbase=proposal.proposalbase_ptr, speaker=speaker)
messages.success(request, "Speaker invited to proposal.")
return redirect("proposal_speaker_manage", proposal.pk)
else:
add_speaker_form = AddSpeakerForm(proposal=proposal)
ctx = {
"proposal": proposal,
"speakers": proposal.speakers(),
"add_speaker_form": add_speaker_form,
}
return render(request, "symposion/proposals/proposal_speaker_manage.html", ctx)
0
Example 21
Project: django-cbv Source File: date_based.py
def object_detail(request, year, month, day, queryset, date_field,
month_format='%b', day_format='%d', object_id=None, slug=None,
slug_field='slug', template_name=None, template_name_field=None,
template_loader=loader, extra_context=None, context_processors=None,
template_object_name='object', mimetype=None, allow_future=False):
"""
Generic detail view from year/month/day/slug or year/month/day/id
structure.
Templates: ``<app_label>/<model_name>_detail.html``
Context:
object:
the object to be detailed
"""
if extra_context is None:
extra_context = {}
try:
tt = time.strptime('%s-%s-%s' % (year, month, day),
'%s-%s-%s' % ('%Y', month_format, day_format))
date = datetime.date(*tt[:3])
except ValueError:
raise Http404
model = queryset.model
now = datetime.datetime.now()
if isinstance(model._meta.get_field(date_field), DateTimeField):
date_range = (
datetime.datetime.combine(date, datetime.time.min),
datetime.datetime.combine(date, datetime.time.max)
)
lookup_kwargs = {'%s__range' % date_field: date_range}
else:
lookup_kwargs = {date_field: date}
# Only bother to check current date if the date isn't in the past and
# future objects aren't requested.
if date >= now.date() and not allow_future:
lookup_kwargs['%s__lte' % date_field] = now
if object_id:
lookup_kwargs['%s__exact' % model._meta.pk.name] = object_id
elif slug and slug_field:
lookup_kwargs['%s__exact' % slug_field] = slug
else:
raise AttributeError("Generic detail view must be called with either "
"an object_id or a slug/slugfield")
try:
obj = queryset.get(**lookup_kwargs)
except ObjectDoesNotExist:
raise Http404("No %s found for" % model._meta.verbose_name)
if not template_name:
template_name = "%s/%s_detail.html" % (
model._meta.app_label,
model._meta.object_name.lower()
)
if template_name_field:
template_name_list = [getattr(obj, template_name_field), template_name]
t = template_loader.select_template(template_name_list)
else:
t = template_loader.get_template(template_name)
c = RequestContext(request, {
template_object_name: obj,
}, context_processors)
for key, value in extra_context.items():
if callable(value):
c[key] = value()
else:
c[key] = value
response = HttpResponse(t.render(c), mimetype=mimetype)
populate_xheaders(request, response, model,
getattr(obj, obj._meta.pk.name))
return response
0
Example 22
Project: djangobb Source File: views.py
def search(request):
# TODO: used forms in every search type
def _render_search_form(form=None):
return render(request, 'djangobb_forum/search_form.html', {'categories': Category.objects.all(),
'form': form,
})
if not 'action' in request.GET:
return _render_search_form(form=PostSearchForm())
if request.GET.get("show_as") == "posts":
show_as_posts = True
template_name = 'djangobb_forum/search_posts.html'
else:
show_as_posts = False
template_name = 'djangobb_forum/search_topics.html'
context = {}
# Create 'user viewable' pre-filtered topics/posts querysets
viewable_category = Category.objects.all()
topics = Topic.objects.all().order_by("-last_post__created")
posts = Post.objects.all().order_by('-created')
user = request.user
if not user.is_superuser:
user_groups = user.groups.all() or [] # need 'or []' for anonymous user otherwise: 'EmptyManager' object is not iterable
viewable_category = viewable_category.filter(Q(groups__in=user_groups) | Q(groups__isnull=True))
topics = Topic.objects.filter(forum__category__in=viewable_category)
posts = Post.objects.filter(topic__forum__category__in=viewable_category)
base_url = None
_generic_context = True
action = request.GET['action']
if action == 'show_24h':
date = timezone.now() - timedelta(days=1)
if show_as_posts:
context["posts"] = posts.filter(Q(created__gte=date) | Q(updated__gte=date))
else:
context["topics"] = topics.filter(Q(last_post__created__gte=date) | Q(last_post__updated__gte=date))
_generic_context = False
elif action == 'show_new':
if not user.is_authenticated():
raise Http404("Search 'show_new' not available for anonymous user.")
try:
last_read = PostTracking.objects.get(user=user).last_read
except PostTracking.DoesNotExist:
last_read = None
if last_read:
if show_as_posts:
context["posts"] = posts.filter(Q(created__gte=last_read) | Q(updated__gte=last_read))
else:
context["topics"] = topics.filter(Q(last_post__created__gte=last_read) | Q(last_post__updated__gte=last_read))
_generic_context = False
else:
#searching more than forum_settings.SEARCH_PAGE_SIZE in this way - not good idea :]
topics_id = [topic.id for topic in topics[:forum_settings.SEARCH_PAGE_SIZE] if forum_extras.has_unreads(topic, user)]
topics = Topic.objects.filter(id__in=topics_id) # to create QuerySet
elif action == 'show_unanswered':
topics = topics.filter(post_count=1)
elif action == 'show_subscriptions':
topics = topics.filter(subscribers__id=user.id)
elif action == 'show_user':
# Show all posts from user or topics started by user
if not user.is_authenticated():
raise Http404("Search 'show_user' not available for anonymous user.")
user_id = request.GET.get("user_id", user.id)
try:
user_id = int(user_id)
except ValueError:
raise SuspiciousOperation()
if user_id != user.id:
try:
search_user = User.objects.get(id=user_id)
except User.DoesNotExist:
messages.error(request, _("Error: User unknown!"))
return HttpResponseRedirect(request.path)
messages.info(request, _("Filter by user '%(username)s'.") % {'username': search_user.username})
if show_as_posts:
posts = posts.filter(user__id=user_id)
else:
# show as topic
topics = topics.filter(posts__user__id=user_id).order_by("-last_post__created").distinct()
base_url = "?action=show_user&user_id=%s&show_as=" % user_id
elif action == 'search':
form = PostSearchForm(request.GET)
if not form.is_valid():
return _render_search_form(form)
keywords = form.cleaned_data['keywords']
author = form.cleaned_data['author']
forum = form.cleaned_data['forum']
search_in = form.cleaned_data['search_in']
sort_by = form.cleaned_data['sort_by']
sort_dir = form.cleaned_data['sort_dir']
query = SearchQuerySet().models(Post)
if author:
query = query.filter(author__username=author)
if forum != '0':
query = query.filter(forum__id=forum)
if keywords:
if search_in == 'all':
query = query.filter(SQ(topic=keywords) | SQ(text=keywords))
elif search_in == 'message':
query = query.filter(text=keywords)
elif search_in == 'topic':
query = query.filter(topic=keywords)
order = {'0': 'created',
'1': 'author',
'2': 'topic',
'3': 'forum'}.get(sort_by, 'created')
if sort_dir == 'DESC':
order = '-' + order
post_pks = query.values_list("pk", flat=True)
if not show_as_posts:
# TODO: We have here a problem to get a list of topics without double entries.
# Maybe we must add a search index over topics?
# Info: If whoosh backend used, setup HAYSTACK_ITERATOR_LOAD_PER_QUERY
# to a higher number to speed up
context["topics"] = topics.filter(posts__in=post_pks).distinct()
else:
# FIXME: How to use the pre-filtered query from above?
posts = posts.filter(pk__in=post_pks).order_by(order)
context["posts"] = posts
get_query_dict = request.GET.copy()
get_query_dict.pop("show_as")
base_url = "?%s&show_as=" % get_query_dict.urlencode()
_generic_context = False
if _generic_context:
if show_as_posts:
context["posts"] = posts.filter(topic__in=topics).order_by('-created')
else:
context["topics"] = topics
if base_url is None:
base_url = "?action=%s&show_as=" % action
if show_as_posts:
context['posts_page'] = get_page(context['posts'], request, forum_settings.SEARCH_PAGE_SIZE)
context["as_topic_url"] = base_url + "topics"
post_count = context["posts"].count()
messages.success(request, _("Found %i posts.") % post_count)
else:
context['topics_page'] = get_page(context['topics'], request, forum_settings.SEARCH_PAGE_SIZE)
context["as_post_url"] = base_url + "posts"
topic_count = context["topics"].count()
messages.success(request, _("Found %i topics.") % topic_count)
return render(request, template_name, context)
0
Example 23
Project: django-generic-images Source File: app_utils.py
def get_site_decorator(site_param='site', obj_param='obj', context_param='context'):
''' It is a function that returns decorator factory useful for PluggableSite
views. This decorator factory returns decorator that do some
boilerplate work and make writing PluggableSite views easier.
It passes PluggableSite instance to decorated view,
retreives and passes object that site is attached to and passes
common context. It also passes and all the decorator factory's
keyword arguments.
For example usage please check photo_albums.views.
Btw, this decorator seems frightening for me. It feels that
"views as PluggableSite methods" approach can easily make this decorator
obsolete. But for now it just works.
'''
def site_method(**extra_params):
def decorator(fn):
@wraps(fn)
def wrapper(request, **kwargs):
try:
site = kwargs.pop(site_param)
except KeyError:
raise ValueError("'%s' parameter must be passed to "
"decorated view (%s)" % (site_param, fn))
# Pop parameters to be passed to actual view function.
params={}
for key in extra_params:
value = kwargs.pop(key, extra_params[key])
params.update({key:value})
# Now there are only site.object_getter lookup parameters in
# kwargs. Get the object and compute common request context.
try:
obj = site.object_getter(**kwargs)
except models.ObjectDoesNotExist:
raise Http404("Base object does not exist.")
context = site.get_common_context(obj)
context_instance = RequestContext(request, context,
processors=site.context_processors)
# pass site name, the object and common request to decorated view
params.update({
site_param:site,
obj_param: obj,
context_param: context_instance
})
return fn(request, **params)
return wrapper
return decorator
return site_method
0
Example 24
Project: GAE-Bulk-Mailer Source File: base.py
def get_response(self, request):
"Returns an HttpResponse object for the given HttpRequest"
try:
# Setup default url resolver for this thread, this code is outside
# the try/except so we don't get a spurious "unbound local
# variable" exception in the event an exception is raised before
# resolver is set
urlconf = settings.ROOT_URLCONF
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
try:
response = None
# Apply request middleware
for middleware_method in self._request_middleware:
response = middleware_method(request)
if response:
break
if response is None:
if hasattr(request, 'urlconf'):
# Reset url resolver with a custom urlconf.
urlconf = request.urlconf
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
resolver_match = resolver.resolve(request.path_info)
callback, callback_args, callback_kwargs = resolver_match
request.resolver_match = resolver_match
# Apply view middleware
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
break
if response is None:
try:
response = callback(request, *callback_args, **callback_kwargs)
except Exception as e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
if response:
break
if response is None:
raise
# Complain if the view returned None (a common error).
if response is None:
if isinstance(callback, types.FunctionType): # FBV
view_name = callback.__name__
else: # CBV
view_name = callback.__class__.__name__ + '.__call__'
raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name))
# If the response supports deferred rendering, apply template
# response middleware and the render the response
if hasattr(response, 'render') and callable(response.render):
for middleware_method in self._template_response_middleware:
response = middleware_method(request, response)
response = response.render()
except http.Http404 as e:
logger.warning('Not Found: %s', request.path,
extra={
'status_code': 404,
'request': request
})
if settings.DEBUG:
response = debug.technical_404_response(request, e)
else:
try:
callback, param_dict = resolver.resolve404()
response = callback(request, **param_dict)
except:
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
except exceptions.PermissionDenied:
logger.warning(
'Forbidden (Permission denied): %s', request.path,
extra={
'status_code': 403,
'request': request
})
try:
callback, param_dict = resolver.resolve403()
response = callback(request, **param_dict)
except:
signals.got_request_exception.send(
sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request,
resolver, sys.exc_info())
except SystemExit:
# Allow sys.exit() to actually exit. See tickets #1023 and #4701
raise
except: # Handle everything else, including SuspiciousOperation, etc.
# Get the exception info now, in case another exception is thrown later.
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
finally:
# Reset URLconf for this thread on the way out for complete
# isolation of request.urlconf
urlresolvers.set_urlconf(None)
try:
# Apply response middleware, regardless of the response
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
response = self.apply_response_fixes(request, response)
except: # Any exception should be gathered and handled
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
return response
0
Example 25
Project: splunk-webframework Source File: views.py
def shortcut(request, content_type_id, object_id):
"""
Redirect to an object's page based on a content-type ID and an object ID.
"""
# Look up the object, making sure it's got a get_absolute_url() function.
try:
content_type = ContentType.objects.get(pk=content_type_id)
if not content_type.model_class():
raise http.Http404(_("Content type %(ct_id)s object has no associated model") %
{'ct_id': content_type_id})
obj = content_type.get_object_for_this_type(pk=object_id)
except (ObjectDoesNotExist, ValueError):
raise http.Http404(_("Content type %(ct_id)s object %(obj_id)s doesn't exist") %
{'ct_id': content_type_id, 'obj_id': object_id})
try:
get_absolute_url = obj.get_absolute_url
except AttributeError:
raise http.Http404(_("%(ct_name)s objects don't have a get_absolute_url() method") %
{'ct_name': content_type.name})
absurl = get_absolute_url()
# Try to figure out the object's domain, so we can do a cross-site redirect
# if necessary.
# If the object actually defines a domain, we're done.
if absurl.startswith('http://') or absurl.startswith('https://'):
return http.HttpResponseRedirect(absurl)
# Otherwise, we need to introspect the object's relationships for a
# relation to the Site object
object_domain = None
if Site._meta.installed:
opts = obj._meta
# First, look for an many-to-many relationship to Site.
for field in opts.many_to_many:
if field.rel.to is Site:
try:
# Caveat: In the case of multiple related Sites, this just
# selects the *first* one, which is arbitrary.
object_domain = getattr(obj, field.name).all()[0].domain
except IndexError:
pass
if object_domain is not None:
break
# Next, look for a many-to-one relationship to Site.
if object_domain is None:
for field in obj._meta.fields:
if field.rel and field.rel.to is Site:
try:
object_domain = getattr(obj, field.name).domain
except Site.DoesNotExist:
pass
if object_domain is not None:
break
# Fall back to the current site (if possible).
if object_domain is None:
try:
object_domain = get_current_site(request).domain
except Site.DoesNotExist:
pass
# If all that malarkey found an object domain, use it. Otherwise, fall back
# to whatever get_absolute_url() returned.
if object_domain is not None:
protocol = request.is_secure() and 'https' or 'http'
return http.HttpResponseRedirect('%s://%s%s'
% (protocol, object_domain, absurl))
else:
return http.HttpResponseRedirect(absurl)
0
Example 26
Project: Misago Source File: test_apipatch.py
def test_dispatch(self):
"""dispatch calls actions and returns response"""
patch = ApiPatch()
def action_error(request, target, value):
if value == '404':
raise Http404()
if value == 'perm':
raise PermissionDenied("yo ain't doing that!")
patch.replace('error', action_error)
def action_mutate(request, target, value):
return {'value': value * 2}
patch.replace('mutate', action_mutate)
# dispatch requires list as an argument
response = patch.dispatch(MockRequest({}), {})
self.assertEqual(response.status_code, 400)
self.assertEqual(
response.data['detail'],
"PATCH request should be list of operations")
# valid dispatch
response = patch.dispatch(MockRequest([
{'op': 'replace', 'path': 'mutate', 'value': 2},
{'op': 'replace', 'path': 'mutate', 'value': 6},
{'op': 'replace', 'path': 'mutate', 'value': 7},
]), MockObject(13))
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.data['detail']), 3)
self.assertEqual(response.data['detail'][0], 'ok')
self.assertEqual(response.data['detail'][1], 'ok')
self.assertEqual(response.data['detail'][2], 'ok')
self.assertEqual(response.data['id'], 13)
self.assertEqual(response.data['value'], 14)
# invalid action in dispatch
response = patch.dispatch(MockRequest([
{'op': 'replace', 'path': 'mutate', 'value': 2},
{'op': 'replace', 'path': 'mutate', 'value': 6},
{'op': 'replace'},
{'op': 'replace', 'path': 'mutate', 'value': 7},
]), MockObject(13))
self.assertEqual(response.status_code, 400)
self.assertEqual(len(response.data['detail']), 3)
self.assertEqual(response.data['detail'][0], 'ok')
self.assertEqual(response.data['detail'][1], 'ok')
self.assertEqual(
response.data['detail'][2], '"replace" op has to specify path')
self.assertEqual(response.data['id'], 13)
self.assertEqual(response.data['value'], 12)
# action in dispatch raised 404
response = patch.dispatch(MockRequest([
{'op': 'replace', 'path': 'mutate', 'value': 2},
{'op': 'replace', 'path': 'error', 'value': '404'},
{'op': 'replace', 'path': 'mutate', 'value': 6},
{'op': 'replace', 'path': 'mutate', 'value': 7},
]), MockObject(13))
self.assertEqual(response.status_code, 400)
self.assertEqual(len(response.data['detail']), 2)
self.assertEqual(response.data['detail'][0], 'ok')
self.assertEqual(
response.data['detail'][1], "NOT FOUND")
self.assertEqual(response.data['id'], 13)
self.assertEqual(response.data['value'], 4)
# action in dispatch raised perm denied
response = patch.dispatch(MockRequest([
{'op': 'replace', 'path': 'mutate', 'value': 2},
{'op': 'replace', 'path': 'mutate', 'value': 6},
{'op': 'replace', 'path': 'mutate', 'value': 9},
{'op': 'replace', 'path': 'error', 'value': 'perm'},
]), MockObject(13))
self.assertEqual(response.status_code, 400)
self.assertEqual(len(response.data['detail']), 4)
self.assertEqual(response.data['detail'][0], 'ok')
self.assertEqual(response.data['detail'][1], 'ok')
self.assertEqual(response.data['detail'][2], 'ok')
self.assertEqual(
response.data['detail'][3], "yo ain't doing that!")
self.assertEqual(response.data['id'], 13)
self.assertEqual(response.data['value'], 18)
0
Example 27
def paginate_queryset(self, queryset, page_size=None):
"""
Paginate a queryset if required, either returning a page object,
or `None` if pagination is not configured for this view.
"""
if "HTTP_X_DISABLE_PAGINATION" in self.request.META:
return None
if "HTTP_X_LAZY_PAGINATION" in self.request.META:
self.paginator_class = LazyPaginator
deprecated_style = False
if page_size is not None:
warnings.warn('The `page_size` parameter to `paginate_queryset()` '
'is due to be deprecated. '
'Note that the return style of this method is also '
'changed, and will simply return a page object '
'when called without a `page_size` argument.',
PendingDeprecationWarning, stacklevel=2)
deprecated_style = True
else:
# Determine the required page size.
# If pagination is not configured, simply return None.
page_size = self.get_paginate_by()
if not page_size:
return None
if not self.allow_empty:
warnings.warn(
'The `allow_empty` parameter is due to be deprecated. '
'To use `allow_empty=False` style behavior, You should override '
'`get_queryset()` and explicitly raise a 404 on empty querysets.',
PendingDeprecationWarning, stacklevel=2
)
paginator = self.paginator_class(queryset, page_size,
allow_empty_first_page=self.allow_empty)
page_kwarg = self.kwargs.get(self.page_kwarg)
page_query_param = self.request.QUERY_PARAMS.get(self.page_kwarg)
page = page_kwarg or page_query_param or 1
try:
page_number = paginator.validate_number(page)
except InvalidPage:
if page == 'last':
page_number = paginator.num_pages
else:
raise Http404(_("Page is not 'last', nor can it be converted to an int."))
try:
page = paginator.page(page_number)
except InvalidPage as e:
raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
'page_number': page_number,
'message': str(e)
})
if page is None:
return page
if not "HTTP_X_LAZY_PAGINATION" in self.request.META:
self.headers["x-pagination-count"] = page.paginator.count
self.headers["x-paginated"] = "true"
self.headers["x-paginated-by"] = page.paginator.per_page
self.headers["x-pagination-current"] = page.number
if page.has_next():
num = page.next_page_number()
url = self.request.build_absolute_uri()
url = replace_query_param(url, "page", num)
self.headers["X-Pagination-Next"] = url
if page.has_previous():
num = page.previous_page_number()
url = self.request.build_absolute_uri()
url = replace_query_param(url, "page", num)
self.headers["X-Pagination-Prev"] = url
return page
0
Example 28
Project: tendenci Source File: views.py
@permission_required('theme_editor.change_themefileversion')
def edit_file(request, form_class=FileForm, template_name="theme_editor/index.html"):
if not has_perm(request.user, 'theme_editor.view_themefileversion'):
raise Http403
selected_theme = request.GET.get("theme_edit", get_theme())
original_theme_root = os.path.join(settings.ORIGINAL_THEMES_DIR, selected_theme)
if settings.USE_S3_THEME:
theme_root = os.path.join(settings.THEME_S3_PATH, selected_theme)
else:
theme_root = os.path.join(settings.ORIGINAL_THEMES_DIR, selected_theme)
# get the default file and clean up any input
default_file = request.GET.get("file", DEFAULT_FILE)
if default_file:
default_file = default_file.replace('\\', '/')
default_file = default_file.strip('/')
default_file = default_file.replace('////', '/')
default_file = default_file.replace('///', '/')
default_file = default_file.replace('//', '/')
is_file = qstr_is_file(default_file, ROOT_DIR=theme_root)
is_dir = qstr_is_dir(default_file, ROOT_DIR=theme_root)
if is_file:
pass
elif is_dir:
# if default_file is a directory then append the
# trailing slash so we can get the dirname below
default_file = '%s/' % default_file
else:
# if the default_file is not a directory or file within
# the themes folder then return a 404
raise Http404(_("Custom template not found. Make sure you've copied over the themes to the THEME_DIR."))
# get the current file name
current_file = os.path.basename(default_file)
# get file ext
name = current_file.split('/')[-1]
ext = name.split('.')[-1]
stylesheets = ['css', 'less']
# get the present working directory
# and make sure they cannot list root
pwd = os.path.dirname(default_file)
if pwd == '/':
pwd = ''
current_file_path = os.path.join(pwd, current_file)
# get the previous directory name and path
prev_dir = '/'
prev_dir_name = 'theme base'
pwd_split = pwd.split('/')
if len(pwd_split) > 1:
prev_dir_name = pwd_split[-2]
pwd_split.pop()
prev_dir = '/'.join(pwd_split)
elif not pwd_split[0]:
prev_dir = ''
# get the direcory list
dirs = get_dir_list(pwd, ROOT_DIR=theme_root)
# get the file list
files, non_editable_files = get_file_list(pwd, ROOT_DIR=theme_root)
all_files_folders = get_all_files_list(ROOT_DIR=theme_root)
# non-deletable files
non_deletable_files = ['homepage.html', 'default.html', 'footer.html', 'header.html', 'sidebar.html', 'nav.html', 'styles.less', 'styles.css']
# get the number of themes in the themes directory on the site
theme_choices = [ i for i in theme_choice_list()]
theme_count = len(theme_choices)
# get a list of revisions
archives = ThemeFileVersion.objects.filter(relative_file_path=default_file).order_by("-create_dt")
if request.is_ajax() and request.method == "POST":
file_form = form_class(request.POST)
response_status = 'FAIL'
response_message = _('Cannot update file.')
if file_form.is_valid():
if file_form.save(request, default_file, ROOT_DIR=theme_root, ORIG_ROOT_DIR=original_theme_root):
response_status = 'SUCCESS'
response_message = unicode(_('Your changes have been saved.'))
EventLog.objects.log()
response = json.dumps({'status':response_status, 'message':response_message})
return HttpResponse(response, content_type="application/json")
content = get_file_content(default_file, ROOT_DIR=theme_root)
file_form = form_class({"content": content, "rf_path": default_file})
theme_form = ThemeSelectForm(initial={'theme_edit': selected_theme})
return render_to_response(template_name, {
'file_form': file_form,
'theme_form': theme_form,
'current_theme': selected_theme,
'current_file_path': current_file_path,
'current_file': current_file,
'prev_dir_name': prev_dir_name,
'prev_dir': prev_dir,
'pwd': pwd,
'dirs': dirs,
'files': files,
'non_editable_files': non_editable_files,
'non_deletable_files': non_deletable_files,
'theme_count': theme_count,
'archives': archives,
'is_file': is_file,
'is_dir': is_dir,
'all_files_folders': all_files_folders,
'ext' : ext,
'stylesheets' : stylesheets
}, context_instance=RequestContext(request))
0
Example 29
Project: redsolution-cms Source File: admin.py
def change_view(self, request, **kwargs):
"The 'change' admin view for this model"
model = self.model
opts = model._meta
try:
obj = self.model.objects.get_settings()
except model.DoesNotExist:
# Don't raise Http404 just yet, because we haven't checked
# permissions yet. We don't want an unauthenticated user to be able
# to determine whether a given object exists.
obj = None
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(kwargs.get('object_id', ''))})
if request.method == 'POST' and request.POST.has_key("_saveasnew"):
return self.add_view(request, form_url='../add/')
ModelForm = self.get_form(request, obj)
formsets = []
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES, instance=obj)
if form.is_valid():
form_validated = True
new_object = self.save_form(request, form, change=True)
else:
form_validated = False
new_object = obj
prefixes = {}
for FormSet in self.get_formsets(request, new_object):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(request.POST, request.FILES,
instance=new_object, prefix=prefix)
formsets.append(formset)
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, change=True)
form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=True)
self.construct_change_message(request, form, formsets)
return self.response_change(request, new_object)
else:
form = ModelForm(instance=obj)
prefixes = {}
for FormSet in self.get_formsets(request, obj):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=obj, prefix=prefix)
formsets.append(formset)
adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(self.inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request, obj))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Change %s') % force_unicode(opts.verbose_name),
'adminform': adminForm,
'original': obj,
'is_popup': request.REQUEST.has_key('_popup'),
'media': mark_safe(media),
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'app_label': opts.app_label,
}
return self.render_change_form(request, context, change=True, obj=obj)
0
Example 30
Project: hubplus Source File: views.py
@login_required
@secure_resource(TgGroup)
def edit_resource(request, group, resource_name,
template_name='plus_resources/upload.html', success_url=None, current_app="plus_groups", **kwargs) :
if not group :
raise Http404(_('This group does not exist'))
try:
secure_upload = Resource.objects.plus_get(request.user, name=resource_name, in_agent=group.get_ref())
except Resource.DoesNotExist:
raise Http404
if secure_upload.name :
old_name = secure_upload.name
else :
old_name = ''
try:
secure_upload.get_all_sliders
perms_bool = True
except PlusPermissionsNoAccessException:
perms_bool = False
if request.POST:
post_kwargs = request.POST.copy()
post_kwargs['obj'] = secure_upload
if "delete_submit" in post_kwargs :
if post_kwargs.has_key('delete_check') :
secure_upload.delete()
return HttpResponseRedirect(reverse(current_app + ':group', args=[group.id]))
if "move_resource_submit" in post_kwargs :
form = MoveResourceForm(post_kwargs)
form.user = request.user # essential, user is checked inside form validation
if form.is_valid() :
new_parent_group = form.cleaned_data['new_parent_group']
try :
secure_upload.move_to_new_group(new_parent_group)
except Exception, e :
print e
return HttpResponseRedirect(reverse(current_app + ':group', args=[form.cleaned_data['new_parent_group'].id]))
form = UploadFileForm(post_kwargs, request.FILES, user=request.user)
if form.is_valid():
a_file = form.cleaned_data['resource']
resource = update_attributes(secure_upload, request.user,
title = form.cleaned_data['title'],
name = form.cleaned_data['name'],
license = form.cleaned_data['license'],
author = form.cleaned_data['author'],
description = form.cleaned_data['description'],
resource = a_file)
resource.stub = False
resource.in_agent = group.get_ref()
# don't allow name to change as this affects the url
if old_name :
resource.name = old_name
resource.save()
if not success_url :
success_url = reverse(current_app + ':view_Resource', args=(group.id, resource.name))
from apps.plus_feed.models import FeedItem
FeedItem.post_UPLOAD(request.user, resource)
return HttpResponseRedirect(success_url)
else:
pass
else :
form = UploadFileForm()
form.data['title'] = secure_upload.title
form.data['name'] = secure_upload.name
tags = get_tags_for_object(secure_upload, request.user)
return render_to_response(template_name, {
'upload': TemplateSecureWrapper(secure_upload),
'resource':TemplateSecureWrapper(secure_upload), # let's us use resource_common included template
'data' : form.data,
'errors': form.errors,
'form_action':'',
'form_encoding':'enctype=multipart/form-data',
'permissions':perms_bool,
'tags':tags,
'pages':[p.get_ref() for p in group.get_resources_of_class(WikiPage)],
'pages_listings_args':listing_args('home', 'home', '')
}, context_instance=RequestContext(request, current_app=current_app))
0
Example 31
Project: django-common Source File: admin.py
@csrf_protect_m
@atomic_decorator
def change_view(self, request, object_id, extra_context=None, **kwargs):
"The 'change' admin view for this model."
model = self.model
opts = model._meta
obj = self.get_object(request, unquote(object_id))
if not self.has_change_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') %
{'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})
if request.method == 'POST' and "_saveasnew" in request.POST:
return self.add_view(request, form_url='../add/')
ModelForm = self.get_form(request, obj)
formsets = []
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES, instance=obj)
if form.is_valid():
form_validated = True
new_object = self.save_form(request, form, change=True)
else:
form_validated = False
new_object = obj
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, new_object),
self.get_inline_instances(request)):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "{0}-{1}".format(prefix, prefixes[prefix])
formset = FormSet(request.POST, request.FILES,
instance=new_object, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
for inline in self.get_inline_instances(request):
# If this is the inline that matches this formset, and
# we have some nested inlines to deal with, then we need
# to get the relevant formset for each of the forms in
# the current formset.
if inline.inlines and inline.model == formset.model:
for nested in inline.inline_instances:
for the_form in formset.forms:
InlineFormSet = nested.get_formset(request, the_form.instance)
prefix = "{0}-{1}".format(the_form.prefix,
InlineFormSet.get_default_prefix())
formsets.append(InlineFormSet(request.POST, request.FILES,
instance=the_form.instance,
prefix=prefix))
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, change=True)
form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=True)
change_message = self.construct_change_message(request, form, formsets)
self.log_change(request, new_object, change_message)
return self.response_change(request, new_object)
else:
form = ModelForm(instance=obj)
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, obj),
self.get_inline_instances(request)):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "{0}-{1}".format(prefix, prefixes[prefix])
formset = FormSet(instance=obj, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
self.prepopulated_fields,
self.get_readonly_fields(request, obj),
model_admin=self)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(self.get_inline_instances(request), formsets):
fieldsets = list(inline.get_fieldsets(request, obj))
readonly = list(inline.get_readonly_fields(request, obj))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets,
readonly, model_admin=self)
if inline.inlines:
for form in formset.forms:
if form.instance.pk:
instance = form.instance
else:
instance = None
form.inlines = inline.get_inlines(request, instance, prefix=form.prefix)
inline_admin_formset.inlines = inline.get_inlines(request)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Change %s') % force_unicode(opts.verbose_name),
'adminform': adminForm,
'object_id': object_id,
'original': obj,
'is_popup': "_popup" in request.REQUEST,
'media': mark_safe(media),
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'app_label': opts.app_label,
}
context.update(extra_context or {})
return self.render_change_form(request, context, change=True, obj=obj)
0
Example 32
Project: readthedocs.org Source File: middleware.py
def process_request(self, request):
if not getattr(settings, 'USE_SUBDOMAIN', False):
return None
full_host = host = request.get_host().lower()
path = request.get_full_path()
log_kwargs = dict(host=host, path=path)
public_domain = getattr(settings, 'PUBLIC_DOMAIN', None)
production_domain = getattr(
settings,
'PRODUCTION_DOMAIN',
'readthedocs.org'
)
if public_domain is None:
public_domain = production_domain
if ':' in host:
host = host.split(':')[0]
domain_parts = host.split('.')
# Serve subdomains - but don't depend on the production domain only having 2 parts
if len(domain_parts) == len(public_domain.split('.')) + 1:
subdomain = domain_parts[0]
is_www = subdomain.lower() == 'www'
if not is_www and (
# Support ports during local dev
public_domain in host or public_domain in full_host
):
request.subdomain = True
request.slug = subdomain
request.urlconf = SUBDOMAIN_URLCONF
return None
# Serve CNAMEs
if (public_domain not in host and
production_domain not in host and
'localhost' not in host and
'testserver' not in host):
request.cname = True
domains = Domain.objects.filter(domain=host)
if domains.count():
for domain in domains:
if domain.domain == host:
request.slug = domain.project.slug
request.urlconf = SUBDOMAIN_URLCONF
request.domain_object = True
log.debug(LOG_TEMPLATE.format(
msg='Domain Object Detected: %s' % domain.domain,
**log_kwargs))
break
if (not hasattr(request, 'domain_object') and
'HTTP_X_RTD_SLUG' in request.META):
request.slug = request.META['HTTP_X_RTD_SLUG'].lower()
request.urlconf = SUBDOMAIN_URLCONF
request.rtdheader = True
log.debug(LOG_TEMPLATE.format(
msg='X-RTD-Slug header detected: %s' % request.slug,
**log_kwargs))
# Try header first, then DNS
elif not hasattr(request, 'domain_object'):
try:
slug = cache.get(host)
if not slug:
slug = cname_to_slug(host)
cache.set(host, slug, 60 * 60)
# Cache the slug -> host mapping permanently.
log.debug(LOG_TEMPLATE.format(
msg='CNAME cached: %s->%s' % (slug, host),
**log_kwargs))
request.slug = slug
request.urlconf = SUBDOMAIN_URLCONF
log.debug(LOG_TEMPLATE.format(
msg='CNAME detected: %s' % request.slug,
**log_kwargs))
except:
# Some crazy person is CNAMEing to us. 404.
log.exception(LOG_TEMPLATE.format(msg='CNAME 404', **log_kwargs))
raise Http404(_('Invalid hostname'))
# Google was finding crazy www.blah.readthedocs.org domains.
# Block these explicitly after trying CNAME logic.
if len(domain_parts) > 3 and not settings.DEBUG:
# Stop www.fooo.readthedocs.org
if domain_parts[0] == 'www':
log.debug(LOG_TEMPLATE.format(msg='404ing long domain', **log_kwargs))
return HttpResponseBadRequest(_('Invalid hostname'))
log.debug(LOG_TEMPLATE.format(msg='Allowing long domain name', **log_kwargs))
# raise Http404(_('Invalid hostname'))
# Normal request.
return None
0
Example 33
Project: ion Source File: rooms.py
@eighth_admin_required
def room_utilization_action(request, start_id, end_id):
try:
start_block = EighthBlock.objects.get(id=start_id)
end_block = EighthBlock.objects.get(id=end_id)
one_block = (start_id == end_id)
except EighthBlock.DoesNotExist:
raise http.Http404
show_all_rooms = ("show_all" in request.GET)
show_listing = show_all_rooms or ("room" in request.GET)
all_rooms = EighthRoom.objects.all().order_by("name")
# If a "show" GET parameter is defined, only show the values that are given.
show_vals = request.GET.getlist("show")
show_opts = ["block", "rooms", "capacity", "signups", "aid", "activity", "comments", "sponsors", "admin_comments"]
show_opts_defaults = ["block", "rooms", "capacity", "signups", "aid", "activity", "comments", "sponsors"]
show_opts_hidden = ["admin_comments"]
if len(show_vals) == 0:
show = {name: True for name in show_opts_defaults}
show.update({name: False for name in show_opts_hidden})
else:
show = {name: name in show_vals for name in show_opts}
hide_administrative = "hide_administrative" in request.GET and request.GET.get("hide_administrative") != "0"
only_show_overbooked = "only_show_overbooked" in request.GET and request.GET.get("only_show_overbooked") != "0"
context = {
"admin_page_title": "Room Utilization",
"start_block": start_block,
"end_block": end_block,
"all_rooms": all_rooms,
"show": show,
"hide_administrative": hide_administrative,
"only_show_overbooked": only_show_overbooked,
"show_listing": show_listing,
"show_all_rooms": show_all_rooms
}
get_csv = request.resolver_match.url_name == "eighth_admin_room_utilization_csv"
if show_listing or get_csv:
sched_acts = (EighthScheduledActivity.objects.exclude(activity__deleted=True))
# .exclude(cancelled=True) # include cancelled activities
if not one_block:
sched_acts = (sched_acts.filter(block__date__gte=start_block.date, block__date__lte=end_block.date))
else:
sched_acts = sched_acts.filter(block=start_block)
logger.debug("sched_acts before: {}".format(sched_acts.count()))
room_ids = request.GET.getlist("room")
if "room" in request.GET:
rooms = EighthRoom.objects.filter(id__in=room_ids)
sched_acts = sched_acts.filter(Q(rooms__in=rooms) | Q(activity__rooms__in=rooms))
logger.debug("sched_acts: {}".format(sched_acts.count()))
sched_acts = (sched_acts.order_by("block__date", "block__block_letter"))
if "room" in request.GET:
all_sched_acts = sched_acts
sched_acts = []
for sched_act in all_sched_acts:
if len(set(rooms).intersection(set(sched_act.get_true_rooms()))) > 0:
sched_acts.append(sched_act)
else:
rooms = all_rooms
logger.debug("sched_acts end: {}".format(len(sched_acts)))
sched_acts = sorted(sched_acts, key=lambda x: ("{}".format(x.block), "{}".format(x.get_true_rooms())))
context.update({"scheduled_activities": sched_acts, "rooms": rooms, "room_ids": [int(i) for i in room_ids]})
if get_csv:
response = http.HttpResponse(content_type="text/csv")
response["Content-Disposition"] = "attachment; filename=\"room_utilization.csv\""
writer = csv.writer(response)
title_row = []
for opt in show_opts:
if show[opt]:
title_row.append(opt.capitalize().replace("_", " "))
writer.writerow(title_row)
for sch_act in sched_acts:
row = []
if sch_act.activity.administrative and hide_administrative:
continue
if not sch_act.is_overbooked() and only_show_overbooked:
continue
if show["block"]:
row.append(sch_act.block)
if show["rooms"]:
row.append(";".join([rm.name for rm in sch_act.get_true_rooms()]))
if show["capacity"]:
row.append(sch_act.get_true_capacity())
if show["signups"]:
row.append(sch_act.members.count())
if show["aid"]:
row.append(sch_act.activity.aid)
if show["activity"]:
row.append(sch_act.activity)
if show["comments"]:
row.append(sch_act.comments)
if show["sponsors"]:
row.append(";".join([str(sp) for sp in sch_act.get_true_sponsors()]))
if show["admin_comments"]:
row.append(sch_act.admin_comments)
writer.writerow(row)
return response
return render(request, "eighth/admin/room_utilization.html", context)
0
Example 34
Project: logtacts Source File: views.py
@csrf_exempt
def sms(request):
if request.method == 'GET':
return HttpResponseRedirect('/')
if request.method == 'POST':
overall_start = time.time()
cache_key = request.POST.get('From')
co_number = request.POST.get('To')
message = request.POST.get('Body').strip()
if not cache_key:
raise Http404()
flow_state = cache.get(cache_key)
if flow_state:
if message.lower() == 'done':
cache.delete(cache_key)
return help_message()
if flow_state == QUERY_ACCOUNT:
if message.lower() in ('yes', 'yep'):
cache.set(cache_key, GET_EMAIL, CACHE_TIMEOUT)
return create_message(
"Ok, what's the email address on your account?",
to=cache_key, sender=co_number,
)
else:
cache.delete(cache_key)
return create_message(
"Ok! Please go to https://www.contactotter.com to create an account.",
to=cache_key, sender=co_number,
)
if flow_state == GET_EMAIL:
try:
# TODO: Send a confirmation email for connecting phone
user = User.objects.get(email=message.lower())
profile, _ = Profile.objects.get_or_create(user=user)
profile.phone_number = cache_key
profile.save()
cache.delete(cache_key)
return create_message(
"Ok! Your phone is connected to your account.",
to=cache_key, sender=co_number,
)
except User.DoesNotExist:
cache.delete(cache_key)
return create_message(
"We couldn't find an account for that email. Please go to https://www.contactotter.com to create one",
to=cache_key, sender=co_number,
)
user, book = get_user_objects_from_message(request.POST)
if not user or not book:
cache.set(cache_key, QUERY_ACCOUNT, CACHE_TIMEOUT)
return create_message(
"Hmm... I can't find an account with this number. Do you have a ContactOtter account?",
to=cache_key, sender=co_number,
)
if flow_state:
if flow_state.startswith('log'):
name = ':'.join(flow_state.split(':')[1:])
contacts = SearchQuerySet().filter(book=book.id).filter(
SQ(name=AutoQuery(name)) | SQ(content=AutoQuery(name))
)
if len(message) == 1 and len(contacts) > 0:
index = ascii_lowercase.index(message.lower())
contact = contacts[index].object
cache.delete(cache_key)
return log_contact(contact, user)
cache.delete(cache_key)
return create_message(
"Sorry, I didn't understand that.",
to=cache_key, sender=co_number,
)
if flow_state.startswith('find'):
name = ':'.join(flow_state.split(':')[1:])
contacts = SearchQuerySet().filter(book=book.id).filter(
SQ(name=AutoQuery(name)) | SQ(content=AutoQuery(name))
)
if len(message) == 1 and len(contacts) > 0:
index = ascii_lowercase.index(message.lower())
contact = contacts[index].object
cache.delete(cache_key)
return create_message(
get_contact_string(contact), to=cache_key, sender=co_number,
)
cache.delete(cache_key)
return create_message(
"Sorry, I didn't understand that.",
to=cache_key, sender=co_number,
)
tokens = message.split(' ')
if len(tokens) < 2:
return help_message()
search_start = time.time()
if tokens[0].lower() in MET_PREFIXES:
if tokens[1].lower() == 'with':
del tokens[1]
name = ' '.join(tokens[1:])
contacts = SearchQuerySet().filter(book=book.id).filter(
SQ(name=AutoQuery(name)) | SQ(content=AutoQuery(name))
)
if len(contacts) > 1:
cache.set(cache_key, "log:{}".format(name), CACHE_TIMEOUT)
response_string = "Which {} did you mean?\n".format(name)
response_string += get_string_from_search_contacts(contacts)
response_string += "(DONE to exit)"
return create_message(
response_string, to=cache_key, sender=co_number,
)
if len(contacts) == 1:
contact = contacts[0].object
else:
contact = Contact.objects.create(
book=book,
name=name,
)
cache.delete(cache_key)
return log_contact(contact, user)
if tokens[0].lower() == 'find':
name = ' '.join(tokens[1:])
contacts = SearchQuerySet().filter(book=book.id).filter(
SQ(name=AutoQuery(name)) | SQ(content=AutoQuery(name))
)
if len(contacts) == 0:
return create_message(
"Hmm... I didn't find any contacts.",
to=cache_key, sender=co_number,
)
if len(contacts) == 1:
return create_message(
get_contact_string(contacts[0].object),
to=cache_key, sender=co_number,
)
response_string = get_string_from_search_contacts(contacts)
if len(contacts) > 3:
response_string += "More: https://{}/search/?q={}".format(
Site.objects.get_current().domain,
name,
)
cache.set(cache_key, "find:{}".format(name), CACHE_TIMEOUT)
return create_message(
"Here's what I found for {}:\n{}".format(name, response_string),
to=cache_key, sender=co_number,
)
return help_message()
0
Example 35
@login_required
def search_view(request):
if not request.user.has_admin_permission("itemreg") and not request.user.is_teacher:
raise http.Http404
type = request.GET.get("type", "")
context = {
"calc_form": CalculatorRegistrationForm(request.GET) if type == "calculator" else CalculatorRegistrationForm(),
"comp_form": ComputerRegistrationForm(request.GET) if type == "computer" else ComputerRegistrationForm(),
"phone_form": PhoneRegistrationForm(request.GET) if type == "phone" else PhoneRegistrationForm()
}
results = {"calculator": None, "computer": None, "phone": None}
if type == "calculator":
cresults = CalculatorRegistration.objects.all()
logger.debug(cresults)
calc_serial = request.GET.get("calc_serial")
if calc_serial:
cresults = cresults.filter(calc_serial__icontains=calc_serial)
logger.debug(cresults)
calc_id = request.GET.get("calc_id")
if calc_id:
cresults = cresults.filter(calc_id__icontains=calc_id)
logger.debug(cresults)
calc_type = request.GET.get("calc_type")
if calc_type:
cresults = cresults.filter(calc_type=calc_type)
logger.debug(cresults)
results["calculator"] = cresults
elif type == "computer":
cresults = ComputerRegistration.objects.all()
logger.debug(cresults)
manufacturer = request.GET.get("manufacturer")
if manufacturer:
cresults = cresults.filter(manufacturer=manufacturer)
logger.debug(cresults)
model = request.GET.get("model")
if model:
cresults = cresults.filter(model__icontains=model)
logger.debug(cresults)
serial = request.GET.get("serial")
if serial:
cresults = cresults.filter(serial__icontains=serial)
logger.debug(cresults)
screen_size = request.GET.get("screen_size")
if screen_size:
cresults = cresults.filter(screen_size=screen_size)
logger.debug(cresults)
results["computer"] = cresults
elif type == "phone":
cresults = PhoneRegistration.objects.all()
logger.debug(cresults)
manufacturer = request.GET.get("manufacturer")
if manufacturer:
cresults = cresults.filter(manufacturer=manufacturer)
logger.debug(cresults)
model = request.GET.get("model")
if model:
cresults = cresults.filter(model__icontains=model)
logger.debug(cresults)
serial = request.GET.get("serial")
if serial:
cresults = cresults.filter(serial__icontains=serial)
logger.debug(cresults)
results["phone"] = cresults
elif type == "all":
results["calculator"] = CalculatorRegistration.objects.all()
results["computer"] = ComputerRegistration.objects.all()
results["phone"] = PhoneRegistration.objects.all()
quser = request.GET.get("user", None)
if quser:
try:
_st, search = get_search_results(quser)
except Exception:
search = []
logger.debug(search)
for i in results:
if results[i]:
results[i] = results[i].filter(user__in=search)
class NoneDict(dict):
def __getitem__(self, key):
return dict.get(self, key)
getargs = NoneDict(dict(request.GET))
context.update({
"type": type,
"results": results,
"no_results": sum([len(results[i]) if results[i] else 0 for i in results]) < 1,
"getargs": getargs
})
return render(request, "itemreg/search.html", context)
0
Example 36
Project: Django--an-app-at-a-time Source File: views.py
def get_context_data(self, **kwargs):
model_name = self.kwargs['model_name']
# Get the model class.
try:
app_config = apps.get_app_config(self.kwargs['app_label'])
except LookupError:
raise Http404(_("App %(app_label)r not found") % self.kwargs)
try:
model = app_config.get_model(model_name)
except LookupError:
raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % self.kwargs)
opts = model._meta
title, body, metadata = utils.parse_docstring(model.__doc__)
if title:
title = utils.parse_rst(title, 'model', _('model:') + model_name)
if body:
body = utils.parse_rst(body, 'model', _('model:') + model_name)
# Gather fields/field descriptions.
fields = []
for field in opts.fields:
# ForeignKey is a special case since the field will actually be a
# descriptor that returns the other object
if isinstance(field, models.ForeignKey):
data_type = field.rel.to.__name__
app_label = field.rel.to._meta.app_label
verbose = utils.parse_rst(
(_("the related `%(app_label)s.%(data_type)s` object") % {
'app_label': app_label, 'data_type': data_type,
}),
'model',
_('model:') + data_type,
)
else:
data_type = get_readable_field_data_type(field)
verbose = field.verbose_name
fields.append({
'name': field.name,
'data_type': data_type,
'verbose': verbose,
'help_text': field.help_text,
})
# Gather many-to-many fields.
for field in opts.many_to_many:
data_type = field.rel.to.__name__
app_label = field.rel.to._meta.app_label
verbose = _("related `%(app_label)s.%(object_name)s` objects") % {
'app_label': app_label,
'object_name': data_type,
}
fields.append({
'name': "%s.all" % field.name,
"data_type": 'List',
'verbose': utils.parse_rst(_("all %s") % verbose, 'model', _('model:') + opts.model_name),
})
fields.append({
'name': "%s.count" % field.name,
'data_type': 'Integer',
'verbose': utils.parse_rst(_("number of %s") % verbose, 'model', _('model:') + opts.model_name),
})
# Gather model methods.
for func_name, func in model.__dict__.items():
if (inspect.isfunction(func) and len(inspect.getargspec(func)[0]) == 1):
try:
for exclude in MODEL_METHODS_EXCLUDE:
if func_name.startswith(exclude):
raise StopIteration
except StopIteration:
continue
verbose = func.__doc__
if verbose:
verbose = utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.model_name)
fields.append({
'name': func_name,
'data_type': get_return_data_type(func_name),
'verbose': verbose,
})
# Gather related objects
for rel in opts.related_objects:
verbose = _("related `%(app_label)s.%(object_name)s` objects") % {
'app_label': rel.opts.app_label,
'object_name': rel.opts.object_name,
}
accessor = rel.get_accessor_name()
fields.append({
'name': "%s.all" % accessor,
'data_type': 'List',
'verbose': utils.parse_rst(_("all %s") % verbose, 'model', _('model:') + opts.model_name),
})
fields.append({
'name': "%s.count" % accessor,
'data_type': 'Integer',
'verbose': utils.parse_rst(_("number of %s") % verbose, 'model', _('model:') + opts.model_name),
})
kwargs.update({
'name': '%s.%s' % (opts.app_label, opts.object_name),
'summary': title,
'description': body,
'fields': fields,
})
return super(ModelDetailView, self).get_context_data(**kwargs)
0
Example 37
Project: wagtail Source File: sendfile.py
def sendfile(request, filename, attachment=False, attachment_filename=None, mimetype=None, encoding=None, backend=None):
'''
create a response to send file using backend configured in SENDFILE_BACKEND
If attachment is True the content-disposition header will be set.
This will typically prompt the user to download the file, rather
than view it. The content-disposition filename depends on the
value of attachment_filename:
None (default): Same as filename
False: No content-disposition filename
String: Value used as filename
If no mimetype or encoding are specified, then they will be guessed via the
filename (using the standard python mimetypes module)
'''
_sendfile = backend or _get_sendfile()
if not os.path.exists(filename):
from django.http import Http404
raise Http404('"%s" does not exist' % filename)
guessed_mimetype, guessed_encoding = guess_type(filename)
if mimetype is None:
if guessed_mimetype:
mimetype = guessed_mimetype
else:
mimetype = 'application/octet-stream'
response = _sendfile(request, filename, mimetype=mimetype)
if attachment:
if attachment_filename is None:
attachment_filename = os.path.basename(filename)
parts = ['attachment']
if attachment_filename:
from unidecode import unidecode
try:
from django.utils.encoding import force_text
except ImportError:
# Django 1.3
from django.utils.encoding import force_unicode as force_text
attachment_filename = force_text(attachment_filename)
ascii_filename = unidecode(attachment_filename)
parts.append('filename="%s"' % ascii_filename)
if ascii_filename != attachment_filename:
from django.utils.http import urlquote
quoted_filename = urlquote(attachment_filename)
parts.append('filename*=UTF-8\'\'%s' % quoted_filename)
response['Content-Disposition'] = '; '.join(parts)
response['Content-length'] = os.path.getsize(filename)
response['Content-Type'] = mimetype
if not encoding:
encoding = guessed_encoding
if encoding:
response['Content-Encoding'] = encoding
return response
0
Example 38
def shortcut(request, content_type_id, object_id):
"""
Redirect to an object's page based on a content-type ID and an object ID.
"""
# Look up the object, making sure it's got a get_absolute_url() function.
try:
content_type = ContentType.objects.get(pk=content_type_id)
if not content_type.model_class():
raise http.Http404(_("Content type %(ct_id)s object has no associated model") %
{'ct_id': content_type_id})
obj = content_type.get_object_for_this_type(pk=object_id)
except (ObjectDoesNotExist, ValueError):
raise http.Http404(_("Content type %(ct_id)s object %(obj_id)s doesn't exist") %
{'ct_id': content_type_id, 'obj_id': object_id})
try:
get_absolute_url = obj.get_absolute_url
except AttributeError:
raise http.Http404(_("%(ct_name)s objects don't have a get_absolute_url() method") %
{'ct_name': content_type.name})
absurl = get_absolute_url()
# Try to figure out the object's domain, so we can do a cross-site redirect
# if necessary.
# If the object actually defines a domain, we're done.
if absurl.startswith(('http://', 'https://', '//')):
return http.HttpResponseRedirect(absurl)
# Otherwise, we need to introspect the object's relationships for a
# relation to the Site object
object_domain = None
if apps.is_installed('django.contrib.sites'):
Site = apps.get_model('sites.Site')
opts = obj._meta
# First, look for an many-to-many relationship to Site.
for field in opts.many_to_many:
if field.rel.to is Site:
try:
# Caveat: In the case of multiple related Sites, this just
# selects the *first* one, which is arbitrary.
object_domain = getattr(obj, field.name).all()[0].domain
except IndexError:
pass
if object_domain is not None:
break
# Next, look for a many-to-one relationship to Site.
if object_domain is None:
for field in obj._meta.fields:
if field.rel and field.rel.to is Site:
try:
object_domain = getattr(obj, field.name).domain
except Site.DoesNotExist:
pass
if object_domain is not None:
break
# Fall back to the current site (if possible).
if object_domain is None:
try:
object_domain = Site.objects.get_current().domain
except Site.DoesNotExist:
pass
else:
# Fall back to the current request's site.
object_domain = RequestSite(request).domain
# If all that malarkey found an object domain, use it. Otherwise, fall back
# to whatever get_absolute_url() returned.
if object_domain is not None:
protocol = request.scheme
return http.HttpResponseRedirect('%s://%s%s'
% (protocol, object_domain, absurl))
else:
return http.HttpResponseRedirect(absurl)
0
Example 39
Project: treeio Source File: views.py
@treeio_login_required
def ajax_upload(request, object_id=None, record=None):
try:
object = None
if request.method == "POST":
if request.is_ajax():
# the file is stored raw in the request
upload = request
is_raw = True
# AJAX Upload will pass the filename in the querystring if it
# is the "advanced" ajax upload
try:
filename = request.GET['qqfile']
content_type = "application/octet-stream"
except KeyError:
return HttpResponseBadRequest("AJAX request not valid")
# not an ajax upload, so it was the "basic" iframe version with
# submission via form
else:
is_raw = False
if len(request.FILES) == 1:
# FILES is a dictionary in Django but Ajax Upload gives the uploaded file an
# ID based on a random number, so it cannot be guessed here in the code.
# Rather than editing Ajax Upload to pass the ID in the querystring,
# observer that each upload is a separate request,
# so FILES should only have one entry.
# Thus, we can just grab the first (and only) value in the
# dict.
upload = request.FILES.values()[0]
content_type = upload.content_type
else:
raise Http404("Bad Upload")
filename = upload.name
random.seed()
filehash = str(random.getrandbits(128))
savefile = join(
getattr(settings, 'MEDIA_ROOT'), 'attachments', filehash)
# save the file
success = save_upload(upload, savefile, is_raw)
attachment = Attachment(filename=filename,
content_type=content_type,
uploaded_by=request.user.profile,
attached_file=filehash)
if record:
attachment.attached_record = record
about = record.about.all()
if about.count():
attachment.attached_object = about[0]
object = attachment.attached_object
else:
object = Object.objects.get(id=object_id)
attachment.attached_object = object
attachment.save()
if object:
object.set_last_updated()
# TODO: smart markup and return as string, and object id, different
# classnames,id or attribute for update records and objects
if success:
ret_json = {'success': success,
'object_id': object.id if object else None,
'update_id': record.id if record else None}
else:
ret_json = {'success': False,
'object_id': None,
'update_id': None}
return HttpResponse(json.dumps(ret_json))
except:
pass
0
Example 40
Project: Django--an-app-at-a-time Source File: base.py
def get_response(self, request):
"Returns an HttpResponse object for the given HttpRequest"
# Setup default url resolver for this thread, this code is outside
# the try/except so we don't get a spurious "unbound local
# variable" exception in the event an exception is raised before
# resolver is set
urlconf = settings.ROOT_URLCONF
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
try:
response = None
# Apply request middleware
for middleware_method in self._request_middleware:
response = middleware_method(request)
if response:
break
if response is None:
if hasattr(request, 'urlconf'):
# Reset url resolver with a custom urlconf.
urlconf = request.urlconf
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
resolver_match = resolver.resolve(request.path_info)
callback, callback_args, callback_kwargs = resolver_match
request.resolver_match = resolver_match
# Apply view middleware
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
break
if response is None:
wrapped_callback = self.make_view_atomic(callback)
try:
response = wrapped_callback(request, *callback_args, **callback_kwargs)
except Exception as e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
if response:
break
if response is None:
raise
# Complain if the view returned None (a common error).
if response is None:
if isinstance(callback, types.FunctionType): # FBV
view_name = callback.__name__
else: # CBV
view_name = callback.__class__.__name__ + '.__call__'
raise ValueError("The view %s.%s didn't return an HttpResponse object. It returned None instead."
% (callback.__module__, view_name))
# If the response supports deferred rendering, apply template
# response middleware and then render the response
if hasattr(response, 'render') and callable(response.render):
for middleware_method in self._template_response_middleware:
response = middleware_method(request, response)
# Complain if the template response middleware returned None (a common error).
if response is None:
raise ValueError(
"%s.process_template_response didn't return an "
"HttpResponse object. It returned None instead."
% (middleware_method.__self__.__class__.__name__))
response = response.render()
except http.Http404 as e:
logger.warning('Not Found: %s', request.path,
extra={
'status_code': 404,
'request': request
})
if settings.DEBUG:
response = debug.technical_404_response(request, e)
else:
response = self.get_exception_response(request, resolver, 404)
except PermissionDenied:
logger.warning(
'Forbidden (Permission denied): %s', request.path,
extra={
'status_code': 403,
'request': request
})
response = self.get_exception_response(request, resolver, 403)
except MultiPartParserError:
logger.warning(
'Bad request (Unable to parse request body): %s', request.path,
extra={
'status_code': 400,
'request': request
})
response = self.get_exception_response(request, resolver, 400)
except SuspiciousOperation as e:
# The request logger receives events for any problematic request
# The security logger receives events for all SuspiciousOperations
security_logger = logging.getLogger('django.security.%s' %
e.__class__.__name__)
security_logger.error(
force_text(e),
extra={
'status_code': 400,
'request': request
})
if settings.DEBUG:
return debug.technical_500_response(request, *sys.exc_info(), status_code=400)
response = self.get_exception_response(request, resolver, 400)
except SystemExit:
# Allow sys.exit() to actually exit. See tickets #1023 and #4701
raise
except: # Handle everything else.
# Get the exception info now, in case another exception is thrown later.
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
try:
# Apply response middleware, regardless of the response
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
# Complain if the response middleware returned None (a common error).
if response is None:
raise ValueError(
"%s.process_response didn't return an "
"HttpResponse object. It returned None instead."
% (middleware_method.__self__.__class__.__name__))
response = self.apply_response_fixes(request, response)
except: # Any exception should be gathered and handled
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
response._closable_objects.append(request)
return response
0
Example 41
Project: django-shorturls Source File: views.py
def redirect(request, prefix, tiny, converter=default_converter):
"""
Redirect to a given object from a short URL.
"""
# Resolve the prefix and encoded ID into a model object and decoded ID.
# Many things here could go wrong -- bad prefix, bad value in
# SHORTEN_MODELS, no such model, bad encoding -- so just return a 404 if
# any of that stuff goes wrong.
try:
app_label, model_name = settings.SHORTEN_MODELS[prefix].split('.')
except KeyError:
raise Http404('Bad prefix.')
try:
model = models.get_model(app_label, model_name)
except LookupError:
model = False
if not model:
raise Http404('Bad model specified in SHORTEN_MODELS.')
try:
id = converter.to_decimal(tiny)
except ValueError:
raise Http404('Bad encoded ID.')
# Try to look up the object. If it's not a valid object, or if it doesn't
# have an absolute url, bail again.
obj = get_object_or_404(model, pk=id)
try:
url = obj.get_absolute_url()
except AttributeError:
raise Http404("'%s' models don't have a get_absolute_url() method." % model.__name__)
# We might have to translate the URL -- the badly-named get_absolute_url
# actually returns a domain-relative URL -- into a fully qualified one.
# If we got a fully-qualified URL, sweet.
if urlparse.urlsplit(url)[0]:
return HttpResponsePermanentRedirect(url)
# Otherwise, we need to make a full URL by prepending a base URL.
# First, look for an explicit setting.
if hasattr(settings, 'SHORTEN_FULL_BASE_URL') and settings.SHORTEN_FULL_BASE_URL:
base = settings.SHORTEN_FULL_BASE_URL
# Next, if the sites app is enabled, redirect to the current site.
elif Site._meta.installed:
base = 'http://%s/' % Site.objects.get_current().domain
# Finally, fall back on the current request.
else:
base = 'http://%s/' % RequestSite(request).domain
return HttpResponsePermanentRedirect(urlparse.urljoin(base, url))
0
Example 42
Project: talk.org Source File: main.py
def change_stage(request, app_label, model_name, object_id):
model = models.get_model(app_label, model_name)
object_id = unquote(object_id)
if model is None:
raise Http404("App %r, model %r, not found" % (app_label, model_name))
opts = model._meta
if not request.user.has_perm(app_label + '.' + opts.get_change_permission()):
raise PermissionDenied
if request.POST and "_saveasnew" in request.POST:
return add_stage(request, app_label, model_name, form_url='../../add/')
try:
manipulator = model.ChangeManipulator(object_id)
except model.DoesNotExist:
raise Http404('%s object with primary key %r does not exist' % (model_name, escape(object_id)))
if request.POST:
new_data = request.POST.copy()
if opts.has_field_type(models.FileField):
new_data.update(request.FILES)
errors = manipulator.get_validation_errors(new_data)
manipulator.do_html2python(new_data)
if not errors:
new_object = manipulator.save(new_data)
pk_value = new_object._get_pk_val()
# Construct the change message.
change_message = []
if manipulator.fields_added:
change_message.append(_('Added %s.') % get_text_list(manipulator.fields_added, _('and')))
if manipulator.fields_changed:
change_message.append(_('Changed %s.') % get_text_list(manipulator.fields_changed, _('and')))
if manipulator.fields_deleted:
change_message.append(_('Deleted %s.') % get_text_list(manipulator.fields_deleted, _('and')))
change_message = ' '.join(change_message)
if not change_message:
change_message = _('No fields changed.')
LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, force_unicode(new_object), CHANGE, change_message)
msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(new_object)}
if "_continue" in request.POST:
request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
if '_popup' in request.REQUEST:
return HttpResponseRedirect(request.path + "?_popup=1")
else:
return HttpResponseRedirect(request.path)
elif "_saveasnew" in request.POST:
request.user.message_set.create(message=_('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(new_object)})
return HttpResponseRedirect("../%s/" % pk_value)
elif "_addanother" in request.POST:
request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
return HttpResponseRedirect("../add/")
else:
request.user.message_set.create(message=msg)
return HttpResponseRedirect("../")
else:
# Populate new_data with a "flattened" version of the current data.
new_data = manipulator.flatten_data()
# TODO: do this in flatten_data...
# If the object has ordered objects on its admin page, get the existing
# order and flatten it into a comma-separated list of IDs.
id_order_list = []
for rel_obj in opts.get_ordered_objects():
id_order_list.extend(getattr(manipulator.original_object, 'get_%s_order' % rel_obj.object_name.lower())())
if id_order_list:
new_data['order_'] = ','.join(map(str, id_order_list))
errors = {}
# Populate the FormWrapper.
form = oldforms.FormWrapper(manipulator, new_data, errors)
form.original = manipulator.original_object
form.order_objects = []
#TODO Should be done in flatten_data / FormWrapper construction
for related in opts.get_followed_related_objects():
wrt = related.opts.order_with_respect_to
if wrt and wrt.rel and wrt.rel.to == opts:
func = getattr(manipulator.original_object, 'get_%s_list' %
related.get_accessor_name())
orig_list = func()
form.order_objects.extend(orig_list)
c = template.RequestContext(request, {
'title': _('Change %s') % force_unicode(opts.verbose_name),
'form': form,
'object_id': object_id,
'original': manipulator.original_object,
'is_popup': '_popup' in request.REQUEST,
})
return render_change_form(model, manipulator, c, change=True)
0
Example 43
Project: zulip Source File: runtornado.py
def get_response(self, request):
# type: (HttpRequest) -> HttpResponse
"Returns an HttpResponse object for the given HttpRequest"
try:
try:
# Setup default url resolver for this thread.
urlconf = settings.ROOT_URLCONF
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
response = None
# Apply request middleware
for middleware_method in self._request_middleware:
response = middleware_method(request)
if response:
break
if hasattr(request, "urlconf"):
# Reset url resolver with a custom urlconf.
urlconf = request.urlconf
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
### ADDED BY ZULIP
request._resolver = resolver
### END ADDED BY ZULIP
callback, callback_args, callback_kwargs = resolver.resolve(
request.path_info)
# Apply view middleware
if response is None:
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
break
### THIS BLOCK MODIFIED BY ZULIP
if response is None:
from ...decorator import RespondAsynchronously
try:
response = callback(request, *callback_args, **callback_kwargs)
if response is RespondAsynchronously:
async_request_stop(request)
return None
clear_handler_by_id(self.handler_id)
except Exception as e:
clear_handler_by_id(self.handler_id)
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
if response:
break
if response is None:
raise
if response is None:
try:
view_name = callback.__name__
except AttributeError:
view_name = callback.__class__.__name__ + '.__call__'
raise ValueError("The view %s.%s returned None." %
(callback.__module__, view_name))
# If the response supports deferred rendering, apply template
# response middleware and the render the response
if hasattr(response, 'render') and callable(response.render):
for middleware_method in self._template_response_middleware:
response = middleware_method(request, response)
response = response.render()
except http.Http404 as e:
if settings.DEBUG:
from django.views import debug
response = debug.technical_404_response(request, e)
else:
try:
callback, param_dict = resolver.resolve404()
response = callback(request, **param_dict)
except:
try:
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
finally:
signals.got_request_exception.send(sender=self.__class__, request=request)
except exceptions.PermissionDenied:
logging.warning(
'Forbidden (Permission denied): %s', request.path,
extra={
'status_code': 403,
'request': request
})
try:
callback, param_dict = resolver.resolve403()
response = callback(request, **param_dict)
except:
try:
response = self.handle_uncaught_exception(request,
resolver, sys.exc_info())
finally:
signals.got_request_exception.send(
sender=self.__class__, request=request)
except SystemExit:
# See https://code.djangoproject.com/ticket/4701
raise
except Exception as e:
exc_info = sys.exc_info()
signals.got_request_exception.send(sender=self.__class__, request=request)
return self.handle_uncaught_exception(request, resolver, exc_info)
finally:
# Reset urlconf on the way out for isolation
urlresolvers.set_urlconf(None)
### ZULIP CHANGE: The remainder of this function was moved
### into its own function, just below, so we can call it from
### finish().
response = self.apply_response_middleware(request, response, resolver)
return response
0
Example 44
Project: dpaste Source File: views.py
def snippet_details(request, snippet_id, template_name='dpaste/snippet_details.html', is_raw=False):
"""
Details list view of a snippet. Handles the actual view, reply and
tree/diff view.
"""
snippet = get_object_or_404(Snippet, secret_id=snippet_id)
# One-Time snippet get deleted if the view count matches our limit
if snippet.expire_type == Snippet.EXPIRE_ONETIME \
and snippet.view_count >= ONETIME_LIMIT:
snippet.delete()
raise Http404()
# Increase the view count of the snippet
snippet.view_count += 1
snippet.save()
tree = snippet.get_root()
tree = tree.get_descendants(include_self=True)
new_snippet_initial = {
'content': snippet.content,
'lexer': snippet.lexer,
}
if request.method == "POST":
snippet_form = SnippetForm(
data=request.POST,
request=request,
initial=new_snippet_initial)
if snippet_form.is_valid():
new_snippet = snippet_form.save(parent=snippet)
url = new_snippet.get_absolute_url()
return HttpResponseRedirect(url)
else:
snippet_form = SnippetForm(
initial=new_snippet_initial,
request=request)
template_context = {
'snippet_form': snippet_form,
'snippet': snippet,
'lexers': LEXER_LIST,
'lines': range(snippet.get_linecount()),
'tree': tree,
'wordwrap': snippet.lexer in LEXER_WORDWRAP and 'True' or 'False',
'gist': getattr(settings, 'DPASTE_ENABLE_GIST', True),
}
response = render(request, template_name, template_context)
if is_raw:
response['Content-Type'] = 'text/plain;charset=UTF-8'
response['X-Content-Type-Options'] = 'nosniff'
return response
else:
return response
0
Example 45
Project: pycon Source File: views.py
@login_required
def proposal_speaker_manage(request, pk):
queryset = ProposalBase.objects.select_related("speaker")
proposal = get_object_or_404(queryset, pk=pk)
proposal = ProposalBase.objects.get_subclass(pk=proposal.pk)
if proposal.speaker != request.user.speaker_profile:
raise Http404()
if request.method == "POST":
add_speaker_form = AddSpeakerForm(request.POST, proposal=proposal)
if add_speaker_form.is_valid():
message_ctx = {
"proposal": proposal,
}
def create_speaker_token(email_address):
# create token and look for an existing speaker to prevent
# duplicate tokens and confusing the pending speaker
try:
pending = Speaker.objects.get(
Q(invite_email=email_address)
)
except Speaker.DoesNotExist:
salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
token = hashlib.sha1(salt + email_address).hexdigest()
pending = Speaker.objects.create(
invite_email=email_address,
invite_token=token,
)
else:
token = pending.invite_token
return pending, token
email_address = add_speaker_form.cleaned_data["email"]
# django-selectable widget will return a User for emails that are
# associated with a current User, else a string
if isinstance(email_address, User):
email_address = email_address.email
# check if email is on the site now
users = EmailAddress.objects.get_users_for(email_address)
if users:
# should only be one since we enforce unique email
user = users[0]
message_ctx["user"] = user
# look for speaker profile
try:
speaker = user.speaker_profile
except ObjectDoesNotExist:
speaker, token = create_speaker_token(email_address)
message_ctx["token"] = token
# fire off email to user to create profile
send_email(
[email_address], "speaker_no_profile",
context = message_ctx
)
else:
# fire off email to user letting them they are loved.
send_email(
[email_address], "speaker_addition",
context = message_ctx
)
else:
speaker, token = create_speaker_token(email_address)
message_ctx["token"] = token
# fire off email letting user know about site and to create
# account and speaker profile
send_email(
[email_address], "speaker_invite",
context = message_ctx
)
invitation, created = AdditionalSpeaker.objects.get_or_create(proposalbase=proposal.proposalbase_ptr, speaker=speaker)
messages.success(request, "Speaker invited to proposal.")
return redirect("proposal_speaker_manage", proposal.pk)
else:
add_speaker_form = AddSpeakerForm(proposal=proposal)
ctx = {
"proposal": proposal,
"speakers": proposal.speakers(),
"add_speaker_form": add_speaker_form,
}
return render(request, "proposals/proposal_speaker_manage.html", ctx)
0
Example 46
Project: jaikuenginepatch Source File: views.py
@alternate_nick
def actor_item(request, nick=None, item=None, format='html'):
# The nick passed in the url looks ugly with the escaped @ in it and is
# generally just shorter if we only use the lead part of the nick
# however the entire system expects full nicks so we should expand this
# as soon as possible
nick = clean.nick(nick)
# Most pages have the concept of a viewer and an actor being viewed,
# in all cases the viewer is `request.user` and the actor being viewed
# should be named `view`
view = api.actor_lookup_nick(request.user, nick)
if not view:
raise exception.UserDoesNotExistError(nick, request.user)
# With very few exceptions, whenever we are referring to a an
# instance that is an entity from the datastore we append `_ref`
# to the variable name to distinguish it from the variable that
# is simply a string identifier.
# In the code below `stream_ref` and `entry_ref` are both entity
# references, while `entry` is simply the string key_name of an entry
stream_ref = api.stream_get_presence(request.user, view.nick)
if not stream_ref:
raise http.Http404()
if item == 'last':
entry_ref = api.entry_get_last(request.user, stream_ref.keyname())
return http.HttpResponseRedirect(entry_ref.url())
else:
entry = '%s/%s' % (stream_ref.key().name(), item)
entry_ref = api.entry_get_safe(request.user, entry)
# Most api calls will return None if the entity being looked up does
# not exist so we usually want to verify the return values
if not entry_ref:
raise http.Http404()
# When handling user actions the following pattern more or less applies
# if 'parameter_unique_to_action' in request.(POST|GET|REQUEST):
# try:
# validate.nonce(request, 'nonce_action')
# validate.anything_else_that_is_related_to_ui_rather_than_call()
#
# local_variable = request.(POST|GET|REQUEST).get('request_arg')
# # or
# params = util.query_dict_to_keywords(request.(POST|GET|REQUEST))
#
# # Our goal is to have most of the logic for any action translate
# # directly into an api call on behalf of the requesting user
# # such that the api call is responsible for validating all input
# # and raising any applicable errors
# result = api.some_api_method(request.user,
# method_variable=local_variable,
# ...)
# # or
# result = api.some_api_method(request.user, **params)
#
# # All actions should issue a redirect with a success message
# return util.RedirectFlash('some_url', 'some success message')
# except:
# exception.handle_exception(request)
#
# When an exception occurs we expect the rest of the page to be able
# to be processed normally as if no action had been taken, the error
# handling section of the template should display the errors caught
# by the exception.handle_exception() call
handled = common_views.handle_view_action(
request,
{'entry_add_comment': entry_ref.url(request=request),
'entry_remove': view.url(request=request),
'entry_remove_comment': entry_ref.url(request=request),
'entry_mark_as_spam': entry_ref.url(request=request)
}
)
if handled:
return handled
comments = api.entry_get_comments(request.user, entry_ref.key().name())
# To minimize the number of lookups to the datastore once we know
# all the data we will be displaying on a page we attempt to make
# a list of all the actors associated with that data so that we can
# fetch them all at once
actor_nicks = [entry_ref.owner, entry_ref.actor] + [c.actor for c in comments]
actors = api.actor_get_actors(request.user, actor_nicks)
# Creates a copy of actors with lowercase keys (Django #6904: template filter
# dictsort sorts case sensitive), excluding the currently logged in user.
participants = {}
for k, v in actors.iteritems():
if (v and
not (hasattr(request.user, 'nick') and request.user.nick == v.nick)):
participants[k.lower()] = v
# Due to restrictions on Django's templating language most of the time
# we will have to take an additional step of preparing all of our data
# for display, this usually translates to attaching references to
# actor or stream entities.
# Functions that handle this preparation should be added to the
# common.display module
entry = display.prep_entry(entry_ref,
{stream_ref.key().name(): stream_ref}, actors)
comments = display.prep_comment_list(comments, actors)
# Additionally, to minimize more logic in the templates some variables
# can be defined to configure the output, these are usually template specific
# though some are common variables for anything that inherits from the
# base templates
green_top = True
sidebar_green_top = True
# The quickest way to make sure we are getting all of the things we care
# about passed to the template without the temptation of making last minute
# changes is just to pass `locals()` to the template context
c = template.RequestContext(request, locals())
# Ideally this is all that should be necessary to add additional output
# formats, in practice it is yet to be seen whether additional data
# preparation will be necessary before outputting in JSON or ATOM formats
if format == 'html':
# We always use the full path to the template to prevent naming conflicts
# and difficult searches.
t = loader.get_template('item.html')
return http.HttpResponse(t.render(c))
elif format == 'json':
t = loader.get_template('item.json')
r = http.HttpResponse(t.render(c))
r['Content-type'] = 'text/javascript'
return r
0
Example 47
Project: talk.org Source File: base.py
def get_response(self, request):
"Returns an HttpResponse object for the given HttpRequest"
from django.core import exceptions, urlresolvers
from django.core.mail import mail_admins
from django.conf import settings
# Apply request middleware
for middleware_method in self._request_middleware:
response = middleware_method(request)
if response:
return response
# Get urlconf from request object, if available. Otherwise use default.
urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
try:
callback, callback_args, callback_kwargs = resolver.resolve(request.path)
# Apply view middleware
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
return response
try:
response = callback(request, *callback_args, **callback_kwargs)
except Exception, e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
if response:
return response
raise
# Complain if the view returned None (a common error).
if response is None:
try:
view_name = callback.func_name # If it's a function
except AttributeError:
view_name = callback.__class__.__name__ + '.__call__' # If it's a class
raise ValueError, "The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)
return response
except http.Http404, e:
if settings.DEBUG:
from django.views import debug
return debug.technical_404_response(request, e)
else:
callback, param_dict = resolver.resolve404()
return callback(request, **param_dict)
except exceptions.PermissionDenied:
return http.HttpResponseForbidden('<h1>Permission denied</h1>')
except SystemExit:
# Allow sys.exit() to actually exit. See tickets #1023 and #4701
raise
except: # Handle everything else, including SuspiciousOperation, etc.
# Get the exception info now, in case another exception is thrown later.
exc_info = sys.exc_info()
receivers = dispatcher.send(signal=signals.got_request_exception, request=request)
if settings.DEBUG:
from django.views import debug
return debug.technical_500_response(request, *exc_info)
else:
# When DEBUG is False, send an error message to the admins.
subject = 'Error (%s IP): %s' % ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path)
try:
request_repr = repr(request)
except:
request_repr = "Request repr() unavailable"
message = "%s\n\n%s" % (self._get_traceback(exc_info), request_repr)
mail_admins(subject, message, fail_silently=True)
# Return an HttpResponse that displays a friendly error message.
callback, param_dict = resolver.resolve500()
return callback(request, **param_dict)
0
Example 48
Project: pretix Source File: middleware.py
def process_request(self, request):
url = resolve(request.path_info)
url_name = url.url_name
if not request.path.startswith(get_script_prefix() + 'control'):
# This middleware should only touch the /control subpath
return
if hasattr(request, 'organizer'):
# If the user is on a organizer's subdomain, he should be redirected to pretix
return redirect(urljoin(settings.SITE_URL, request.get_full_path()))
if url_name in self.EXCEPTIONS:
return
if not request.user.is_authenticated:
# Taken from django/contrib/auth/decorators.py
path = request.build_absolute_uri()
# urlparse chokes on lazy objects in Python 3, force to str
resolved_login_url = force_str(
resolve_url(settings.LOGIN_URL_CONTROL))
# If the login url is the same scheme and net location then just
# use the path as the "next" url.
login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
current_scheme, current_netloc = urlparse(path)[:2]
if ((not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(
path, resolved_login_url, REDIRECT_FIELD_NAME)
request.user.events_cache = request.user.events.order_by(
"organizer", "date_from").prefetch_related("organizer")
if 'event' in url.kwargs and 'organizer' in url.kwargs:
try:
request.event = Event.objects.filter(
slug=url.kwargs['event'],
permitted__id__exact=request.user.id,
organizer__slug=url.kwargs['organizer'],
).select_related('organizer')[0]
request.eventperm = EventPermission.objects.get(
event=request.event,
user=request.user
)
request.organizer = request.event.organizer
except IndexError:
raise Http404(_("The selected event was not found or you "
"have no permission to administrate it."))
elif 'organizer' in url.kwargs:
try:
request.organizer = Organizer.objects.filter(
slug=url.kwargs['organizer'],
permitted__id__exact=request.user.id,
)[0]
except IndexError:
raise Http404(_("The selected organizer was not found or you "
"have no permission to administrate it."))
0
Example 49
Project: django-modelclone Source File: admin.py
def clone_view(self, request, object_id, form_url='', extra_context=None):
opts = self.model._meta
if not self.has_add_permission(request):
raise PermissionDenied
original_obj = self.get_object(request, unquote(object_id))
if original_obj is None:
raise Http404(_('{name} object with primary key {key} does not exist.'.format(
name=force_text(opts.verbose_name),
key=repr(escape(object_id))
)))
ModelForm = self.get_form(request)
formsets = []
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES)
if form.is_valid():
new_object = self.save_form(request, form, change=False)
form_validated = True
else:
new_object = self.model()
form_validated = False
prefixes = {}
for FormSet, inline in self.get_formsets_with_inlines(request):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(data=request.POST, files=request.FILES,
instance=new_object,
save_as_new="_saveasnew" in request.POST, # ????
prefix=prefix)
formsets.append(formset)
if all_valid(formsets) and form_validated:
# if original model has any file field, save new model
# with same paths to these files
for name in vars(original_obj):
field = getattr(original_obj, name)
if isinstance(field, FieldFile) and name not in request.FILES:
setattr(new_object, name, field)
self.save_model(request, new_object, form, False)
self.save_related(request, form, formsets, False)
try:
self.log_addition(request, new_object)
except TypeError:
# In Django 1.9 we need one more param
self.log_addition(request, new_object, "Cloned object")
return self.response_add(request, new_object, None)
else:
initial = model_to_dict(original_obj)
initial = self.tweak_cloned_fields(initial)
form = ModelForm(initial=initial)
prefixes = {}
for FormSet, inline in self.get_formsets_with_inlines(request):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
initial = []
queryset = inline.get_queryset(request).filter(
**{FormSet.fk.name: original_obj})
for obj in queryset:
initial.append(model_to_dict(obj, exclude=[obj._meta.pk.name,
FormSet.fk.name]))
initial = self.tweak_cloned_inline_fields(prefix, initial)
formset = FormSet(prefix=prefix, initial=initial)
# Since there is no way to customize the `extra` in the constructor,
# construct the forms again...
# most of this view is a hack, but this is the ugliest one
formset.extra = len(initial) + formset.extra
# _construct_forms() was removed on django 1.6
# see https://github.com/django/django/commit/ef79582e8630cb3c119caed52130c9671188addd
if hasattr(formset, '_construct_forms'):
formset._construct_forms()
formsets.append(formset)
admin_form = helpers.AdminForm(
form,
list(self.get_fieldsets(request)),
self.get_prepopulated_fields(request),
self.get_readonly_fields(request),
model_admin=self
)
media = self.media + admin_form.media
inline_admin_formsets = []
for inline, formset in zip(self.get_inline_instances(request), formsets):
fieldsets = list(inline.get_fieldsets(request, original_obj))
readonly = list(inline.get_readonly_fields(request, original_obj))
prepopulated = dict(inline.get_prepopulated_fields(request, original_obj))
inline_admin_formset = InlineAdminFormSetFakeOriginal(inline, formset,
fieldsets, prepopulated, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
title = u'{0} {1}'.format(self.clone_verbose_name, opts.verbose_name)
context = {
'title': title,
'original': title,
'adminform': admin_form,
'is_popup': "_popup" in getattr(request, 'REQUEST', request.GET),
'show_delete': False,
'media': media,
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'app_label': opts.app_label,
}
context.update(extra_context or {})
return self.render_change_form(request,
context,
form_url=form_url,
change=False
)
0
Example 50
Project: tendenci Source File: views.py
def plugin_static_serve(request, plugin, path, show_indexes=False):
"""
Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
(r'^(?P<path>.*)$', 'django.views.static.serve', {'docuement_root' : '/path/to/my/files/'})
in your URLconf. You must provide the ``docuement_root`` param. You may
also set ``show_indexes`` to ``True`` if you'd like to serve a basic index
of the directory. This index view will use the template hardcoded below,
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
import mimetypes
import os
import posixpath
import stat
import urllib
from email.Utils import parsedate_tz, mktime_tz
from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseNotModified
from django.utils.http import http_date
from django.views.static import was_modified_since, directory_index
from django.conf import settings
docuement_root = os.path.join(settings.PROJECT_ROOT,'plugins',plugin,'media')
# Clean up given path to only allow serving files below docuement_root.
path = posixpath.normpath(urllib.unquote(path))
path = path.lstrip('/')
newpath = ''
for part in path.split('/'):
if not part:
# Strip empty path components.
continue
drive, part = os.path.splitdrive(part)
head, part = os.path.split(part)
if part in (os.curdir, os.pardir):
# Strip '.' and '..' in path.
continue
newpath = os.path.join(newpath, part).replace('\\', '/')
if newpath and path != newpath:
return HttpResponseRedirect(newpath)
fullpath = os.path.join(docuement_root, newpath)
if os.path.isdir(fullpath):
if show_indexes:
return directory_index(newpath, fullpath)
raise Http404(_("Directory indexes are not allowed here."))
if not os.path.exists(fullpath):
raise Http404('"%s" does not exist' % fullpath)
# Respect the If-Modified-Since header.
statobj = os.stat(fullpath)
mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream'
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
return HttpResponseNotModified(content_type=mimetype)
contents = open(fullpath, 'rb').read()
response = HttpResponse(contents, content_type=mimetype)
response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
response["Content-Length"] = len(contents)
return response