コード例 #1
0
ファイル: views.py プロジェクト: vdboor/django-fiber
def page(request):
    url = request.path_info

    context = RequestContext(request)
    if 'fiber_page' not in context:
        """
        Take care of Django's CommonMiddleware redirect if the request URL doesn't end in a slash, and APPEND_SLASH=True
        https://docs.djangoproject.com/en/dev/ref/settings/#append-slash
        """
        if not url.endswith('/') and settings.APPEND_SLASH:
            return HttpResponsePermanentRedirect('%s/' % url)
        else:
            raise Http404
    else:
        page = context['fiber_page']
        if page.redirect_page and page.redirect_page != page:  #prevent redirecting to itself
            return HttpResponsePermanentRedirect(
                page.redirect_page.get_absolute_url())

    t = loader.get_template(page.template_name or DEFAULT_TEMPLATE)
    context['page'] = page

    response = HttpResponse(t.render(context))
    populate_xheaders(request, response, Page, page.id)
    return response
コード例 #2
0
ファイル: views.py プロジェクト: theatlantic/django-fatpages
def render_fatpage(request, f):
    """
    Internal interface to the fat 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 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 fatpage 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, {
        'fatpage': f,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, FatPage, f.id)
    return response
コード例 #3
0
ファイル: date_based.py プロジェクト: GoSteven/Diary
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):
        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
コード例 #4
0
def flatpage(request, url, queryset=FlatPage.objects.all()):
    """improved default view by extra parameter queryset instead hard-coded FlatPage"""
    if not url.endswith('/') and settings.APPEND_SLASH:
        return HttpResponseRedirect("%s/" % request.path)
    if not url.startswith('/'):
        url = "/" + url
    f = get_object_or_404(queryset, url__exact=url, sites__id__exact=settings.SITE_ID)
    # 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 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
コード例 #5
0
def flatpage(request, url):
    """
    Flat page view.

    Models: `flatpages.flatpages`
    Templates: Uses the template defined by the ``template_name`` field,
        or `flatpages/default.html` if template_name is not defined.
    Context:
        flatpage
            `flatpages.flatpages` object
    """
    if not url.startswith('/'):
        url = "/" + url
    f = get_object_or_404(FlatPage,
                          url__exact=url,
                          sites__id__exact=settings.SITE_ID)
    # 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 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)
    c = RequestContext(request, {
        'flatpage': f,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, FlatPage, f.id)
    return response
コード例 #6
0
ファイル: views.py プロジェクト: hawkerpl/k2
def flatpage(request, url):
    """
    Extended editable flat page view.

    Models: `flatpages.flatpages`
    Templates: Uses the template defined by the ``template_name`` field,
        or `flatpages/default.html` if template_name is not defined.
    Context:
        flatpage
            `flatpages.flatpages` object
    """
    if not request.GET.get('action') in ('create', 'edit', 'delete'):
        return flatpage_detail(request, url)
    if not url.endswith('/') and settings.APPEND_SLASH:
        return HttpResponseRedirect("%s/" % request.path)
    if not url.startswith('/'):
        url = "/" + url
    f = get_object_or_none(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID)
    if not f:
        if not request.user.has_perm('flatpages.add_flatpage'):
            raise Http404
        f = FlatPage(url=url)
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f and f.registration_required and not request.user.is_authenticated():
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if request.method == 'POST':
        form = FlatPageEditForm(request.POST, instance=f)
        if form.is_valid(): # All validation rules pass
            f.save()
            current_site = Site.objects.get_current()
            if not current_site in f.sites.all():
                # Assign page to current site
                f.sites.add(current_site)
                f.save()
            msg = _("The %(verbose_name)s was updated successfully.") %\
                {"verbose_name": FlatPage._meta.verbose_name}
            messages.success(request, msg, fail_silently=True)
            return HttpResponseRedirect(f.url)
    else:
        if request.GET.get('action') == 'delete':
            f.delete()
            msg = _("The %(verbose_name)s was deleted.") %\
                {"verbose_name": FlatPage._meta.verbose_name}
            messages.success(request, msg, fail_silently=True)
            return HttpResponseRedirect('/')
        form = FlatPageEditForm(instance=f)
    if f.template_name:
        t = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        t = loader.get_template(DEFAULT_TEMPLATE)

    c = RequestContext(request, {
        'form': form,
        'flatpage': f,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, FlatPage, f.id)
    return response
コード例 #7
0
def easy_page(request, page):
	"""
	Easy Page view.

	Models: `easy_pages.models.Page`
	Templates: Uses the template defined by the ``template_name`` field,
	    or `simple_pages/default.html` if template_name is not defined.
	Context:
	    page
	        `easy_pages.models.Page` object
	"""
	if not page.published:
		raise Http404
	if page.template:
		#template_name = 'templates/'.join(page.template.split('templates/')[1:])
		t = loader.select_template((page.template, DEFAULT_TEMPLATE))
	else:
		t = loader.get_template(DEFAULT_TEMPLATE)

	c = RequestContext(request, {
	    'page': page,
	})
	response = HttpResponse(t.render(c))
	populate_xheaders(request, response, Page, page.id)
	return response
コード例 #8
0
ファイル: views.py プロジェクト: wpjunior/b13
def render_wikipage(request, f):
    """
    Internal interface to the wiki page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.

    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, {
        'page': f,
        'request': request,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, Page, f.id)
    return response
