def render(request, template_name, context=None, content_type=None, status=None, using=None): """ This is a wrapper around Django's render function that we use to handle chosing which frontend to render. A session variable is used to store which frontend should be used. This wrapper calls Django's render function with the `using` parameter set to the template engine name corresponding to the specified frontend. If the template can't be found, then we try again but using the default frontend. What this ebhaviour achieves is that if a template is not found for a given frontend, then it is loaded from the defualt frontend. This is similar to what could be ahieved using the `DIRS` parameter of the template engines configuration but it is not exatcly the same. Using this wrapper, we make sure that templates from the different frontend will never be mixed (e.g. we make sure that we don't take `sounds.html` from one frontend and `base.html` from another). This wrapper is intented to be use while we implement the new frontend. Once the whole implementation process is finished and we don't need the two frontends to coexist anymore, then we can get rid of this wrapper. """ # Get the name of the template engine/frontend name = selected_frontend(request) try: return django_render(request, template_name, context, content_type, status, using=name) except TemplateDoesNotExist: if name != settings.FRONTEND_DEFAULT: # If the required template does can't be found using the dselected engine, try with the default engine return django_render(request, template_name, context, content_type, status, using=settings.FRONTEND_DEFAULT) else: # If the default engine was being used, then raise the exception normally raise
def render(args=None, use_request_context = True, request=None): ''' Magic render... steal the request from the calling function. The template is determinted by whatever is set in args.template and lastly, pass in any of their arguments requires the primer.middleware.AutoMiddleware for the extra request parameters ''' #get the request out of the stack if request is None: request = get_request() #make args an empty dictionary if it is none so we can merge it with kwargs if not args: args = {} #check to see what template we should render #if the dev passed one, honor that, otherwise use the one determined in primer middleware if not 'view_template' in args: args['view_template'] = request.primer.get('view_template') if use_request_context: return django_render(request, args['view_template'], args, context_instance=RequestContext(request)) else: return django_render(request, args['view_template'], args)
def render(request, template, context=None, **kwargs): """ Same as django's render() shortcut, but with l10n template support. If used like this:: return l10n_utils.render(request, 'myapp/mytemplate.html') ... this helper will render the following template:: l10n/LANG/myapp/mytemplate.html if present, otherwise, it'll render the specified (en-US) template. """ context = {} if context is None else context # Make sure we have a single template if isinstance(template, list): template = template[0] # Every template gets its own .lang file, so figure out what it is # and pass it in the context context['template'] = template context['langfile'] = get_lang_path(template) # Get the available translation list of the current page context['translations'] = translations_for_template(template) # Look for localized template if not default lang. if hasattr(request, 'locale') and request.locale != settings.LANGUAGE_CODE: # Redirect to one of the user's accept languages or the site's default # language (en-US) if the current locale not active if not template_is_active(template, get_locale(request)): matched = None for lang in get_accept_languages(request): if template_is_active(template, lang): matched = lang break response = HttpResponseRedirect('/' + '/'.join([ matched or settings.LANGUAGE_CODE, split_path(request.get_full_path())[1] ])) # Add the Vary header to avoid wrong redirects due to a cache response['Vary'] = 'Accept-Language' return response localized_tmpl = '%s/templates/%s' % (request.locale, template) try: return django_render(request, localized_tmpl, context, **kwargs) except TemplateDoesNotExist: # If not found, just go on and try rendering the parent template. pass return django_render(request, template, context, **kwargs)
def render(request, template, context=None, **kwargs): """ Same as django's render() shortcut, but with l10n template support. If used like this:: return l10n_utils.render(request, 'myapp/mytemplate.html') ... this helper will render the following template:: l10n/LANG/myapp/mytemplate.html if present, otherwise, it'll render the specified (en-US) template. """ context = {} if context is None else context # Make sure we have a single template if isinstance(template, list): template = template[0] # Every template gets its own .lang file, so figure out what it is # and pass it in the context context['langfile'] = get_lang_path(template) # Get the available translation list of the current page context['translations'] = get_translations(context['langfile']) # Look for localized template if not default lang. if hasattr(request, 'locale') and request.locale != settings.LANGUAGE_CODE: # Redirect to one of the user's accept languages or the site's default # language (en-US) if the current locale not active if not template_is_active(template, get_locale(request)): matched = None for lang in get_accept_languages(request): if template_is_active(template, lang): matched = lang break response = HttpResponseRedirect('/' + '/'.join([ matched or settings.LANGUAGE_CODE, split_path(request.get_full_path())[1] ])) # Add the Vary header to avoid wrong redirects due to a cache response['Vary'] = 'Accept-Language' return response localized_tmpl = '%s/templates/%s' % (request.locale, template) try: return django_render(request, localized_tmpl, context, **kwargs) except TemplateDoesNotExist: # If not found, just go on and try rendering the parent template. pass return django_render(request, template, context, **kwargs)
def blank_payment(request): listing_form = ListingsForms() received_payments = FeedItem.objects.filter( recipient_id=request.profile.id, item_type='acknowledgement').order_by('-date') made_payments = FeedItem.objects.filter( poster_id=request.profile.id, item_type='acknowledgement').order_by('-date') form = BlankPaymentForm(max_ripple=None, initial=request.GET) if request.method == 'POST': if not request.POST['recipient']: messages.add_message(request, messages.ERROR, 'The recipient is invalid, please verify') return django_render(request, 'blank_payment.html', { 'form': form, 'listing_form': listing_form }) recipient = get_object_or_404(Profile, user__username=request.POST['recipient']) max_amount = ripple.max_payment(request.profile, recipient) form = BlankPaymentForm(request.POST, max_ripple=max_amount) if recipient == request.profile: messages.add_message(request, messages.ERROR, 'You cant send a payment to yourself') return django_render(request, 'blank_payment.html', { 'form': form, 'listing_form': listing_form }) can_ripple = max_amount > 0 if not can_ripple and request.POST['ripple'] == 'routed': messages.add_message( request, messages.ERROR, 'There are no available paths through the trust network, ' 'so you can only send direct trust') form = BlankPaymentForm(max_ripple=None, initial=request.GET) return django_render(request, 'blank_payment.html', { 'form': form, 'listing_form': listing_form }) payment = form.send_payment(request.profile, recipient, request.POST) create_notification(notifier=request.profile, recipient=recipient, type=Notification.PAYMENT) # send_payment_notification(payment) messages.add_message(request, messages.INFO, 'Payment sent.') return HttpResponseRedirect(reverse('blank_payment_user')) else: form = BlankPaymentForm(max_ripple=None, initial=request.GET) return django_render( request, 'blank_payment.html', { 'form': form, 'listing_form': listing_form, 'received_payments': received_payments, 'made_payments': made_payments })
def render(request, template, context = {}, ignore_ajax = False, obj=None, content_type=None, status=None, using=None): 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 = django_render(request=request, template_name=template, context=context) else: response = django_render(request, template_name=template, context=context, content_type=content_type, status=status, using=using) return response
def _render(request, template_name, wrapper_name, modals=None, assets=None, context=None, use_theme=True): """Render a selected template. Args: request: template_name: wrapper_name: modals: assets: context: use_theme: Returns: """ modals = modals if modals is not None else [] assets = assets if assets is not None else {"css": [], "js": []} js_asset = assets["js"] if "js" in assets else [] assets["js"] = _build_js_assets(js_asset) context = context if context is not None else {} # Rebuild the context for the app_wrapper template context = { "template": template_name, "modals": modals, "assets": assets, "data": context, "use_theme": use_theme, } return django_render(request, wrapper_name, context)
def render(request, template, context=None, status=None): """Wrapper around Django render to extend context""" if context is None: context = {} if 'project' in context and context['project'] is not None: context['description'] = get_project_description(context['project']) return django_render(request, template, context, status=status)
def render(request, template, context): context['pages'] = user_profile.get_pages(request, context['profile']) for page in context['pages']: if page['is_active']: context['active_page'] = page break if request.user.is_authenticated(): is_authenticated_user = context['profile'].pk == request.user.pk else: is_authenticated_user = False context['is_authenticated_user'] = is_authenticated_user user_acl = request.user.acl if request.user.is_authenticated(): if is_authenticated_user: context['show_email'] = True else: context['show_email'] = user_acl['can_see_users_emails'] else: context['show_email'] = False context['state'] = get_user_state(context['profile'], user_acl) return django_render(request, template, context)
def render(request, template, options=None): """ This is a replacement for the default 'render' function, but it adds a bunch of stuff from settings.py and some useful defaults. These get passed to every template. """ if options is None: options = {} f_code = sys._getframe(1).f_code dashboard = {} dashboard['favicon'] = settings.FAVICON dashboard['site_title'] = settings.TITLE dashboard['google_tracking_code'] = settings.GOOGLE_TRACKING_CODE dashboard['caller'] = f_code.co_name dashboard['filename'] = f_code.co_filename dashboard['year'] = datetime.date.today().year dashboard['page_title'] = unslugify(dashboard['caller'].capitalize()) # If any dashboard options are already set, they override the default settings # if they are not already set, set them! if 'dashboard' in options: dashboard.update(options['dashboard']) options['dashboard'] = dashboard return django_render(request, template, options)
def post(self, request): form = UserForm(request.POST) username = request.POST['username'] password = request.POST['password'] try: if not '@' in username: user = User.objects.get(username=username) user = authenticate(username=username, password=password) else: user = User.objects.get(email=username) user = authenticate(username=user.username, password=password) if user: # Password matching and user found with authenticate login(request, user) return HttpResponseRedirect(reverse('frontend:home')) else: # Password wrong messages.add_message(request, messages.ERROR, 'Username or Password is wrong') return HttpResponseRedirect( reverse('accounts:sign_in_user:sign_in_log_in')) except ObjectDoesNotExist: form.fields.pop('first_name') form.fields.pop('email') messages.add_message(request, messages.WARNING, 'This user is not registered yet') return django_render(request, 'accounts/sign_in.html', {'form': form}) except Exception as e: messages.add_message(request, messages.ERROR, " User not found") # return django_render(request, 'accounts/sign_in.html', {'form': form}) return HttpResponseRedirect( reverse('accounts:sign_in_user:sign_in_log_in'))
def render(request, template_name, context=None, content_type=None, status=None, using=None, logs=None): """ Wrapper around Django render method. Can take one or a list of logs and logs the response. No overhead if no logs are passed. """ if logs: obj_logger = ObjectLogger() if not isinstance(logs, list): logs = [ logs, ] for log in logs: log = obj_logger.log_response(log, context, status=str(status), headers='', content_type=str(content_type)) log.save() return django_render(request, template_name, context=context, content_type=content_type, status=status, using=using)
def render(request, template_name, context=None, **kwargs): """ Calls through to django.shortcuts.render but wraps the passed context in an AngularSafeContext object which by default will not allow access to the context unless inside a {% django_block %} template tag (which will ensure ng-non-bindable has been applied). """ context = context.copy() or {} def make_safe(ctx): for k in ctx: if not _is_safe_type(ctx[k]): ctx[k] = AngularContextValue(ctx[k]) return ctx context = make_safe(context) context["is_angular_template"] = True try: _local.ng_protected = True response = django_render(request, template_name, context, **kwargs) finally: delattr(_local, "ng_protected") response._ng_safe = True return response
def render(request, template_name, additional=None): if additional is None: additional = {} if request.user.is_authenticated(): additional.update({'username': request.user.get_username()}) return django_render(request, template_name, additional)
def discussion(request, game, player, sender_id): """ Panel to show discussions with other players """ # Set the game_id in session to always display all tabs request.session['gameid'] = game.pk sender = Player.objects.get(pk=sender_id) if request.method == 'POST': if player.game != sender.game: raise Http404("Seul les joueurs appartenant à la même partie peuvent discuter entre eux") form = MessageForm(request.POST) if form.is_valid(): # We add the sender and the receiver (they are not in the form) message = form.save(commit=False) message.sender = player message.receiver = sender message.save() return HttpResponseRedirect('') else: # creation form form = MessageForm() messages = Message.objects.get_discussion(player, sender) return django_render(request, 'game/discussion.html', { "game": game, "sender": sender, "messages": messages, "form": form, "request": request, })
def wrapper(request, *args, **kwargs): context = fun(request, *args, **kwargs) if isinstance(context, dict): template = name + ".html" return django_render(request, template, context) else: return context
def render(request, template, context=None): if context is None: context = {} # user_logged_in = getUserLoggedIn() # logger.debug("homepage hit") if 'user_logged_in' not in context: context['user_logged_in'] = request.user.is_authenticated() return django_render(request, template, context)
def render(request, *args, **kwargs): if len(args) > 1: args[1]["data"] = get_down_menu_data(request) elif "context" in kwargs: kwargs["context"]["data"] = get_down_menu_data(request) else: kwargs["context"] = {"data": get_down_menu_data(request)} return django_render(request, *args, **kwargs)
def render(*args, **kwargs): """ Wrapper around Django's `render` shortcut that is not allowed to run database queries """ with queries_disabled(): response = django_render(*args, **kwargs) return response
def render(request, template, context = None): if context is None: context = {} # user_logged_in = getUserLoggedIn() # logger.debug("homepage hit") if 'user_logged_in' not in context: context['user_logged_in'] = request.user.is_authenticated() return django_render(request, template, context)
def render(request, template_name, vars=None, *args, **kwargs): if vars is None: vars = {} if request.user.is_authenticated() and "user" not in vars: vars["user"] = request.user vars["is_doctor"] = user_in_group(request.user, "Doctors") vars["is_patient"] = user_in_group(request.user, "Patients") return django_render(request, template_name, vars, *args, **kwargs)
def get(self, request): if not request.location: return HttpResponseRedirect( "%s?%s=%s" % (reverse('locator'), REDIRECT_FIELD_NAME, request.path)) form = self.form_class() # form.fields.pop('new_password') return django_render(request, 'accounts/signup.html', {'form': form})
def render(request, template, context): """ If the "Accept" HTTP header contains "application/json", return a json string. Otherwise, return an HTML string. """ from django.shortcuts import render as django_render from django.http import HttpResponse from django.db.models.query import QuerySet from sqlalchemy.orm.query import Query from sqlalchemy.engine.result import ResultProxy from .models import user as csv2_user import datetime import decimal import json class csv2Encoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, csv2_user): return str(obj) if isinstance(obj, datetime.date): return str(obj) if isinstance(obj, decimal.Decimal): return str(obj) if isinstance(obj, dict) and 'ResultProxy' in obj: return json.dumps(obj['ResultProxy']) if isinstance(obj, Query): fields = {} for field in [ x for x in dir(obj) if not x.startswith('_') and x != 'metadata' ]: data = obj.__getattribute__(field) try: json.dumps( data ) # this will fail on non-encodable values, like other classes fields[field] = data except TypeError: fields[field] = None # a json-encodable dict return json.dumps(fields) return json.JSONEncoder.default(self, obj) if request.META['HTTP_ACCEPT'] == 'application/json': response = HttpResponse(json.dumps(context, cls=csv2Encoder), content_type='application/json') else: response = django_render(request, template, context) end_time = time.time() print("Render time: %f.5" % end_time) return response
def render(request, template, context=None, **kwargs): """ Same as django's render() shortcut, but with l10n template support. If used like this:: return l10n_utils.render(request, 'myapp/mytemplate.html') ... this helper will render the following template:: l10n/LANG/myapp/mytemplate.html if present, otherwise, it'll render the specified (en-US) template. """ context = {} if context is None else context # Make sure we have a single template if isinstance(template, list): template = template[0] # Every template gets its own .lang file, so figure out what it is # and pass it in the context context['langfile'] = get_lang_path(template) # Get the available translation list of the current page context['translations'] = get_translations(context['langfile']) # Look for localized template if not default lang. if hasattr(request, 'locale') and request.locale != settings.LANGUAGE_CODE: # redirect to default lang if locale not active if not (settings.DEV or lang_file_is_active(context['langfile'], request.locale)): return HttpResponseRedirect('/' + '/'.join([ settings.LANGUAGE_CODE, split_path(request.get_full_path())[1] ])) localized_tmpl = '%s/templates/%s' % (request.locale, template) try: return django_render(request, localized_tmpl, context, **kwargs) except TemplateDoesNotExist: # If not found, just go on and try rendering the parent template. pass return django_render(request, template, context, **kwargs)
def dashboard_offers_create(request): company = request.user.company if request.method == 'POST': offers = company.json.get("offers", []) offers.append(dict(request.POST)) company.json['offers'] = offers company.save() return HttpResponseRedirect(reverse("dashboard-offers-create")) return django_render(request, 'dashboard/offers/create.html', context_instance=RequestContext(request))
def dashboard_campaigns_create(request): company = request.user.company if request.method == 'POST': campaigns = company.json.get("campaigns", []) campaigns.append(dict(request.POST)) company.json['campaigns'] = campaigns company.save() return HttpResponseRedirect(reverse("dashboard-campaigns-create")) return django_render(request, 'dashboard/campaigns/create.html', context_instance=RequestContext(request))
def dashboard_fingerprints_create(request): company = request.user.company if request.method == 'POST': fingerprints = company.json.get("fingerprints", []) fingerprints.append(dict(request.POST)) company.json['fingerprints'] = fingerprints company.save() return HttpResponseRedirect(reverse("dashboard-fingerprints-create")) return django_render(request, 'dashboard/fingerprints/create.html', context_instance=RequestContext(request))
def _render_to_response(template, request, *args, **kwargs): template_lib = _get_template_lib(template, kwargs) if template_lib == DJANGO: kwargs.update(csrf(request)) return django_render(request, template, *args, **kwargs) elif template_lib == MAKO: return django_mako.render_to_response(template, *args, **kwargs) else: raise Exception("Bad template lib: %s" % template_lib)
def render(request, template_name, context=None, permission_cls=BasePermission): permission = permission_cls(request.permission_codes) if not context: context = {} context.setdefault('permission', permission) return django_render(request, template_name, context)
def render(request, *args, **kwargs): """Wrapper for django's render function which ensures there is a list of categories in the context if the user is logged in""" if request.user.is_authenticated: context = kwargs.get('context', {}) if 'categories' not in context: context['categories'] = models.Category.objects.all() kwargs['context'] = context return django_render(request, *args, **kwargs)
def render(request, template, options={}): dashboard = SiteOptions.get() f_code = sys._getframe(1).f_code dashboard.caller = f_code.co_name dashboard.filename = f_code.co_filename options['dashboard'] = dashboard options['year'] = datetime.date.today().year options['dice'] = random.choice([1,2,3,4,5,6]) return django_render(request, template, options)
def endorse_user(request, recipient_username): data = {} recipient = get_object_or_404(Profile, user__username=recipient_username) if recipient == request.profile: data['error'] = 'Logged profile and recipient are the same' return JsonResponse({'data': data}) try: endorsement = Endorsement.objects.get(endorser=request.profile, recipient=recipient) except Endorsement.DoesNotExist: endorsement = None if request.method == 'POST': if 'delete' in request.POST and endorsement: endorsement.delete() messages.info(request, MESSAGES['endorsement_deleted']) return HttpResponseRedirect( endorsement.recipient.get_absolute_url()) form = EndorseForm(request.POST, instance=endorsement, endorser=request.profile, recipient=recipient) if form.is_valid(): endorsement = form.save() create_notification(notifier=request.profile, recipient=recipient, type=Notification.TRUST) if form.cleaned_data['referral']: existing_referral = Referral.objects.filter( referrer=request.profile, recipient=recipient) if not existing_referral: new_referral = Referral() new_referral.referrer = request.profile new_referral.recipient = recipient new_referral.save() new_referral_count = FeedItem.objects.filter( item_type='profile', poster=recipient)[0].referral_count + 1 FeedItem.objects.filter(poster=recipient, item_type='profile').\ update(referral_count=new_referral_count) send_endorsement_notification(endorsement) messages.info(request, MESSAGES['endorsement_saved']) data['recipient'] = recipient_username data['stat'] = 'ok' return JsonResponse({'data': data}) else: data['stat'] = 'error' data['errors'] = form.errors return JsonResponse({'data': data}) else: form = EndorseForm(instance=endorsement, endorser=request.profile, recipient=recipient) profile = recipient # For profile_base.html. return django_render(request, 'frontend/home.html', {'form': form})
def render(request, template, context=None): context = context or {} context['pages'] = usercp.get_pages(request) for page in context['pages']: if page['is_active']: context['active_page'] = page break return django_render(request, template, context)
def render(request, template_name, additional=None): dictionary = { 'user': request.user, 'next': request.path, 'events': Event.objects.filter(dropdown=True), 'houses': HousePoints.current.all(), 'eligibility_list': Settings.objects.get_eligibility_list().url } if additional is not None: dictionary.update(additional) return django_render(request, template_name, dictionary)
def render(request, templateUrl, viewbag={}): #try: ad = get_ad() cfg = get_config() nav = get_navigation() return django_render(request, templateUrl, { 'ad': ad, 'cfg': cfg, 'nav': nav, 'viewbag': viewbag, })
def render(request, template, context=None, **kwargs): """ Same as django's render() shortcut, but with l10n template support. If used like this:: return l10n_utils.render(request, 'myapp/mytemplate.html') ... this helper will render the following template:: l10n/LANG/myapp/mytemplate.html if present, otherwise, it'll render the specified (en-US) template. """ context = {} if context is None else context # Every template gets its own .lang file, so figure out what it is # and pass it in the context context['langfile'] = get_lang_path(template) # Get the available translation list of the current page context['translations'] = get_translations(context['langfile']) # Look for localized template if not default lang. if hasattr(request, 'locale') and request.locale != settings.LANGUAGE_CODE: # redirect to default lang if locale not active if not (settings.DEV or lang_file_is_active(context['langfile'], request.locale)): return HttpResponseRedirect('/' + '/'.join([ settings.LANGUAGE_CODE, split_path(request.get_full_path())[1] ])) localized_tmpl = '%s/templates/%s' % (request.locale, template) try: return django_render(request, localized_tmpl, context, **kwargs) except TemplateDoesNotExist: # If not found, just go on and try rendering the parent template. pass return django_render(request, template, context, **kwargs)
def _view(request): if newrelic: # Name this in New Relic to differentiate pages newrelic.agent.set_transaction_name("mozorg.util.page:" + url_name.replace(".", "_")) kwargs.setdefault("urlname", url_name) # skip l10n if path exempt name_prefix = request.path_info.split("/", 2)[1] if name_prefix in settings.SUPPORTED_NONLOCALES: return django_render(request, tmpl, kwargs) return l10n_utils.render(request, tmpl, kwargs)
def decorated_func(request, *args, **kwargs): if self.template is None: self.template = '%s.html' % view_func.__name__ result = view_func(request, *args, **kwargs) if isinstance(result, tuple): result, self.template = result if isinstance(result, dict): response = django_render(request, self.template, result, **self.render_kwargs) else: response = result return response
def decorated_func(request, *args, **kwargs): if self.template is None: self.template = '%s.html' % view_func.__name__ result = view_func(request, *args, **kwargs) if isinstance(result, tuple): result, self.template = result if isinstance(result, dict): response = django_render( request, self.template, result, **self.render_kwargs) else: response = result return response
def render(request, template, context): request.frontend_context['PROFILE_PAGES'] = [] context['sections'] = user_profile.get_sections(request, context['profile']) for section in context['sections']: request.frontend_context['PROFILE_PAGES'].append({ 'name': unicode(section['name']), 'icon': section['icon'], 'meta': section.get('metadata'), 'component': section['component'], }) if section['is_active']: context['active_section'] = section if request.user.is_authenticated(): is_authenticated_user = context['profile'].pk == request.user.pk else: is_authenticated_user = False context['is_authenticated_user'] = is_authenticated_user user_acl = request.user.acl if request.user.is_authenticated(): if is_authenticated_user: context['show_email'] = True else: context['show_email'] = user_acl['can_see_users_emails'] else: context['show_email'] = False context['profile'].status = get_user_status(context['profile'], user_acl) if request.user.is_authenticated(): try: allow_message_user(request.user, context['profile']) context['can_message'] = True except PermissionDenied as e: context['can_message'] = False context['cant_message_reason'] = e request.frontend_context['PROFILE'] = UserProfileSerializer( context['profile'], context={ 'user': request.user }).data return django_render(request, template, context)
def undefined_contact(request, username=None): form = ContactForm() if request.method == 'POST' and not request.is_ajax(): form = ContactForm(request.POST) if form.is_valid(): profile = Profile.objects.get( user__username=form.cleaned_data['data_profile']) form.send(sender=request.profile, recipient=profile) messages.add_message(request, messages.SUCCESS, 'Successfully sent message') form = ContactForm() return django_render(request, 'contact.html', {'form': form}) elif request.method == 'POST' and request.is_ajax(): form = ContactForm(request.POST) if form.is_valid(): profile = Profile.objects.get( user__username=form.cleaned_data['contact_recipient_name']) form.send(sender=request.profile, recipient=profile) messages.add_message(request, messages.SUCCESS, 'Successfully sent message') return JsonResponse({'msg': 'Success'}) return django_render(request, 'contact.html', {'form': form})
def render_new(request, *args, **kwargs): """ Wraps django.shortcuts.render() to account for different templates based on the user agent as well as leveraging the API. """ httpresponse_kwargs = { 'content_type': kwargs.pop('content_type', None), 'status': kwargs.pop('status', None), } if request.REQUEST.get("api", "") == "json": pass return django_render(request. args, kwargs)
def render_new(request, *args, **kwargs): """ Wraps django.shortcuts.render() to account for different templates based on the user agent as well as leveraging the API. """ httpresponse_kwargs = { 'content_type': kwargs.pop('content_type', None), 'status': kwargs.pop('status', None), } if request.REQUEST.get("api", "") == "json": pass return django_render(request.args, kwargs)
def _view(request): if newrelic: # Name this in New Relic to differentiate pages newrelic.agent.set_transaction_name('mozorg.util.page:' + url_name.replace('.', '_')) kwargs.setdefault('urlname', url_name) # skip l10n if path exempt name_prefix = request.path_info.split('/', 2)[1] if name_prefix in settings.SUPPORTED_NONLOCALES: return django_render(request, tmpl, kwargs) return l10n_utils.render(request, tmpl, kwargs)
def render(request, template, context={}, **kwargs): """ Same as django's render() shortcut, but with l10n template support. If used like this:: return l10n_utils.render(request, 'myapp/mytemplate.html') ... this helper will render the following template:: l10n/LANG/myapp/mytemplate.html if present, otherwise, it'll render the specified (en-US) template. """ # Every template gets its own .lang file, so figure out what it is # and pass it in the context context['langfile'] = get_lang_path(template) # Look for localized template if not default lang. if request.locale != settings.LANGUAGE_CODE: # redirect to default lang if locale not active if not (settings.DEV or lang_file_is_active(context['langfile'], request.locale)): return HttpResponseRedirect('/' + '/'.join([ settings.LANGUAGE_CODE, split_path(request.get_full_path())[1] ])) localized_tmpl = '%s/templates/%s' % (request.locale, template) try: return django_render(request, localized_tmpl, context, **kwargs) except TemplateNotFound: # If not found, just go on and try rendering the parent template. pass return django_render(request, template, context, **kwargs)
def game_panel(request, game, player, turn): """ Game panel to resolve turn and start the game """ # If you are not the owner, you have nothing to do here # if game.owner != request.user: # raise Http404("Only the owner of a game can manage the game") # Set the game_id in session to always display all tabs request.session['gameid'] = game.pk if game.ended: ranking = PlayerPoints.objects.filter(player__game=game, turn=turn).order_by('-total_points') for pp in ranking: if pp.total_points == ranking[0].total_points: pp.win = True else: pp.win = False players = game.player_set.all() else: ranking = None players = game.player_set.all().annotate( numordre=Count(Case( When(order__turn=game.current_turn, then=1), delfault=0, output_field=IntegerField(), )) ).filter(numordre=0) if(request.GET.get('resolve_turn') and player.user == game.owner): game.resolve_current_turn() if(request.GET.get('start_game') and player.user == game.owner): game.start_game() if(request.GET.get('end_game') and player.user == game.owner): game.end_game() return django_render(request, 'game/game_panel.html', { "game": game, "request": request, "players": players, "pods": ['d_inc', 'current_player', 'players', ], "turn": game.current_turn, "player": player, "ranking": ranking, })
def render(*args, **kwargs): """ Wraps django.shortcuts.render, adding the proper 'sidebar_item' value to the template context """ predef_dict = {'sidebar_item': 'applicationprocess', 'form_status_choices': FormStatusChoices, 'application_status_choices': ApplicationStatusChoices, } if 'dictionary' in kwargs: kwargs['dictionary'].update(predef_dict) elif len(args) >= 3: args[2].update(predef_dict) else: kwargs['dictionary'] = predef_dict return django_render(*args, **kwargs)
def render(request, template, context): request.frontend_context['USERS_LISTS'] = [] context['pages'] = users_list.get_sections(request) for page in context['pages']: page['reversed_link'] = reverse(page['link']) request.frontend_context['USERS_LISTS'].append({ 'name': six.text_type(page['name']), 'component': page['component'], }) active_rank = context.get('rank') for rank in Rank.objects.filter(is_tab=True).order_by('order'): context['pages'].append({ 'name': rank.name, 'reversed_link': reverse('misago:users-rank', kwargs={ 'slug': rank.slug }), 'is_active': active_rank.pk == rank.pk if active_rank else None }) if rank.description: description = { 'plain': rank.description, 'html': format_plaintext_for_html(rank.description) } else: description = None request.frontend_context['USERS_LISTS'].append({ 'id': rank.pk, 'name': rank.name, 'slug': rank.slug, 'css_class': rank.css_class, 'description': description, 'component': 'rank', }) for page in context['pages']: if page['is_active']: context['active_page'] = page break return django_render(request, template, context)
def render(request, template, context): request.frontend_context['PROFILE_PAGES'] = [] context['sections'] = user_profile.get_sections(request, context['profile']) for section in context['sections']: request.frontend_context['PROFILE_PAGES'].append({ 'name': unicode(section['name']), 'icon': section['icon'], 'meta': section.get('metadata'), 'component': section['component'], }) if section['is_active']: context['active_section'] = section if request.user.is_authenticated(): is_authenticated_user = context['profile'].pk == request.user.pk else: is_authenticated_user = False context['is_authenticated_user'] = is_authenticated_user user_acl = request.user.acl if request.user.is_authenticated(): if is_authenticated_user: context['show_email'] = True else: context['show_email'] = user_acl['can_see_users_emails'] else: context['show_email'] = False context['profile'].status = get_user_status(context['profile'], user_acl) if request.user.is_authenticated(): try: allow_message_user(request.user, context['profile']) context['can_message'] = True except PermissionDenied as e: context['can_message'] = False context['cant_message_reason'] = e request.frontend_context['PROFILE'] = UserProfileSerializer( context['profile'], context={'user': request.user}).data return django_render(request, template, context)
def add_player(request, game_id): """ Join the game by adding a player """ # if gameid is not null, we display the menu. # We dont want to display the menu for creation but we want to display it for modification. game = Game.objects.get(pk=game_id) # If playeryer exists we will change it, else it's a creation try: player = Player.objects.select_related('game').get(user=request.user, game=game_id) except: player = None if request.method == 'POST': form = PlayerForm(request.POST, request.FILES, instance=player, game=game) if form.is_valid(): # We add the user and the game (they are not in the form) player = form.save(commit=False) player.user = request.user player.game = game player.save() form.save_m2m() return redirect('website.views.data.wallstreet', game_id=game_id) else: if player is None: # creation form form = PlayerForm(game=game) # We disable the game to hide the menu on this screen game = None else: # display game menu game = player.game # edit form form = PlayerForm(instance=player, game=game) return django_render(request, 'game/add_player.html', { "game_id": game_id, "form": form, "game": game, "request": request, "player": player })
def show_perm_table(request): if not request.user.is_staff: return HttpResponseForbidden() rules = RULES.keys() members_rules = MEMBERS_RULES.keys() print members_rules permissions = sorted(set( RULES["node_visibility_public"].keys() + MEMBERS_RULES[const.NODE_USER_ROLE_MANAGER].keys() )) _map = [ ('node_visibility_public', RULES), ('node_visibility_registered_users', RULES), ('user_loggedin', RULES), ('node_visibility_private', RULES), ('node_visibility_semiprivate', RULES), ('thread_external_access', RULES), ('member', MEMBERS_RULES), ('document-manager', MEMBERS_RULES), ('readonly', MEMBERS_RULES), ('manager', MEMBERS_RULES), ('thread_is_closed', RULES), ('node_qa_is_readonly', RULES), ('node_forum_is_readonly', RULES), ('node_library_is_readonly', RULES), ('node_is_closed', RULES), ('node_is_deleted', RULES), ] rules = [] for rule, data in _map: rules.append([rule, data[rule]]) to_tmpl = { "rules": rules, "permissions": permissions, } return django_render(request, 'admin/show_perm_table.html', to_tmpl)
def render(request, template, context): context['pages'] = users_list.get_pages(request) for page in context['pages']: page['reversed_link'] = reverse(page['link']) active_rank = context.get('rank') for rank in Rank.objects.filter(is_tab=True).order_by('order'): context['pages'].append({ 'name': rank.name, 'reversed_link': reverse('misago:users_rank', kwargs={'rank_slug': rank.slug}), 'is_active': active_rank.pk == rank.pk if active_rank else None }) for page in context['pages']: if page['is_active']: context['active_page'] = page break return django_render(request, template, context)
def render(request, template, context): context["pages"] = users_list.get_pages(request) for page in context["pages"]: page["reversed_link"] = reverse(page["link"]) active_rank = context.get("rank") for rank in Rank.objects.filter(is_tab=True).order_by("order"): context["pages"].append( { "name": rank.name, "reversed_link": reverse("misago:users_rank", kwargs={"rank_slug": rank.slug}), "is_active": active_rank.pk == rank.pk if active_rank else None, } ) for page in context["pages"]: if page["is_active"]: context["active_page"] = page break return django_render(request, template, context)