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 = timezone.now() if isinstance(model._meta.get_field(date_field), DateTimeField): lookup_kwargs = {'%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max))} 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
def auth_processor_no_attr_access(request): r1 = render_to_response( 'context_processors/auth_attrs_no_access.html', RequestContext(request, {}, processors=[context_processors.auth])) # *After* rendering, we check whether the session was accessed return render_to_response('context_processors/auth_attrs_test_access.html', {'session_accessed': request.session.accessed})
def template_filter_index(request): if not utils.docutils_is_available: return missing_docutils_page(request) load_all_installed_template_libraries() filters = [] app_libs = template.libraries.items() builtin_libs = [(None, lib) for lib in template.builtins] for module_name, library in builtin_libs + app_libs: for filter_name, filter_func in library.filters.items(): title, body, metadata = utils.parse_docstring(filter_func.__doc__) if title: title = utils.parse_rst(title, 'filter', _('filter:') + filter_name) if body: body = utils.parse_rst(body, 'filter', _('filter:') + filter_name) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'filter', _('filter:') + filter_name) if library in template.builtins: tag_library = None else: tag_library = module_name.split('.')[-1] filters.append({ 'name': filter_name, 'title': title, 'body': body, 'meta': metadata, 'library': tag_library, }) return render_to_response('admin_doc/template_filter_index.html', { 'root_path': urlresolvers.reverse('admin:index'), 'filters': filters }, context_instance=RequestContext(request))
def view_index(request): if not utils.docutils_is_available: return missing_docutils_page(request) if settings.ADMIN_FOR: settings_modules = [import_module(m) for m in settings.ADMIN_FOR] else: settings_modules = [settings] views = [] for settings_mod in settings_modules: urlconf = import_module(settings_mod.ROOT_URLCONF) view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns) if Site._meta.installed: site_obj = Site.objects.get(pk=settings_mod.SITE_ID) else: site_obj = GenericSite() for (func, regex) in view_functions: views.append({ 'full_name': '%s.%s' % (func.__module__, getattr(func, '__name__', func.__class__.__name__)), 'site_id': settings_mod.SITE_ID, 'site': site_obj, 'url': simplify_regex(regex), }) return render_to_response('admin_doc/view_index.html', { 'root_path': urlresolvers.reverse('admin:index'), 'views': views }, context_instance=RequestContext(request))
def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from my_django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) c = RequestContext(request, { 'flatpage': f, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, FlatPage, f.id) return response
def model_index(request): if not utils.docutils_is_available: return missing_docutils_page(request) m_list = [m._meta for m in models.get_models()] return render_to_response('admin_doc/model_index.html', { 'root_path': urlresolvers.reverse('admin:index'), 'models': m_list }, context_instance=RequestContext(request))
def resolve_context(self, context): """Convert context data into a full RequestContext object (assuming it isn't already a Context object). """ if isinstance(context, Context): return context return RequestContext(self._request, context, current_app=self._current_app)
def __search(request, repo): """ search in a repository ``repo`` the repository """ if 'q' in request.GET: q = request.GET.get('q') else: q = None results = [] if q is not None: max = repo.get_context().rev end = max - global_settings.DJANGO_HG_MAX_SEARCH_RESULTS c = max while c > end: ctx = repo.get_context().repository[c] files = [] for f in ctx.files(): if f.lower().find(q.lower()) > -1: files.append(f) if (codecs.decode(ctx.description(), 'utf8').lower().find( q.lower()) > -1 or (codecs.decode( ctx.user(), 'utf8').lower().find(q.lower()) > -1) or (str(ctx).find(q) > -1) or (len(files) > 0)): results.append({ "user": ctx.user(), "description": ctx.description(), "time": datetime.fromtimestamp(ctx.date()[0]).time(), "date": date.fromtimestamp(ctx.date()[0]), "files_count": len(ctx.files()), "files": files, "hash": str(ctx), "rev": c, }) c = c - 1 if c < 0: break return render_to_response('django_hg/search.html', { 'max': global_settings.DJANGO_HG_MAX_SEARCH_RESULTS, 'q': q, 'repo': repo, 'results': results, 'rev': 'tip', 'groups': _get_left_side_cont(), }, context_instance=RequestContext(request))
def __log(request, repo, rev, path): """ display the file log ``repo`` the repository ``rev`` the revision in the changesets history ``path`` the file for which we want the log """ ctx = repo.get_context().repository[rev] fctx = ctx.filectx(path) filelog = [] for fl in fctx.filelog(): l = fctx.filectx(fl) filelog.append({ 'user': l.user(), "time": datetime.fromtimestamp(l.date()[0]).time(), "date": date.fromtimestamp(l.date()[0]), 'description': l.description(), 'branch': l.branch(), 'hash': str(l)[str(l).rfind('@') + 1:], 'filesize': l.size(), 'rev': l.rev(), 'files_count': len(ctx.files()) }) filelog.reverse() from_rev = request.GET.get('from_rev', '') to_rev = request.GET.get('to_rev', '') form = HgDiffForm(filelog, {'from_rev': from_rev, 'to_rev': to_rev}) if '' != from_rev and '' != to_rev and form.is_valid(): return HttpResponseRedirect( reverse('hg-repo-action-rev-path', kwargs={ 'name': repo.name, 'action': 'changesets', 'rev': from_rev, 'path': path }) + '?from_rev=' + str(from_rev) + '&to_rev=' + str(to_rev)) return render_to_response('django_hg/log.html', { 'file': path, 'filelog': filelog, 'form': form, 'from_rev': from_rev, 'path': path, 'repo': repo, 'rev': rev, 'to_rev': to_rev, 'groups': _get_left_side_cont(), }, context_instance=RequestContext(request))
def object_detail(request, queryset, 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): """ Generic detail of an object. Templates: ``<app_label>/<model_name>_detail.html`` Context: object the object """ if extra_context is None: extra_context = {} model = queryset.model if object_id: queryset = queryset.filter(pk=object_id) elif slug and slug_field: queryset = queryset.filter(**{slug_field: slug}) else: raise AttributeError( "Generic detail view must be called with either an object_id or a slug/slug_field." ) try: obj = queryset.get() except ObjectDoesNotExist: raise Http404("No %s found matching the query" % (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
def __changesets(request, repo): """ display the changesets history of a repository """ max = repo.get_context().rev page = int(request.GET.get('page', 1)) # forbid a page to be greater than the max or to be lower than one if page > max / global_settings.DJANGO_HG_PAGER_ITEMS: page = max / global_settings.DJANGO_HG_PAGER_ITEMS + 1 elif page < 1: page = 1 start = max - (page - 1) * global_settings.DJANGO_HG_PAGER_ITEMS end = max - (page) * global_settings.DJANGO_HG_PAGER_ITEMS changelog = [] c = start while c > end: try: ctx = repo.get_context().repository[c] # we pass a dict instead of the object because it's really, really # faster (from 12500 to 48 ms with the django repository ! ) changelog.append({ "user": ctx.user(), "description": ctx.description(), "time": datetime.fromtimestamp(ctx.date()[0]).time(), "date": date.fromtimestamp(ctx.date()[0]), "files_count": len(ctx.files()), "hash": ctx, "rev": c, }) except: pass c = c - 1 if c < 0: break return render_to_response('django_hg/changesets.html', { 'changelog': changelog, 'end': end > 0 and end + 1 or 1, 'items_per_page': global_settings.DJANGO_HG_PAGER_ITEMS, 'max': max, 'page': page, 'repo': repo, 'start': start, 'groups': _get_left_side_cont(), }, context_instance=RequestContext(request))
def update_object(request, model=None, object_id=None, slug=None, slug_field='slug', template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, template_object_name='object', form_class=None): """ Generic object-update function. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form for the object object the original object being edited """ if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) model, form_class = get_model_and_form_class(model, form_class) obj = lookup_object(model, object_id, slug, slug_field) if request.method == 'POST': form = form_class(request.POST, request.FILES, instance=obj) if form.is_valid(): obj = form.save() msg = ugettext("The %(verbose_name)s was updated successfully.") %\ {"verbose_name": model._meta.verbose_name} messages.success(request, msg, fail_silently=True) return redirect(post_save_redirect, obj) else: form = form_class(instance=obj) if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, template_object_name: obj, }, context_processors) apply_extra_context(extra_context, c) response = HttpResponse(t.render(c)) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.attname)) return response
def confirmed(request): comment = None if 'c' in request.GET: try: comment = comments.get_model().objects.get(pk=request.GET['c']) except (ObjectDoesNotExist, ValueError): pass return render_to_response(template, {'comment': comment}, context_instance=RequestContext(request) )
def render_to_response(request, template_name, context_dict, **kwargs): from cicero.context import default from my_django.template import RequestContext from my_django.shortcuts import render_to_response as _render_to_response #if not kwargs.has_key('extra_context'): # kwargs['extra_context'] = {} #kwargs['extra_context']['groups'] = _get_left_side_cont() context_dict['groups'] = _get_left_side_cont() context = RequestContext(request, context_dict, [default]) return _render_to_response(template_name, context_instance=context, **kwargs)
def __diff(request, repo, rev, path): """ display a diff of a file ``repo`` the repository ``rev`` the revision in the changesets history ``path`` the file for which we want the log """ ctx = repo.get_context().repository[rev] if request.GET.get('from_rev') and request.GET.get('to_rev'): # compare two given revs from_rev = request.GET.get('from_rev') to_rev = request.GET.get('to_rev') else: # Compare the rev given as parameter with the previous one the file has # been changed from_rev = rev to_rev = rev ctx = repo.get_context().repository[rev] fctx = ctx.filectx(path) for fl in fctx.filelog(): l = fctx.filectx(fl) if fl == fctx.filerev() - 1: from_rev = l.rev() break ctx = repo.get_context().repository[from_rev] fctx = ctx.filectx(path) data1 = fctx.data().split('\n') ctx2 = repo.get_context().repository[to_rev] data2 = ctx2.filectx(path).data().split('\n') diff = difflib.unified_diff(data1, data2, fromfile=path + '@' + str(from_rev), tofile=path + '@' + str(to_rev)) return render_to_response('django_hg/diff.html', { 'diff': diff, 'file': path, 'from_rev': from_rev, 'path': path, 'repo': repo, 'rev': rev, 'to_rev': to_rev, 'groups': _get_left_side_cont(), }, context_instance=RequestContext(request))
def archive_week(request, year, week, queryset, date_field, template_name=None, template_loader=loader, extra_context=None, allow_empty=True, context_processors=None, template_object_name='object', mimetype=None, allow_future=False): """ Generic weekly archive view. Templates: ``<app_label>/<model_name>_archive_week.html`` Context: week: (date) this week object_list: list of objects published in the given week """ if extra_context is None: extra_context = {} try: tt = time.strptime(year+'-0-'+week, '%Y-%w-%U') date = datetime.date(*tt[:3]) except ValueError: raise Http404 model = queryset.model now = timezone.now() # Calculate first and last day of week, for use in a date-range lookup. first_day = date last_day = date + datetime.timedelta(days=7) lookup_kwargs = { '%s__gte' % date_field: first_day, '%s__lt' % date_field: last_day, } # Only bother to check current date if the week isn't in the past and future objects aren't requested. if last_day >= now.date() and not allow_future: lookup_kwargs['%s__lte' % date_field] = now object_list = queryset.filter(**lookup_kwargs) if not object_list and not allow_empty: raise Http404 if not template_name: template_name = "%s/%s_archive_week.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { '%s_list' % template_object_name: object_list, 'week': date, }) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value return HttpResponse(t.render(c), mimetype=mimetype)
def delete_object(request, model, post_delete_redirect, object_id=None, slug=None, slug_field='slug', template_name=None, template_loader=loader, extra_context=None, login_required=False, context_processors=None, template_object_name='object'): """ Generic object-delete function. The given template will be used to confirm deletetion if this view is fetched using GET; for safty, deletion will only be performed if this view is POSTed. Templates: ``<app_label>/<model_name>_confirm_delete.html`` Context: object the original object being deleted """ if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) obj = lookup_object(model, object_id, slug, slug_field) if request.method == 'POST': obj.delete() msg = ugettext("The %(verbose_name)s was deleted.") %\ {"verbose_name": model._meta.verbose_name} messages.success(request, msg, fail_silently=True) return HttpResponseRedirect(post_delete_redirect) else: if not template_name: template_name = "%s/%s_confirm_delete.html" % ( model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: obj, }, context_processors) apply_extra_context(extra_context, c) response = HttpResponse(t.render(c)) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.attname)) return response
def __browse(request, repo, rev, path): if rev == 'tip': rev = repo.get_context().rev files = repo.get_context().get_directory(path) if files == False: raise Http404 return render_to_response('django_hg/browse.html', { 'files': files, 'hash': repo.get_context().repository[rev], 'path': path, 'repo': repo, 'rev': rev, 'groups': _get_left_side_cont(), }, context_instance=RequestContext(request))
def archive_year(request, year, queryset, date_field, template_name=None, template_loader=loader, extra_context=None, allow_empty=False, context_processors=None, template_object_name='object', mimetype=None, make_object_list=False, allow_future=False): """ Generic yearly archive view. Templates: ``<app_label>/<model_name>_archive_year.html`` Context: date_list List of months in this year with objects year This year object_list List of objects published in the given month (Only available if make_object_list argument is True) """ if extra_context is None: extra_context = {} model = queryset.model now = timezone.now() lookup_kwargs = {'%s__year' % date_field: year} # Only bother to check current date if the year isn't in the past and future objects aren't requested. if int(year) >= now.year and not allow_future: lookup_kwargs['%s__lte' % date_field] = now date_list = queryset.filter(**lookup_kwargs).dates(date_field, 'month') if not date_list and not allow_empty: raise Http404 if make_object_list: object_list = queryset.filter(**lookup_kwargs) else: object_list = [] if not template_name: template_name = "%s/%s_archive_year.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'date_list': date_list, 'year': year, '%s_list' % template_object_name: object_list, }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value return HttpResponse(t.render(c), mimetype=mimetype)
def __overview(request, repo, rev): ctx = repo.get_context().repository[rev] return render_to_response('django_hg/overview.html', { 'ctx': { "user": ctx.user(), "description": ctx.description(), "time": datetime.fromtimestamp(ctx.date()[0]).time(), "date": date.fromtimestamp(ctx.date()[0]), "hash": ctx, "rev": repo.get_context().rev, "files_count": len(ctx.files()) }, 'repo': repo, 'rev': 'tip', 'groups': _get_left_side_cont(), }, context_instance=RequestContext(request))
def create_object(request, model=None, template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, form_class=None): """ Generic object-creation function. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form for the object """ if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) model, form_class = get_model_and_form_class(model, form_class) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): new_object = form.save() msg = ugettext("The %(verbose_name)s was created successfully.") %\ {"verbose_name": model._meta.verbose_name} messages.success(request, msg, fail_silently=True) return redirect(post_save_redirect, new_object) else: form = form_class() # Create the template, context, response if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, }, context_processors) apply_extra_context(extra_context, c) return HttpResponse(t.render(c))
def direct_to_template(request, template, extra_context=None, mimetype=None, **kwargs): """ Render a given template with any extra URL parameters in the context as ``{{ params }}``. """ if extra_context is None: extra_context = {} dictionary = {'params': kwargs} for key, value in extra_context.items(): if callable(value): dictionary[key] = value() else: dictionary[key] = value c = RequestContext(request, dictionary) t = loader.get_template(template) return HttpResponse(t.render(c), content_type=mimetype)
def archive_index(request, queryset, date_field, num_latest=15, template_name=None, template_loader=loader, extra_context=None, allow_empty=True, context_processors=None, mimetype=None, allow_future=False, template_object_name='latest'): """ Generic top-level archive of date-based objects. Templates: ``<app_label>/<model_name>_archive.html`` Context: date_list List of years latest Latest N (defaults to 15) objects by date """ if extra_context is None: extra_context = {} model = queryset.model if not allow_future: queryset = queryset.filter(**{'%s__lte' % date_field: timezone.now()}) date_list = queryset.dates(date_field, 'year')[::-1] if not date_list and not allow_empty: raise Http404("No %s available" % model._meta.verbose_name) if date_list and num_latest: latest = queryset.order_by('-'+date_field)[:num_latest] else: latest = None if not template_name: template_name = "%s/%s_archive.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'date_list' : date_list, template_object_name : latest, }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value return HttpResponse(t.render(c), mimetype=mimetype)
def view_detail(request, view): if not utils.docutils_is_available: return missing_docutils_page(request) mod, func = urlresolvers.get_mod_func(view) try: view_func = getattr(import_module(mod), func) except (ImportError, AttributeError): raise Http404 title, body, metadata = utils.parse_docstring(view_func.__doc__) if title: title = utils.parse_rst(title, 'view', _('view:') + view) if body: body = utils.parse_rst(body, 'view', _('view:') + view) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view) return render_to_response('admin_doc/view_detail.html', { 'root_path': urlresolvers.reverse('admin:index'), 'name': view, 'summary': title, 'body': body, 'meta': metadata, }, context_instance=RequestContext(request))
def template_detail(request, template): templates = [] for site_settings_module in settings.ADMIN_FOR: settings_mod = import_module(site_settings_module) if Site._meta.installed: site_obj = Site.objects.get(pk=settings_mod.SITE_ID) else: site_obj = GenericSite() for dir in settings_mod.TEMPLATE_DIRS: template_file = os.path.join(dir, template) templates.append({ 'file': template_file, 'exists': os.path.exists(template_file), 'contents': lambda: os.path.exists(template_file) and open(template_file).read() or '', 'site_id': settings_mod.SITE_ID, 'site': site_obj, 'order': list(settings_mod.TEMPLATE_DIRS).index(dir), }) return render_to_response('admin_doc/template_detail.html', { 'root_path': urlresolvers.reverse('admin:index'), 'name': template, 'templates': templates, }, context_instance=RequestContext(request))
def __show(request, repo, rev, path): """ display the file informations at the given rev ``repo`` the repository ``rev`` the revision in the changesets history ``file`` the file for which we want the history """ ctx = repo.get_context().repository[rev] fctx = ctx.filectx(path) if 'raw' in request.GET: mimetype = ('text/plain', None) else: mimetype = mimetypes.guess_type(path) if 'download' in request.GET: response = HttpResponse(fctx.data(), mimetype[0]) response['Content-Disposition'] = 'attachment; filename=' + path[ path.rfind('/') + 1:] return response else: return render_to_response('django_hg/show.html', { 'DJANGO_HG_PYGMENT_STYLE': global_settings.DJANGO_HG_PYGMENT_STYLE, 'fctx': fctx, 'file': path, 'host': request.META['HTTP_HOST'], 'mimetype': mimetype, 'path': path, 'repo': repo, 'rev': rev, 'size': fctx.size(), 'groups': _get_left_side_cont(), }, context_instance=RequestContext(request))
def render(request, *args, **kwargs): """ Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. Uses a RequestContext by default. """ httpresponse_kwargs = { 'content_type': kwargs.pop('content_type', None), 'status': kwargs.pop('status', None), } if 'context_instance' in kwargs: context_instance = kwargs.pop('context_instance') if kwargs.get('current_app', None): raise ValueError('If you provide a context_instance you must ' 'set its current_app before calling render()') else: current_app = kwargs.pop('current_app', None) context_instance = RequestContext(request, current_app=current_app) kwargs['context_instance'] = context_instance return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
def __changeset(request, repo, rev): """ display the file history ``name`` the name of the repository ``rev`` the revision in the changesets history """ ctx = repo.get_context().repository[rev] to_rev = rev files = [] for f in ctx.files(): mimetype = mimetypes.guess_type(f) try: fc = ctx[f] if mimetype[0] is not None: if mimetype[0] not in BINARY_MIMETYPES: data1 = fc.data().split('\n') from_rev = int(rev) - int(fc.filerev()) ctx2 = repo.get_context().repository[from_rev] data2 = ctx2.filectx(f).data().split('\n') diff = difflib.unified_diff(data1, data2, fromfile=f + '@' + str(from_rev), tofile=f + '@' + str(to_rev)) else: diff = None else: diff = None files.append({ 'name': f, 'size': len(fc.data()), 'mimetype': mimetype[0], 'diff': diff }) except: files.append({'name': f, 'size': -1}) if 'HTTP_REFERER' in request.META: referer = request.META['HTTP_REFERER'] else: referer = reverse('hg-repo-action', kwargs={ 'name': repo.name, 'action': 'changesets' }) return render_to_response('django_hg/changeset.html', { 'ctx': { "user": ctx.user(), "description": ctx.description(), "time": datetime.fromtimestamp(ctx.date()[0]).time(), "date": date.fromtimestamp(ctx.date()[0]), "hash": ctx, "rev": rev, "files_count": len(ctx.files()) }, 'files': files, 'repo': repo, 'referer': referer, 'rev': rev, 'groups': _get_left_side_cont(), }, context_instance=RequestContext(request))
def list(request, tab): """ display a paginated list of repositories. If the user is authenticated, the contains both public and private repositories. If not, the list contains only public repositories """ if not request.user.is_authenticated(): tab = 'all' if tab == 'all': form = HgRepositoryForm(request.user, { 'search': request.GET.get('search'), 'display': 'all', }, label_suffix='') else: form = HgRepositoryForm(request.user, { 'search': request.GET.get('search'), 'display': request.GET.get('display'), }, label_suffix='') if form.is_valid(): search = form.data['search'] display = form.data['display'] if search != '' and search is not None: terms = search.split(' ') else: terms = None else: search = None display = 'all' terms = None page = int(request.GET.get('page', 1)) if page <= 0: page = 1 max = HgRepository.objects.count_for_user(request.user, 1, search=search, display=display) if ceil(float(max) / float(global_settings.DJANGO_HG_PAGER_ITEMS)) < page: page = int( ceil(float(max) / float(global_settings.DJANGO_HG_PAGER_ITEMS))) start = (page - 1) * global_settings.DJANGO_HG_PAGER_ITEMS end = page * global_settings.DJANGO_HG_PAGER_ITEMS if end > max: end = max repositories = [] if (max > 0): q = HgRepository.objects.get_for_user(request.user, 1, search=search, display=display)[start:end] for repo in q: try: repo.set_context(HgContext(repo, 'tip')) repo.absolute_url = ''.join([ 'http', ('', 's')[request.is_secure()], '://', request.META['HTTP_HOST'], repo.get_absolute_url() ]) repositories.append(repo) except: pass return render_to_response('django_hg/list.html', { 'end': end, 'host': request.META['HTTP_HOST'], 'items_per_page': global_settings.DJANGO_HG_PAGER_ITEMS, 'repositories': repositories, 'page': page, 'form': form.as_ul(), 'start': start + 1, 'terms': terms, 'max': int(max), 'groups': _get_left_side_cont(), }, context_instance=RequestContext(request))
def show(request): t = Template(TEMPLATE) return HttpResponse(t.render(RequestContext(request)))