コード例 #9
0
def render_page(request, p):
    """
    Internal interface to the page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    # If page is not pusblished and user is not admin of pages then raises 404
    if p.registration_required and not request.user.is_authenticated():
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if p.template_name:
        t = loader.select_template((p.template_name, DEFAULT_TEMPLATE))
    else:
        t = loader.get_template(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in page templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    p.title = mark_safe(p.title)
    p.content = mark_safe(p.content)

    c = RequestContext(request, {
        'page': p,
        'user': request.user,
    })
    response = HttpResponse(t.render(c))
    response.set_cookie('lang',
                        value=translation.get_language(),
                        max_age=(3600 * 24 * 7))
    populate_xheaders(request, response, Page, p.id)
    return response
コード例 #10
0
ファイル: list_detail.py プロジェクト: avastjohn/maventy_old
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
    obj = lookup_object(model, object_id, slug, slug_field, queryset)
    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, obj.key())
    return response
コード例 #11
0
ファイル: views.py プロジェクト: 0xmilk/appscale
def flatpage(request, url):
    """
    Flat page view.

    Models: `flatpages.flatpages`
    Templates: Uses the template defined by the ``template_name`` field,
        or `flatpages/default.html` if template_name is not defined.
    Context:
        flatpage
            `flatpages.flatpages` object
    """
    if not url.startswith('/'):
        url = "/" + url
    f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID)
    # 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 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)
    c = RequestContext(request, {
        'flatpage': f,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, FlatPage, f.id)
    return response
コード例 #12
0
ファイル: views.py プロジェクト: franckbret/django-massmedia
def mediatype_detail(request, queryset, object_id=None, slug=None,
            slug_field='slug', template_name=None, template_name_field=None,
            template_loader=None, extra_context=None,
            context_processors=None, template_object_name='object',
            mimetype=None):
    
    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 media 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))
    t = obj.get_template()
    c = RequestContext(request, {
        'media': 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
コード例 #13
0
    def _get_node(self):
        try:
            self.object = self.get_object()
        except self.model.DoesNotExist:
            return None

        self.request._current_fluent_page = self.object   # Avoid additional lookup in templatetags

        # Before returning the response of an object,
        # check if the plugin overwrites the root url with a custom view.
        plugin = self.get_plugin()
        resolver = plugin.get_url_resolver()
        if resolver:
            try:
                match = resolver.resolve('/')
            except Resolver404:
                pass
            else:
                return self._call_url_view(match)

        # Let page type plugin handle the request.
        response = plugin.get_response(self.request, self.object)
        if response is None:
            # Avoid automatic fallback to 404 page in this dispatcher.
            raise ValueError("The method '{0}.get_response()' didn't return an HttpResponse object.".format(plugin.__class__.__name__))

        if 'X-Object-Type' not in response:
            populate_xheaders(self.request, response, self.object, self.object.pk)

        return response
コード例 #14
0
ファイル: date_based.py プロジェクト: FactFiber/django-ff
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):
        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
コード例 #15
0
def infopage(request, url):
    """
    Info page view
    """
    if not url.endswith('/') and settings.APPEND_SLASH:
        return HttpResponseRedirect("%s/" % request.path)
    if not url.startswith('/'):
        url = "/" + url
    print url.replace(InfoPage.DELIMETER,"/").rstrip("/").lstrip("/")
    f = get_object_or_404(InfoPage, Q( url__exact=url ) | Q( path__exact=InfoPage.DELIMETER.join([ s for s in url.split("/") if len(s)]) ), sites__id__exact=settings.SITE_ID)

    # 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 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)

    c = RequestContext(request, {
        'infopage': f,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, InfoPage, f.id)
    return response
コード例 #16
0
def render_wikipage(request, f):
    """
    Internal interface to the wiki page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
        
    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, {
        'page': f,
        'request': request,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, Page, f.id)
    return response
コード例 #17
0
ファイル: views.py プロジェクト: suicidegirlsdev/kitdjango
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 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
コード例 #18
0
def get_product(request,
                product_slug=None,
                selected_options=(),
                default_view_tax=None):
    """Basic product view"""

    errors = [m for m in get_messages(request) if m.level == constants.ERROR]

    try:
        product = Product.objects.get_by_site(active=True, slug=product_slug)
    except Product.DoesNotExist:
        return bad_or_missing(
            request, _('The product you have requested does not exist.'))

    if default_view_tax is None:
        default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    subtype_names = product.get_subtypes()

    # Save product id for xheaders, in case we display a ConfigurableProduct
    product_id = product.id

    # Clone product object in order to have current product variations in context (extra_context)
    current_product = product

    if 'ProductVariation' in subtype_names:
        selected_options = product.productvariation.unique_option_ids
        #Display the ConfigurableProduct that this ProductVariation belongs to.
        product = product.productvariation.parent.product
        subtype_names = product.get_subtypes()

    best_discount = find_best_auto_discount(product)

    if errors:
        error_message = errors[0]
    else:
        error_message = None

    extra_context = {
        'product': product,
        'current_product': current_product,
        'default_view_tax': default_view_tax,
        'sale': best_discount,
        'error_message': error_message,
    }

    # Get the template context from the Product.
    extra_context = product.add_template_context(
        context=extra_context,
        request=request,
        selected_options=selected_options,
        default_view_tax=default_view_tax)

    template = find_product_template(product, producttypes=subtype_names)
    context = RequestContext(request, extra_context)

    response = http.HttpResponse(template.render(context))
    populate_xheaders(request, response, Product, product_id)
    return response
