def ajax_form(request, extra_context=None, template=bookmarks_tags.BookmarkFormNode.template_name): """ Called by *ajax_bookmark_form* templatetag, this view accepts AJAX requests and returns the bookmark form html fragment. The template used to render the context is the same as the one used by *bookmark_form* templatetag. """ if request.is_ajax(): # getting handler model_name = request.GET.get('model', '') model = get_model(*model_name.split('.')) if model is None: # invalid model -> bad request return http.HttpResponseBadRequest(ERRORS['model']) handler = handlers.library.get_handler(model) if handler is None: # bad or unregistered model -> bad request return http.HttpResponseBadRequest(ERRORS['handler']) # getting instance object_id = request.GET.get('object_id') try: instance = model.objects.get(pk=object_id) except (TypeError, ValueError, model.DoesNotExist): # invalid instance -> bad request return http.HttpResponseBadRequest(ERRORS['instance']) # getting form form = handler.get_form(request, data=request.GET) # validating the bookmark key key = handler.get_key(request, instance, request.GET.get('key')) if not handler.allow_key(request, instance, key): return http.HttpResponseBadRequest(ERRORS['key']) # context and template context = bookmarks_tags.BookmarkFormNode.get_template_context( request, form, instance, key) context['next_url'] = request.META.get('HTTP_REFERER') or '/' if extra_context is not None: context.update(extra_context) template = utils.get_templates(instance, key, template) # output return render_to_response(template, context, context_instance=RequestContext(request)) # only answer AJAX requests return http.HttpResponseForbidden('Forbidden.')
def render(self, context): # user validation request = context['request'] if request.user.is_anonymous() and self.varname is not None: return '' # instance and handler instance = self.instance.resolve(context) handler = handlers.library.get_handler(instance) # handler validation if handler is None: return '' # key validation key = handler.get_key(request, instance, self._get_key(context)) if not handler.allow_key(request, instance, key): return '' # creating form data = { 'model': str(instance._meta), 'object_id': str(instance.pk), 'key': key, } form = handler.get_form(request, data=data) if self.varname is None: # rendering the form ctx = template.RequestContext(request, self.get_template_context(context, form, instance, key)) templates = utils.get_templates(instance, key, self.template_name) return template.loader.render_to_string(templates, ctx) else: # form as template variable context[self.varname] = form return ''