Source

botanic_apartments / catalogue / utils.py

Full commit
# -*- coding: utf-8 -*-
from catalogue import models
from django.db.models import BLANK_CHOICE_DASH
from django.db.models import Q
from django.db.models.aggregates import Count
from django.forms.fields import ChoiceField
from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _
from django_utils.functions import import_object_from_package

def search_apartment(conditions, search_form=None):
    qs = models.Apartment.objects.filter( ** conditions)
    if search_form is not None and hasattr(search_form, '_bonus_fields'):
        bonuses = Q()
        for name, field in search_form._bonus_fields.items():
            value = search_form.cleaned_data.pop(name, None)
            if value is not None:
                if value is True: value = '1'
                if value is False: value = '0'
                bonuses |= Q(bonus_type=field.bonus_type, value=value)
        bonus_qs = models.Bonus.objects.filter(bonuses)
        bonus_qs = bonus_qs.values('apartment').annotate(num_apartments=Count('apartment')).order_by()
        bonus_qs = bonus_qs.filter(num_apartments=len(bonuses))
        bonus_apartments = bonus_qs.values_list('apartment', flat=True)
        qs = qs.filter(pk__in=bonus_apartments)
    return qs

def build_bonus_field(bonus_type, orig_field=None, override={}, exclude=[], add_empty_choice=False):
    defaults = {}
    defaults['label'] = getattr(orig_field, 'label', None) or _(bonus_type.name).capitalize()
    field_str = smart_str(bonus_type.field)
    field_module, field_class = import_object_from_package(field_str)
    if orig_field:
        for f in ['required', 'widget', 'initial']:
            if f not in exclude:
                defaults[f] = getattr(orig_field, f, None)
    if issubclass(field_class, ChoiceField):
        options = bonus_type.options.split(models.BONUS_CHOICE_DELIMATER)
        choices = list(BLANK_CHOICE_DASH) if add_empty_choice else []
        choices += [(i.strip(), _(i.strip())) for i in options]
        defaults['choices'] = choices
    defaults.update(override)
    field = field_class(** defaults)
    return field

def set_currency(response, currency):
    return response.set_cookie('botanic_currency', currency, 7*24*60*60)
def get_currency(request):
    return request.COOKIES.get('botanic_currency', 'uah')
def delete_currency(response):
    return response.delete_cookie('botanic_currency')