コード例 #19
0
ファイル: views.py プロジェクト: seler/django-basics
def render_category(request, category):
    t = loader.get_template('categories/category_detail.html')
    c = RequestContext(request, {
        'category': category,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, Category, category.id)
    return response
コード例 #20
0
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,
                  follow=None,
                  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
    """
    deprecate_follow(follow)
    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()
            if request.user.is_authenticated():
                request.user.message_set.create(
                    message=ugettext(
                        "The %(verbose_name)s was updated successfully.") %
                    {"verbose_name": model._meta.verbose_name})
            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
コード例 #21
0
ファイル: __init__.py プロジェクト: DrOctogon/Satchmo
def get_product(request, product_slug=None, selected_options=(),
    default_view_tax=None):
    """Basic product view"""

    errors = [m for m in get_messages(request) if m.level == constants.ERROR]

    try:
        product = Product.objects.get_by_site(active=True, slug=product_slug)
    except Product.DoesNotExist:
        return bad_or_missing(request, _('The product you have requested does not exist.'))

    if default_view_tax is None:
        default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    subtype_names = product.get_subtypes()

    # Save product id for xheaders, in case we display a ConfigurableProduct
    product_id = product.id

    # Clone product object in order to have current product variations in context (extra_context)
    current_product = product

    if 'ProductVariation' in subtype_names:
        selected_options = product.productvariation.unique_option_ids
        #Display the ConfigurableProduct that this ProductVariation belongs to.
        product = product.productvariation.parent.product
        subtype_names = product.get_subtypes()

    best_discount = find_best_auto_discount(product)

    if errors:
        error_message = errors[0]
    else:
        error_message = None

    extra_context = {
        'product': product,
        'current_product' : current_product,
        'default_view_tax': default_view_tax,
        'sale': best_discount,
        'error_message' : error_message,
    }

    # Get the template context from the Product.
    extra_context = product.add_template_context(context=extra_context,
        request=request, selected_options=selected_options,
        default_view_tax=default_view_tax)

    template = find_product_template(product, producttypes=subtype_names)
    context = RequestContext(request, extra_context)

    response = http.HttpResponse(template.render(context))
    try:
        from django.core.xheaders import populate_xheaders
        populate_xheaders(request, response, Product, product_id)
    except ImportError:
        pass
    return response
コード例 #22
0
ファイル: create_update.py プロジェクト: nbio/tweetly
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()
            if request.user.is_authenticated():
                # GAE: Create message with constructor
                Message(
                    request.user,
                    message=ugettext("The %(verbose_name)s was updated successfully.")
                    % {"verbose_name": model._meta.verbose_name},
                ).put()
            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))
    # GAE: changed last parameter to obj.key()
    populate_xheaders(request, response, model, obj.key())
    return response
コード例 #23
0
    def _call_url_view(self, match):
        response = match.func(self.request, *match.args, **match.kwargs)
        if response is None:
            raise RuntimeError("The view '{0}' didn't return an HttpResponse object.".format(match.url_name))

        if 'X-Object-Type' not in response:
            populate_xheaders(self.request, response, self.object, self.object.pk)

        return response
コード例 #24
0
ファイル: views.py プロジェクト: IgKh/Open-Knesset
    def render_object(self, request, 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, include_dir='include'):
        """
        Generic detail of an object.

        Templates: 
            if full ``<app_label>/<model_name>_detail.html`` or
            ``<app_label>/<include_dir>/_<model_name>_detail.html``

        Context:
            object
                the object
        """
        if self.extra_context:
            ec = dict(self.extra_context) 
        else:
            ec = {}
        ec.update(extra_context or {})     
        model = self.queryset.model

        if object_id:
            queryset = self.queryset.filter(pk=object_id)
        elif slug and slug_field:
            queryset = self.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 'part' in request.GET:
            template_name=self.full_to_part(template_name)
    
        if template_name_field:
            # TODO: if part specified modify the data from 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 ec.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
コード例 #25
0
ファイル: views.py プロジェクト: alainwolf/openbroadcast.org
def esi(request, app_label=None, model_name=None, object_id=None, timeout=900, template=None):
    """
    Using the app_label, module_name and object_id parameters create an object and render it using `template_name` or `template_dir`.
    
    Parameters:
        :app_label: `Name of a app (i.e. auth)`
        :model_name: `Name of a model (i.e. user)`
        :object_id: `This's objects primary key id`
        :timeout: `Time in secondsfor this objects max_age. [default 900]`
        :template: `a path to a template directory or a template`
        
    Context:
        `object`
            The object that was returned
        `model_name`
            If you are using a User object `user` will be in the context.
    
    Templates:
        if `template` is a directory:
            A file called `app_label`.`model_name`.html ,along with any other models'
            content types that the object extends, will be looked for in the `template`
            directory falling back to `template`/default.html 
            if none can be found.
        if `template` is a file:
            The file `template` will be loaded and rendered.
            
        If no template is provided `settings`.ESI_DEFAULT_TEMPLATE and `settings`.ESI_DEFAULT_DIRECTORY
        will be checked with the same logic as above.
        
    """
    default_template = getattr(settings, 'ESI_DEFAULT_TEMPLATE', None)
    default_template_dir = getattr(settings, 'ESI_DEFAULT_DIRECTORY', None)
    obj, model = get_object(app_label, model_name, object_id)
    template_list = []
    if template is not None:
        template_list.extend(get_template_list(obj, template))
    else:
        if default_template is not None:
            temp_t =  get_template_list(obj, default_template)
            if temp_t is not None:
                template_list.extend(get_template_list(obj, default_template))
        if default_template_dir is not None and len(template_list) == 0:
            temp_t =  get_template_list(obj, default_template_dir)
            if temp_t is not None:
                template_list.extend(get_template_list(obj, default_template_dir))
    if len(template_list) == 0:
        raise Http404
    t = loader.select_template(template_list)
    context = {
        'object': obj,
        model_name: obj
    }
    c = RequestContext(request, context)
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, model, getattr(obj, model._meta.pk.name))
    patch_cache_control(response, max_age=timeout)
    return response
コード例 #26
0
def show_order_pdf(request, objid):
    """Some descriptive text."""
    angebot = get_object_or_404(Angebot, id=objid)
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s' % (filename % objid)
    response.write(angebot.generate_pdf())
    LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(Angebot).id,
                                angebot.id, unicode(angebot), CHANGE, 'Output erzeugt') 
    populate_xheaders(request, response, Angebot, angebot.id)
    return response
コード例 #27
0
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
コード例 #28
0
def object_detail(request, year, month, day, app_label, module_name, date_field,
                  month_format='%b', day_format='%d', object_id=None, slug=None,
                  slug_field=None, template_name=None, template_name_field=None,
                  template_loader=template_loader, extra_lookup_kwargs={}, 
                  extra_context={}):
    """
    Generic detail view from year/month/day/slug or year/month/day/id structure.

    Templates: ``<app_label>/<module_name>_detail``
    Context:
        object:
            the object to be detailed
    """
    try:
        date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3])
    except ValueError:
        raise Http404

    mod = get_module(app_label, module_name)
    now = datetime.datetime.now()
    lookup_kwargs = {
        '%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max)),
    }
    # Only bother to check current date if the date isn't in the past.
    if date >= now.date():
        lookup_kwargs['%s__lte' % date_field] = now
    if object_id:
        lookup_kwargs['%s__exact' % mod.Klass._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")
    lookup_kwargs.update(extra_lookup_kwargs)
    try:
        object = mod.get_object(**lookup_kwargs)
    except ObjectDoesNotExist:
        raise Http404("%s.%s does not exist for %s" % (app_label, module_name, lookup_kwargs))
    if not template_name:
        template_name = "%s/%s_detail" % (app_label, module_name)
    if template_name_field:
        template_name_list = [getattr(object, template_name_field), template_name]
        t = template_loader.select_template(template_name_list)
    else:
        t = template_loader.get_template(template_name)
    c = Context(request, {
        'object': object,
    })
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, app_label, module_name, getattr(object, object._meta.pk.name))
    return response
コード例 #29
0
ファイル: util.py プロジェクト: antonis-m/synnefo
def _update_object(request, model=None, object_id=None, slug=None,
                   slug_field='slug', template_name=None,
                   template_loader=template_loader, extra_context=None,
                   post_save_redirect=None, login_required=False,
                   context_processors=None, template_object_name='object',
                   form_class=None, msg=None, summary_template_name=None):
    """
    Based of django.views.generic.create_update.update_object which displays a
    summary page before updating 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)
    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():
            verify = request.GET.get('verify')
            edit = request.GET.get('edit')
            if verify == '1':
                extra_context['show_form'] = False
                extra_context['form_data'] = form.cleaned_data
                template_name = summary_template_name
            elif edit == '1':
                extra_context['show_form'] = True
            else:
                obj = form.save()
                if not msg:
                    msg = _(
                        "The %(verbose_name)s was created successfully.")
                msg = msg % model._meta.__dict__
                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
コード例 #30
0
def showpage(request, url):
    """
    Flat page wiki view.
    
    template hardcoded for now
    """

    if not url.startswith('/'):
        url = "/" + url
    if not url.endswith('/'):
        url = url + "/"
    wikipath = url.split('/')[1]
    if not wikipath in settings.FLATPAGEWIKI_PATHS:
        raise Http404
    try:
        f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID)
    except Http404:
        return newpage(request, url)

    # 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():
        return redirect_to_login(request.path)
    if f.template_name:
        t = 'wiki/%s' % f.template_name
    else:
        t = DEFAULT_TEMPLATE

    edit = '0'
    if request.method == 'POST':
        if not request.user.has_perm('flatpages.change_flatpage'):
            raise Http404
        if request.POST['result'] == 'Cancel':
            return HttpResponseRedirect(f.url)
        else:
            if not request.user.is_authenticated():
                return redirect_to_login(request.path)
            form = WikiPageForm(request.POST)
            if form.is_valid():
                f.title = form.cleaned_data['title']
                f.content = (form.cleaned_data['content'])
                if settings.EMAIL_FLATPAGE_SAVES:
                    fp_change(request, f)
                f.save()
                return HttpResponseRedirect(f.url)
    else:
        if request.user.has_perm('flatpages.change_flatpage'):
            edit = request.GET.get('edit', '0') 
        form = WikiPageForm({'url': f.url, 'title': f.title, 'content': f.content })

    response = render_to_response(t,  
        RequestContext( request, { 'form': form, 'object': f, 'edit': edit  }) )
    populate_xheaders(request, response, FlatPage, f.id)
    return response
コード例 #31
0
ファイル: create_update.py プロジェクト: alatteri/informer
def delete_object(request, model, post_delete_redirect,
        object_id=None, slug=None, slug_field=None, 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)

    # Look up the object to be edited
    lookup_kwargs = {}
    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 delete view must be called with either an object_id or a slug/slug_field")
    try:
        object = model._default_manager.get(**lookup_kwargs)
    except ObjectDoesNotExist:
        raise Http404, "No %s found for %s" % (model._meta.app_label, lookup_kwargs)

    if request.method == 'POST':
        object.delete()
        if request.user.is_authenticated():
            request.user.message_set.create(message=gettext("The %(verbose_name)s was deleted.") % {"verbose_name": model._meta.verbose_name})
        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: object,
        }, context_processors)
        for key, value in extra_context.items():
            if callable(value):
                c[key] = value()
            else:
                c[key] = value
        response = HttpResponse(t.iter_render(c))
        populate_xheaders(request, response, model, getattr(object, object._meta.pk.attname))
        return response
コード例 #32
0
ファイル: views.py プロジェクト: chemt/vsad
def page(request, slug):
    f = get_object_or_404(Page, slug__exact=slug)

    f.name = mark_safe(f.name)
    f.text = mark_safe(f.text)

    c = RequestContext(request, {
        'page': f,
    })
    response = render_to_response('page.html', c)
    populate_xheaders(request, response, Page, f.id)
    return response
コード例 #33
0
ファイル: rendering.py プロジェクト: qwaya/my-django
def render(request, template, context = {}, ignore_ajax = False, obj=None, **render_kwargs):
    if request.is_ajax() and not ignore_ajax:
        basename = os.path.basename(template)
        if not basename.startswith("_"):
            dirname = os.path.dirname(template)
            template = "%s/_%s"%(dirname,basename)
        response = render_to_response(template, context)
    else:
        response = render_to_response(template, context, context_instance=RequestContext(request), **render_kwargs)
    if obj is not None:
        populate_xheaders(request, response, obj.__class__, obj.pk)
    return response
コード例 #34
0
def print_detail(request, app_label, model_name, pk, template_name=None,
        template_name_field=None,\
        template_loader=loader, extra_context=None,\
        context_processors=None, template_object_name='object',\
        mimetype=None):
    """
    Put the following line in your urls.py BEFORE your admin include
    (r'^admin/(?P<app_label>[\d\w]+)/(?P<model_name>[\d\w]+)/(?P<pk>[\d]+)/print/', 'biola.utils.print_view.print_detail'),

    Generic detail of an object.

    Templates: ``<app_label>/<model_name>_print_detail.html``
    Context:
        object
            the object
    """
    if not request.user.is_staff:
        return HttpResponseForbidden()
    if extra_context is None: extra_context = {}
    try:
        model = get_model(app_label, model_name)
        obj = model.objects.get(pk=pk)
    except ObjectDoesNotExist:
        raise Http404, "No %s found matching the query" % (
            model._meta.verbose_name)
    if not template_name:
        template_name = "admin/%s/%s_print_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)
    if model_name == 'application':
        try:
            pp = ParentPart.objects.get(application=obj)
        except:
            pp = []

    c = RequestContext(request, {
        template_object_name: obj,
        'pp': pp,
    }, 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
コード例 #35
0
ファイル: create_update.py プロジェクト: nbio/tweetly
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()
        if request.user.is_authenticated():
            # GAE: Create message with constructor
            Message(
                user=request.user,
                message=ugettext("The %(verbose_name)s was deleted.") % {"verbose_name": model._meta.verbose_name},
            ).put()
        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))
        # GAE: changed last parameter to obj.key()
        populate_xheaders(request, response, model, obj.key())
        return response
コード例 #36
0
def flat_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 view from just the slug name.

    Templates: ``<app_label>/<model_name>_detail.html``
    Context:
        object:
            the object to be detailed
    """
    if extra_context is None:
        extra_context = {}

    model = queryset.model

    lookup_kwargs = {}
    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
コード例 #37
0
def multilingual_flatpage(request, url):
    """
    Multilingual flat page view.

    Models: `multilingual.flatpages.models`
    Templates: Uses the template defined by the ``template_name`` field,
        or `flatpages/default.html` if template_name is not defined.
    Context:
        flatpage
            `flatpages.flatpages` object
    """
    if not url.endswith('/') and settings.APPEND_SLASH:
        return HttpResponseRedirect("%s/" % request.path)
    if not url.startswith('/'):
        url = "/" + url
    f = get_object_or_404(MultilingualFlatPage,
                          url__exact=url,
                          sites__id__exact=settings.SITE_ID)
    #breadcrumbs
    if f: breadcrumbs_for_flatpages(request, f)
    # 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 django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    # Serve the content in the language defined by the Django translation module
    # if possible else serve the default language.
    f._default_language = get_language()
    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)

    data = request_started.send(sender=MultilingualFlatPage, flatpage=f)

    if data.count > 1:
        data.pop(0)

    c = RequestContext(request, {
        'flatpage': f,
        'data': data,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, MultilingualFlatPage, f.id)
    return response
コード例 #38
0
ファイル: list_detail.py プロジェクト: idlweb/djangobile
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]
        if hasattr(request, 'device'):
            d = getattr(request, 'device', {})
            t = template_loader.select_template(template_name, d)
        else:
            t = template_loader.select_template(template_name_list)
    else:
        if hasattr(request, 'device'):
            d = getattr(request, 'device', {})
            t = template_loader.get_template(template_name, d)
        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
コード例 #39
0
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()
        if request.user.is_authenticated():
            request.user.message_set.create(
                message=ugettext("The %(verbose_name)s was deleted.") %
                {"verbose_name": model._meta.verbose_name})
        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
コード例 #40
0
ファイル: create_update.py プロジェクト: kawazrepos/Kawaz2nd
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, initial=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':
        if issubclass(form_class, ModelFormWithRequest):
            form = form_class(request, request.POST, request.FILES, instance=obj)
        else:
            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:
        if issubclass(form_class, ModelFormWithRequest):
            form = form_class(request, instance=obj, initial=initial)
        else:
            form = form_class(instance=obj, initial=initial)

    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
コード例 #41
0
ファイル: views.py プロジェクト: amachefe/Django-School
def print_detail(request, app_label, model_name, pk, template_name=None,
        template_name_field=None,\
        template_loader=loader, extra_context=None,\
        context_processors=None, template_object_name='object',\
        mimetype=None):
    """
    Put the following line in your urls.py BEFORE your admin include
    (r'^admin/(?P<app_label>[\d\w]+)/(?P<model_name>[\d\w]+)/(?P<pk>[\d]+)/print/', 'biola.utils.print_view.print_detail'),

    Generic detail of an object.

    Templates: ``<app_label>/<model_name>_print_detail.html``
    Context:
        object
            the object
    """
    if not request.user.is_staff:
        return HttpResponseForbidden()
    if extra_context is None: extra_context = {}
    try:
        model = get_model(app_label, model_name)
        obj = model.objects.get(pk=pk)
    except ObjectDoesNotExist:
        raise Http404, "No %s found matching the query" % (model._meta.verbose_name)
    if not template_name:
        template_name = "admin/%s/%s_print_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)
    if model_name == 'application':
        try:
            pp = ParentPart.objects.get(application = obj)
        except:
            pp = []

    c = RequestContext(request, {
        template_object_name: obj,
        'pp':pp,
    }, 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
コード例 #42
0
 def element(self, request, elem):
     """
     Renders single model objects to HttpResponse.
     """
     template_name = '%s/%s_detail.html' % (self.template_dir, elem._meta.module_name)
     t = self.template_loader.get_template(template_name)
     c = RequestContext(request, {
         self.template_object_name : elem,
     }, self.context_processors)
     # Hide unexposed fields
     self._hide_unexposed_fields(elem, self.expose_fields)
     c.update(self.extra_context)
     response = HttpResponse(t.render(c), mimetype=self.mimetype)
     populate_xheaders(request, response, elem.__class__, getattr(elem, elem._meta.pk.name))
     return response
コード例 #43
0
 def element(self, request, elem):
     """
     Renders single model objects to HttpResponse.
     """
     template_name = '%s/%s_detail.html' % (self.template_dir, elem._meta.module_name)
     t = self.template_loader.get_template(template_name)
     c = RequestContext(request, {
         self.template_object_name : elem,
     }, self.context_processors)
     # Hide unexposed fields
     self._hide_unexposed_fields(elem, self.expose_fields)
     c.update(self.extra_context)
     response = HttpResponse(t.render(c), mimetype=self.mimetype)
     populate_xheaders(request, response, elem.__class__, getattr(elem, elem._meta.pk.name))
     return response
コード例 #44
0
ファイル: views.py プロジェクト: refik/raptiye
def flatpage(request, url, template_name="default.html"):
    """
    Flat page view.

    Models: `flatpages.flatpages`
    Templates: Uses the template defined by the ``template_name`` field,
        or `flatpages/default.html` if template_name is not defined.
    Context:
        flatpage
            `flatpages.flatpages` object

    """

    if not url.endswith('/') and settings.APPEND_SLASH:
        return HttpResponseRedirect("%s/" % request.path)

    if not url.startswith('/'):
        url = "/" + url

    f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID, lang=request.LANGUAGE_CODE)

    # 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 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, template_name))
    else:
        t = loader.get_template(template_name)

    # 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
コード例 #45
0
def flatpage(request, url):
    """
    Flat page view.

    Models: `flatpages.flatpages`
    Templates: Uses the template defined by the ``template_name`` field,
        or `flatpages/default.html` if template_name is not defined.
    Context:
        flatpage
            `flatpages.flatpages` object
    """
    print >> sys.stderr, 'Goodbye, cruel world!'
    if not url.endswith('/') and settings.APPEND_SLASH:
        return HttpResponseRedirect("%s/" % request.path)
    if not url.startswith('/'):
        url = "/" + url
    f = get_object_or_404(FlatPage,
                          url__exact=url,
                          sites__id__exact=settings.SITE_ID)
    # 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 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,
        'current_path': request.path(),
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, FlatPage, f.id)
    return response
コード例 #46
0
def mediatype_detail(request,
                     queryset,
                     object_id=None,
                     slug=None,
                     slug_field='slug',
                     template_name=None,
                     template_name_field=None,
                     template_loader=None,
                     extra_context=None,
                     context_processors=None,
                     template_object_name='object',
                     mimetype=None):

    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 media 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))
    t = obj.get_template()
    c = RequestContext(request, {
        'media': 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
コード例 #47
0
def page(request, url):
    if not url.endswith('/') and settings.APPEND_SLASH:
        return HttpResponsePermanentRedirect("%s/" % request.path)

    context = RequestContext(request)
    if 'fiber_page' not in context:
        raise Http404
    else:
        page = context['fiber_page']
        if page.redirect_page and page.redirect_page != page:  #prevent redirecting to itself
            return HttpResponsePermanentRedirect(
                page.redirect_page.get_absolute_url())

    t = loader.get_template(page.template_name or DEFAULT_TEMPLATE)
    c = RequestContext(request, {
        'page': page,
    })

    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, Page, page.id)
    return response
コード例 #48
0
ファイル: views.py プロジェクト: zhiltsov/django-flypack
def render_flypage(request, f):
    if f.template_name:
        t = loader.select_template(
            (f.template_name, settings.DEFAULT_TEMPLATE))
    else:
        t = loader.get_template(settings.DEFAULT_TEMPLATE)

    f.title = mark_safe(f.title)
    f.text = mark_safe(f.text)

    c = RequestContext(
        request, {
            'title': f.title,
            'content': f.text,
            'description': f.description,
            'keywords': f.keywords,
            'flypage': f,
            'request': request,
        })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, Page, f.id)
    return response
コード例 #49
0
ファイル: views.py プロジェクト: registerguard/django-dox
def render_page(request, f):

    if f.login_required and not request.user.is_authenticated():
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)

    if f.template_name:
        template = DEFAULT_TEMPLATE.replace(
            'default.html',
            f.template_name)  # Saves user from having to type "dox/" path.
        t = loader.select_template((template, DEFAULT_TEMPLATE))
    else:
        t = loader.get_template(DEFAULT_TEMPLATE)

    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)

    c = RequestContext(request, {
        'page': f,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, Page, f.id)
    return response
コード例 #50
0
def delete_object(request,
                  model,
                  post_delete_redirect,
                  object_id=None,
                  slug=None,
                  slug_field=None,
                  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)

    # Look up the object to be edited
    lookup_kwargs = {}
    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 delete view must be called with either an object_id or a slug/slug_field"
        )
    try:
        object = model._default_manager.get(**lookup_kwargs)
    except ObjectDoesNotExist:
        raise Http404, "No %s found for %s" % (model._meta.app_label,
                                               lookup_kwargs)

    if request.method == 'POST':
        object.delete()
        if request.user.is_authenticated():
            request.user.message_set.create(
                message=gettext("The %(verbose_name)s was deleted.") %
                {"verbose_name": model._meta.verbose_name})
        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: object,
        }, context_processors)
        for key, value in extra_context.items():
            if callable(value):
                c[key] = value()
            else:
                c[key] = value
        response = HttpResponse(t.render(c))
        populate_xheaders(request, response, model,
                          getattr(object, object._meta.pk.attname))
        return response
コード例 #51
0
ファイル: views.py プロジェクト: nyumatova/django-page-cms
    def __call__(self, request, path=None, lang=None, delegation=True,
            **kwargs):

        current_page = False

        if path is None:
            raise ValueError(
                "pages.views.Details class view requires the path argument. "
                "Check your urls.py file.")

        # for the ones that might have forgotten to pass the language
        # the language is now removed from the page path
        if settings.PAGE_USE_LANGUAGE_PREFIX and lang is None:
            maybe_lang = path.split("/")[0]
            if maybe_lang in LANGUAGE_KEYS:
                lang = maybe_lang
                path = path[(len(lang) + 1):]

        lang = self.choose_language(lang, request)
        pages_navigation = self.get_navigation(request, path, lang)

        context = {
            'path': path,
            'pages_navigation': pages_navigation,
            'lang': lang,
        }

        is_staff = self.is_user_staff(request)

        current_page = self.resolve_page(request, context, is_staff)

        # if no pages has been found, we will try to find it via an Alias
        if not current_page:
            redirection = self.resolve_alias(request, path, lang)
            if redirection:
                return redirection
        else:
            context['current_page'] = current_page

        # If unauthorized to see the pages, raise a 404, That can
        # happen with expired pages.
        if not is_staff and not current_page.visible:
            raise Http404

        redirection = self.resolve_redirection(request, context)
        if redirection:
            return redirection

        template_name = self.get_template(request, context)

        self.extra_context(request, context)

        if delegation and current_page.delegate_to:
            answer = self.delegate(request, context, delegation, **kwargs)
            if answer:
                return answer

        # do what the auto_render was used to do.
        if kwargs.get('only_context', False):
            return context
        template_name = kwargs.get('template_name', template_name)
        response = render_to_response(template_name,
            RequestContext(request, context))
        current_page = context['current_page']
        populate_xheaders(request, response, Page, current_page.id)
        return response
コード例 #52
0
ファイル: views.py プロジェクト: salty-horse/Open-Knesset
    def render_object(self,
                      request,
                      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,
                      include_dir='include'):
        """
        Generic detail of an object.

        Templates: 
            if full ``<app_label>/<model_name>_detail.html`` or
            ``<app_label>/<include_dir>/_<model_name>_detail.html``

        Context:
            object
                the object
        """
        if self.extra_context:
            ec = dict(self.extra_context)
        else:
            ec = {}
        ec.update(extra_context or {})
        model = self.queryset.model

        if object_id:
            queryset = self.queryset.filter(pk=object_id)
        elif slug and slug_field:
            queryset = self.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 'part' in request.GET:
            template_name = self.full_to_part(template_name)

        if template_name_field:
            # TODO: if part specified modify the data from 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 ec.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
コード例 #53
0
def xview_xheaders(request, object_id):
    response = HttpResponse()
    populate_xheaders(request, response, Article, 1)
    return response
コード例 #54
0
ファイル: views.py プロジェクト: shaijudavis/project_layouts
def render_flatpage(request, f):
    """
    Internal interface to the flat page view.
    """
    # If the page is a draft, only show it to users who are staff.
    if f.status == 'd' and not request.user.is_authenticated():
        raise Http404
    # 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 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)

    # Track pageviews (but not of owner).
    if request.user != f.owner:
        f.views += 1
        f.save()

    # 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)

    # Create breadcrumb navigation links.
    # breadcrumb_urls = f.url.lstrip('/').rstrip('/').split('/')
    # breadcrumb_urls.insert(0, '/')
    #
    # for i, u in enumerate(breadcrumb_urls):
    #     try: # Try and get a flatpage instance from the URL.
    #         if u != '/':
    #             u = '/%s/' % u
    #         fp = FlatPage.objects.get(url__exact=u)
    #         bt = fp.title
    #         bu = fp.url
    #     except: # Default to the URL slug, capitalized if no flatpage was found.
    #         bt = u.capitalize()
    #         bu = None
    #     breadcrumbs += [{ # Contsruct a dictionary for the breadcrumb entity.
    #         'url': bu,
    #         'title': bt,
    #     }]

    breadcrumb_urls = []
    breadcrumbs = []

    def trim_page(url):
        """Trim the last section off a URL."""
        regex = re.compile(r'(?P<url>.*/)[-\w\.]+/?$')
        try:
            trimmed_url = regex.match(url).group(
                'url')  # Return the parent page
        except:
            trimmed_url = None  # Return None to indicate no parent.
        return trimmed_url

    def do_trimming(url):
        """Perform the trimming operations recursively."""
        breadcrumb_urls.append(url)
        trimmed_url = trim_page(url)
        if trimmed_url:
            do_trimming(trimmed_url)
        else:
            return True

    # Trim the flatpage's URL.
    do_trimming(f.url)

    # Reverse the list of breadcrumbs so the parent pages start first.
    breadcrumb_urls.reverse()

    # Loop through the list of pages and construct a list of url/title dictionaries
    # for each page to use in the templates.
    for i, u in enumerate(breadcrumb_urls):
        bn = ''
        bu = ''
        try:  # Try and get a flatpage instance from the URL.
            # if u != '/':
            #     u = '/%s/' % u
            fp = FlatPage.objects.get(url__exact=u)
            bn = fp.name
            bu = fp.url
        except:  # Try to handle missing pages cleanly.
            regex = re.compile(r'.*/(?P<url>[-\w\.]+)/?$')
            try:
                # Default to the URL slug of the last segment of the URL
                # (capitalized) if no flatpage was found. This gives us an
                # OK default for missing pages.
                bn = regex.match(u).group('url')
            except:
                # Worst case scenario we show the URL as the title if we can't
                # grab the last bit of the URL...
                bn = u
            bn = bn.capitalize(
            )  # Capitalize it to make it look a little nicer.
            # Return None if the flatpage doesn't exist so we don't link to it,
            # because it would cause a 404 error if we did.
            bu = None
        if (bn == '/'):
            bu = '/weblog'
        breadcrumbs += [{ # Contsruct a dictionary for the breadcrumb entity.
            'url': bu,
            'name': bn,
        }]

    c = RequestContext(request, {
        'flatpage': f,
        'breadcrumbs': breadcrumbs,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, FlatPage, f.id)
    return response
コード例 #55
0
def update_object(request,
                  model,
                  object_id=None,
                  slug=None,
                  slug_field=None,
                  template_name=None,
                  template_loader=loader,
                  extra_context=None,
                  post_save_redirect=None,
                  login_required=False,
                  follow=None,
                  context_processors=None,
                  template_object_name='object'):
    """
    Generic object-update function.

    Templates: ``<app_label>/<model_name>_form.html``
    Context:
        form
            the form wrapper 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)

    # Look up the object to be edited
    lookup_kwargs = {}
    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 edit view must be called with either an object_id or a slug/slug_field"
        )
    try:
        object = model.objects.get(**lookup_kwargs)
    except ObjectDoesNotExist:
        raise Http404, "No %s found for %s" % (model._meta.verbose_name,
                                               lookup_kwargs)

    manipulator = model.ChangeManipulator(getattr(object,
                                                  object._meta.pk.attname),
                                          follow=follow)

    if request.POST:
        new_data = request.POST.copy()
        if model._meta.has_field_type(FileField):
            new_data.update(request.FILES)
        errors = manipulator.get_validation_errors(new_data)
        manipulator.do_html2python(new_data)
        if not errors:
            object = manipulator.save(new_data)

            if request.user.is_authenticated():
                request.user.message_set.create(
                    message=gettext(
                        "The %(verbose_name)s was updated successfully.") %
                    {"verbose_name": model._meta.verbose_name})

            # Do a post-after-redirect so that reload works, etc.
            if post_save_redirect:
                return HttpResponseRedirect(post_save_redirect %
                                            object.__dict__)
            elif hasattr(object, 'get_absolute_url'):
                return HttpResponseRedirect(object.get_absolute_url())
            else:
                raise ImproperlyConfigured(
                    "No URL to redirect to from generic create view.")
    else:
        errors = {}
        # This makes sure the form acurate represents the fields of the place.
        new_data = manipulator.flatten_data()

    form = oldforms.FormWrapper(manipulator, new_data, errors)
    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: object,
    }, context_processors)
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, model,
                      getattr(object, object._meta.pk.attname))
    return response
コード例 #56
0
ファイル: util.py プロジェクト: mpastyl/websocket-console
    except (IOError, PermissionDenied), e:
        messages.error(request, e)
        return None
    else:
        if response == None:
            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 _resources_catalog(for_project=False, for_usage=False):
    """
    `resource_catalog` contains a list of tuples. Each tuple contains the group
    key the resource is assigned to and resources list of dicts that contain
    resource information.
    `resource_groups` contains information about the groups
    """
    # presentation data
    resources_meta = presentation.RESOURCES
    resource_groups = resources_meta.get('groups', {})
    resource_catalog = ()
    resource_keys = []
コード例 #57
0
def esi(request,
        app_label=None,
        model_name=None,
        object_id=None,
        timeout=900,
        template=None):
    """
    Using the app_label, module_name and object_id parameters create an object and render it using `template_name` or `template_dir`.
    
    Parameters:
        :app_label: `Name of a app (i.e. auth)`
        :model_name: `Name of a model (i.e. user)`
        :object_id: `This's objects primary key id`
        :timeout: `Time in secondsfor this objects max_age. [default 900]`
        :template: `a path to a template directory or a template`
        
    Context:
        `object`
            The object that was returned
        `model_name`
            If you are using a User object `user` will be in the context.
    
    Templates:
        if `template` is a directory:
            A file called `app_label`.`model_name`.html ,along with any other models'
            content types that the object extends, will be looked for in the `template`
            directory falling back to `template`/default.html 
            if none can be found.
        if `template` is a file:
            The file `template` will be loaded and rendered.
            
        If no template is provided `settings`.ESI_DEFAULT_TEMPLATE and `settings`.ESI_DEFAULT_DIRECTORY
        will be checked with the same logic as above.
        
    """
    default_template = getattr(settings, 'ESI_DEFAULT_TEMPLATE', None)
    default_template_dir = getattr(settings, 'ESI_DEFAULT_DIRECTORY', None)
    obj, model = get_object(app_label, model_name, object_id)
    template_list = []
    if template is not None:
        template_list.extend(get_template_list(obj, template))
    else:
        if default_template is not None:
            temp_t = get_template_list(obj, default_template)
            if temp_t is not None:
                template_list.extend(get_template_list(obj, default_template))
        if default_template_dir is not None and len(template_list) == 0:
            temp_t = get_template_list(obj, default_template_dir)
            if temp_t is not None:
                template_list.extend(
                    get_template_list(obj, default_template_dir))
    if len(template_list) == 0:
        raise Http404
    t = loader.select_template(template_list)
    context = {'object': obj, model_name: obj}
    c = RequestContext(request, context)
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, model,
                      getattr(obj, model._meta.pk.name))
    patch_cache_control(response, max_age=timeout)
    return response
コード例 #58
0
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, inlines=None):
    """
    Generic object-update function with inlines.

    Templates: ``<app_label>/<model_name>_form.html``
    Context:
        form
            the form for the object
        object
            the original object being edited
        xxx_formset
            ModelFormSet for model classes in ``inlines`` argument.
    """
    if extra_context is None:
        extra_context = {}
    if inlines is None:
        inlines = ()
    if login_required and not request.user.is_authenticated():
        return redirect_to_login(request.path)
    formset_classes = []
    formsets = []

    model, form_class = get_model_and_form_class(model, form_class)
    obj = lookup_object(model, object_id, slug, slug_field)

    for inline in inlines:
        formset_classes.append(inlineformset_factory(model, **inline))

    if request.method == 'POST':
        form = form_class(request.POST, request.FILES, instance=obj)
        if form.is_valid():
            form_validated = True
            new_object = form.save()
        else:
            form_validated = False
            new_object = obj

        for klass in formset_classes:
            formset = klass(request.POST, request.FILES, instance=new_object)
            formsets.append(formset)

        if all_valid(formsets) and form_validated:
            new_object.save()
            for formset in formsets:
                formset.save()

            if request.user.is_authenticated():
                request.user.message_set.create(message=ugettext("The "
                    "%(verbose_name)s was updated successfully.") % 
                        {"verbose_name": model._meta.verbose_name})
            return redirect(post_save_redirect, new_object)
    else:
        form = form_class(instance=obj)
        for klass in formset_classes:
            formset = klass(instance=obj)
            formsets.append(formset)

    if not template_name:
        template_name = "%s/%s_form.html" % (model._meta.app_label,
            model._meta.object_name.lower())
    template = template_loader.get_template(template_name)
    context = RequestContext(request, {
        'form': form,
        template_object_name: obj,
    }, context_processors)
    apply_extra_context(extra_context, context)
    for formset in formsets:
        key = '%s_formset' % formset.model._meta.object_name.lower()
        context[key] = formset
    response = http.HttpResponse(template.render(context))
    populate_xheaders(request, response, model, getattr(obj,
        obj._meta.pk.name))
    return response