Ejemplo n.º 1
0
def show_photo_duplicates(request):
    from utils.paginator import HandyPaginator

    groups = Photo.find_ads_duplicates()
    paginator = HandyPaginator(groups, 10, request=request)

    groups = paginator.current_page.object_list
    for group in groups:
        group['photos'] = Photo.objects.filter(hash__in=group['hashes']).order_by('hash').distinct('hash')
        group['ads'] = Ad.objects.filter(user__isnull=False, pk__in=group['ad_ids']).order_by('user', 'created').select_related('user', 'region')

    return render(request, "admin/ad/show_photo_duplicates.html", {'paginator': paginator, 'groups': groups})
Ejemplo n.º 2
0
def category_list(request, category):
    if category == 'news':
        categories = settings.NEWS_CATEGORIES
    else:
        categories = (category, )
    articles = Article.objects.filter(
        category__in=categories, visible=True).filter(
            Q(subdomains=request.subdomain_region)
            | Q(subdomains__isnull=True))
    paginator = HandyPaginator(articles, 16, request=request)

    title, description = get_meta_for_guide(request.subdomain_region, category)
    return render(request, 'guide/category_list.jinja.html', locals())
Ejemplo n.º 3
0
def category_list(request):
    category = 'school'
    articles = Article.objects.filter(category=category, visible=True).filter(
        Q(subdomains=request.subdomain_region) | Q(subdomains__isnull=True))
    paginator = HandyPaginator(articles, 16, request=request)

    title = _(u"Полезные статьи от портала недвижимости Mesto.ua")
    description = _(
        u"Полезные статьи о рынке недвижимости Украины. Новые методы продаж,\
                      что работает в 2017 году, актуальные кейсы от портала Mesto.ua"
    )

    return render(request, 'guide/category_list.jinja.html', locals())
Ejemplo n.º 4
0
def agency_realtors(request, agency_id):
    try:
        agency = get_public_agencies().get(id=agency_id)
    except Agency.DoesNotExist:
        raise Http404

    realtors = agency.realtors.filter(is_active=True,
                                      is_admin=False).prefetch_related(
                                          'user', 'agency', 'user__phones')
    paginator = HandyPaginator(realtors, 16, request=request)

    return render(request, 'professionals/agency_realtors.jinja.html',
                  locals())
Ejemplo n.º 5
0
def inbox(request, outbox=False):
    condition = Q(from_user=request.user) | Q(to_user=request.user)
    sended_message_lists = Q(
        from_user=request.user,
        message_list__isnull=False) & ~Q(to_user=request.user)

    if request.GET.get('filter') == 'unreaded':
        condition.add(Q(readed=False) & Q(to_user=request.user), Q.AND)

    # группируем по диалогам (root_message у группы сообщений одинаковый)
    dialogs = Message.objects.filter(condition).exclude(sended_message_lists)\
        .values("root_message").annotate(count=Count('id'), id=Max('id'))

    counters = dict((message['id'], message['count']) for message in dialogs)

    user_messages = Message.objects.filter(
        id__in=counters.keys()).exclude(sended_message_lists).order_by('-time')

    # архив
    if request.GET.get('filter') == 'deleted':
        user_messages = user_messages.filter(
            root_message__hidden_for_user=request.user)
        archive = True
    else:
        user_messages = user_messages.exclude(
            root_message__hidden_for_user=request.user)

    for message in user_messages:
        message.replies = counters[message.id] - 1

    if 'delete-this' in request.GET or 'delete-selected' in request.GET:
        message_ids = [] + request.GET.getlist('delete-this')
        if 'delete-selected' in request.GET:
            message_ids += request.GET.getlist('delete')

        root_messages_to_delete = Message.objects.filter(id__in=message_ids)
        for message in root_messages_to_delete:
            message.hidden_for_user.add(request.user)

        # обновим счетчик новых сообщений
        cache.delete('new_messages_for_user%d' % request.user.id)

        return redirect('.')

    paginator = HandyPaginator(user_messages, 10, request=request)

    title = _(u'Отправленные сообщения') if outbox else _(
        u'Входяшие сообщения')
    return render(request, 'profile/messages/list.jinja.html', locals())
Ejemplo n.º 6
0
def agency_reviews(request, agency_id):
    try:
        agency = get_public_agencies().get(id=agency_id)
    except Agency.DoesNotExist:
        raise Http404

    if request.user.is_authenticated():
        request_user_is_agency_realtor = agency.realtors.filter(
            is_active=True, user=request.user).exists()

    review_form = ReviewForm()
    reply_form = ReplyForm()

    if request.method == 'POST':
        if request.user.is_anonymous():
            raise Exception('Anonymous user can`t post reviews or replies')

        if 'review' in request.POST:
            review_to_reply = agency.reviews.get(id=request.POST.get('review'))
            reply_form = ReplyForm(request.POST,
                                   instance=Reply(user=request.user,
                                                  review=review_to_reply))

            if reply_form.is_valid():
                reply_form.save()
                return redirect(request.get_full_path())

        else:
            if request_user_is_agency_realtor:
                raise Exception('Realtors can`t post reviews on its agency')

            review_form = ReviewForm(request.POST,
                                     instance=Review(agency=agency,
                                                     user=request.user))

            if review_form.is_valid():
                review_form.save()
                return redirect(request.path)

    reviews = agency.reviews.prefetch_related('user', 'replies',
                                              'replies__user')
    paginator = HandyPaginator(reviews, 15, request=request)

    is_agency = True
    return render(request, 'professionals/agency_reviews.jinja.html', locals())
Ejemplo n.º 7
0
def agency_profile(request, agency_id):
    try:
        agency = get_public_agencies().get(id=agency_id)
    except Agency.DoesNotExist:
        raise Http404

    agency_ads = Ad.objects.filter(
        is_published=True,
        user__in=set(
            agency.users.filter(realtors__is_active=True).values_list(
                'id', flat=True))  # todo проверить
    ).prefetch_related('photos', 'region').order_by('-vip_type')
    agency_ads_count = agency_ads.count()

    # выбор основных типов сделки объявлений
    deal_types = [
        (deal_type, dict(DEAL_TYPE_CHOICES)[deal_type])
        for deal_type, cnt in collections.Counter(
            agency_ads.values_list('deal_type', flat=True)).most_common(4)
    ]

    # фильтруем по типу сделки
    if deal_types:
        agency_ads = agency_ads.filter(
            deal_type=request.GET.get('deal_type', deal_types[0][0]))

    paginator = HandyPaginator(agency_ads, 4, request=request)

    realtor = agency.realtors.get(is_admin=True)

    reviews_stat = agency.reviews.aggregate(avg_rating=Avg('rating'),
                                            count=Count('id'))

    is_agency = True
    contacts_link = reverse('professionals:agency_contacts', args=[agency.id])

    # seo-корректировки за январь 2016 для раздела профессионалы
    title, description = meta_tags.get_professionals_agency_metatags(
        request.subdomain_region, agency)

    return render(request, 'professionals/profile.jinja.html', locals())
Ejemplo n.º 8
0
def search(request, professional_type=None):
    normalized_url = build_normalized_search_url(request, professional_type)
    if normalized_url != request.build_absolute_uri():
        return HttpResponsePermanentRedirect(normalized_url)

    query_dict = request.GET.copy()
    if request.subdomain_region.kind == 'locality' and not request.GET.get(
            'city'):
        query_dict['city'] = request.subdomain_region.id

    form = ProfessionalForm(query_dict)

    if form.is_valid():
        # .filter(...).filter(...) или exclude() приводят к дополнительным JOIN, поэтому фильтр общий
        # TODO возможно имеет смысл расписать get_public_agencies через фильтры

        search = form.cleaned_data['search']

        agency_q = Q(
            Q(agency__name__icontains=search) if search else Q(),
            agency__logo__gt='',
            is_admin=True,
        )

        realtor_q = Q(
            is_admin=False,
            user__in=User.objects.filter(
                (Q(first_name__icontains=search)
                 | Q(last_name__icontains=search)) if search else Q(),
                image__gt='',
                ads_count__gt=0,
            ),
        )

        if professional_type == 'agency':
            type_q = agency_q
        elif professional_type == 'realtor':
            type_q = realtor_q
        else:
            type_q = agency_q | realtor_q

        deal_type = form.cleaned_data['deal_type']
        city = form.cleaned_data['city']

        realtors = Realtor.objects.filter(
            type_q,
            agency__in=get_public_agencies().filter(
                Q(deal_types=deal_type) if deal_type else Q(),
                Q(city=city) if city else Q(),
            )).select_related('user').order_by(
                '-user__last_action').prefetch_related(
                    Prefetch('agency',
                             queryset=Agency.objects.annotate(
                                 reviews_count=Count('reviews'),
                                 avg_rating=Avg('reviews__rating'))),
                    'agency__city',
                    'user__phones',
                )

    else:
        realtors = Realtor.objects.none()

    paginator = HandyPaginator(realtors, 16, request=request)

    title, description = meta_tags.get_professionals_search_metatags(
        request.subdomain_region, professional_type)
    seo_text_block = TextBlock.find_by_request(request,
                                               request.subdomain_region)

    return render(request, 'professionals/search.jinja.html', locals())
Ejemplo n.º 9
0
def index(request, type):
    """
    Список вебинаров
    """

    now_date = datetime.datetime.now()

    # Список ближайших 4 вебинаров / семинаров
    future_webinars = Webinar.objects.filter(type=type,
                                             finish_at__gt=now_date,
                                             is_published=True)[:4]

    # Список архивных вебинаров / семинаров
    archived_webinars = Webinar.objects.filter(
        type=type, finish_at__lt=now_date,
        is_published=True).order_by('-start_at')

    # Проверяем незаполненные архивные вебинары
    if type == 'webinar':
        for archived_webinar in archived_webinars:
            checks = [
                not archived_webinar.youtube_duration,
                not archived_webinar.youtube_image
            ]
            if any(checks):
                gapi = GoogleAPI()
                try:
                    video_info = gapi.youtube_get_video_info(
                        embed=archived_webinar.video)
                    archived_webinar.youtube_image = video_info[
                        'thumbnail_url']
                    archived_webinar.youtube_duration = video_info['duration']
                    archived_webinar.save()
                    archived_webinar.skip = False
                except:
                    archived_webinar.skip = True

            else:
                archived_webinar.skip = False

        # Добавляем проверку, что у нас рабочий EMBED стоит
        archived_webinars = filter(lambda a: not a.skip, archived_webinars)

    archived_webinars_paginator = HandyPaginator(archived_webinars,
                                                 12,
                                                 request=request)

    type_display = _(u'вебинары') if type == 'webinar' else _(u'семинары')
    title = _(u'%s - портал недвижимости Mesto.ua') % type_display.capitalize()
    descriptions = {
        'webinar':
        _(u"Вебинар для риэлторов от портала Mesto.ua. Подробные видео уроки \
                        про эффективные продажи недвижимости: работающие методы от практиков"
          ),
        'seminar':
        _(u"Обучающие семинары по продаже недвижимости от портала Mesto.ua. Эффективные \
                        методы, готовые и работающие кейсы от ведущих риелторов Украины"
          )
    }
    description = descriptions[
        'webinar'] if type == 'webinar' else descriptions['seminar']

    return render(request, 'webinars/index.jinja.html', locals())
Ejemplo n.º 10
0
def search(request, deal_type, property_type, regions_slug=None, show_result=None):
    region  = Region.get_region_from_slug(regions_slug, '' if request.subdomain == 'bank' else request.subdomain, request.subdomain_region)
    if not region:
        raise Http404
    
    # весь список объявлений с указанном типом объявления
    items_list = Ad.objects.filter(bank__isnull=False, is_published=True, deal_type__in=deal_type.split(',')).exclude(get_exclude_rules())\
        .prefetch_related('region','photos','user')

    # применяем фильтр по регионам
    items_list = items_list.filter(region__in=region.get_descendants(True))

    ad_property_types = convert_to_ad(property_type)
    items_list = items_list.filter(property_type__in=ad_property_types)
    
    min_price, max_price = get_price_range('%s_%s_%s_bank' % (deal_type, property_type, region.pk), items_list)
    
    # применяем фильтры поиска
    if len(request.GET) > 0:
        form = PropertySearchForm(request.GET) # A form bound to the POST data
        
        if form.is_valid():
            if not (len(request.GET)== 1 and 'property_type' in request.GET):
                show_result = True
            
            # currency rate
            curr_rate = 1
            if ('currency' in form.cleaned_data and form.cleaned_data['currency'] and form.cleaned_data['currency'] != 'UAH') and ((form.cleaned_data['price_from'] > 0) or (form.cleaned_data['price_to'] > 0)):
                from utils.currency import get_currency_rates
                curr_rate = get_currency_rates()[form.cleaned_data['currency']]
                
            if form.cleaned_data['price_from'] > 0:
                items_list = items_list.filter(price_uah__gte=form.cleaned_data['price_from'] * curr_rate)
            if form.cleaned_data['price_to'] > 0:
                items_list = items_list.filter(price_uah__lte=form.cleaned_data['price_to'] * curr_rate)
            
            if form.cleaned_data['rooms']:
                Q_rooms = Q()
                for room in form.cleaned_data['rooms']:
                    if room.find('+') > 0:
                        Q_rooms = Q_rooms | Q(rooms__gte=room[:-1])
                    else:
                        Q_rooms = Q_rooms | Q(rooms=room)
                items_list = items_list.filter(Q_rooms)
                
            if form.cleaned_data['property_commercial_type']:
                items_list = items_list.filter(property_commercial_type=form.cleaned_data['property_commercial_type'])
            
            if form.cleaned_data['with_image'] > 0:
                items_list = items_list.filter(has_photos=True)
                
            if form.cleaned_data['without_commission'] > 0:
                items_list = items_list.filter(without_commission=True)

            if form.cleaned_data['sort']:
                items_list = items_list.order_by(form.cleaned_data['sort'])
                
            # ключевые слова
            if form.cleaned_data['keywords'] != '':
                keywords = form.cleaned_data['keywords'].split(',')
                criterions = Q()
                for keyword in keywords:
                    keyword = keyword.strip()
                    selected_region = _check_region_subdomain(keyword)
                    if type(selected_region) == Region:
                        if selected_region != region:
                            kwargs = {'property_type': property_type}
                            region_slug = selected_region.get_region_slug()
                            if region_slug:
                                kwargs['regions_slug'] = region_slug
                            url = selected_region.get_host_url('bank-ad-search-result', host='bank', kwargs=kwargs)
                            return HttpResponsePermanentRedirect(url)
                    criterions.add(Q(description__icontains=keyword) | Q(address__icontains=keyword), Q.AND)
                items_list = items_list.filter(criterions)
            
    else:
        try:
            # в __init__ подготовка списка регионов для формы
            form = PropertySearchForm(request.GET)
        except Region.DoesNotExist: # не найден активный регион в выпадающем списке
            return redirect('..')
    
    if not show_result:
        items_list = items_list.filter(has_photos=True).order_by('-updated')
        items_list = items_list[:4]
    else:
        pass

    items_list = items_list.prefetch_related('photos')

    paginator = HandyPaginator(items_list, 10, request=request)

    seo_klass = SEO(current_language=settings.LANGUAGE_CODE)
    seo = seo_klass.get_seo(
        region=region,
        deal_type=deal_type,
        property_type=ad_property_types[0],
    )

    return render(request, 'bank/search.html', locals())
Ejemplo n.º 11
0
def bank_list(request):
    bank_list = Bank.objects.filter(is_active=True)
    paginator = HandyPaginator(bank_list, 4, request=request)
    title = u'Список банков'
    return render(request, 'bank/bank_list.html', locals())
Ejemplo n.º 12
0
def realtors(request):
    title = _(u'Риелторы агентства')
    agency = request.own_agency
    if not agency:
        raise Http404

    # клик по кнопке "Показать статистику"
    if 'show-stats' in request.GET:
        return HttpResponseRedirect(
            reverse('agency_admin:stats') + '?%s' %
            urllib.urlencode({'realtor': request.GET.getlist('realtor')}, True)
        )

    if request.method == 'POST':
        add_form = AddRealtorForm(request.POST, request.FILES, agency=agency)
        if add_form.is_valid():
            with db_transaction.atomic():
                agency_realtor = Realtor.objects.filter(
                    is_admin=True, user=request.user).get()

                try:
                    user = User.objects.get(
                        email__iexact=add_form.cleaned_data['email'])
                except User.DoesNotExist:
                    user = add_form.save(commit=False)
                    user.username = User.make_unique_username(
                        add_form.cleaned_data['email'])
                    password = ''.join(
                        random.choice(string.digits) for i in xrange(8))
                    user.set_password(password)
                    user.save()
                    phone, created = Phone.objects.get_or_create(
                        number=add_form.cleaned_data['phone'])
                    UserPhone(user=user, phone=phone, order=1).save()
                else:
                    password = None

                new_realtor = Realtor(agency=agency_realtor.agency,
                                      user=user,
                                      is_active=False,
                                      confirmation_key=uuid.uuid4().hex)
                new_realtor.save()
                new_realtor.send_mail(password)
                new_realtor.send_message()

            add_form = AddRealtorForm(agency=agency)
            messages.info(
                request,
                _(u'Рилетор добавлен.<br/>Риелтору отправлено личное сообщений с ссылкой для подтверждения'
                  ),
                extra_tags='modal-dialog-w400 modal-success')
            return HttpResponseRedirect(reverse('agency_admin:realtors'))
        else:
            add_form.set_required()

    else:
        add_form = AddRealtorForm(agency=agency)
        add_form.set_required()

    # удаляем неугодных
    if 'delete' in request.GET:
        agency.realtors.filter(pk=request.GET['delete']).delete()

    # риелторы агентства
    realtors = agency.realtors.prefetch_related('user__phones').order_by(
        '-is_admin', 'pk')

    form = RieltorFilterForm(request.GET)
    if form.is_valid():
        if form.cleaned_data['search']:
            q = form.cleaned_data['search']
            search_filter = Q(user__first_name__icontains=q) | Q(
                user__last_name__icontains=q) | Q(user__email__icontains=q)
            realtors = realtors.filter(search_filter)

    paginator = HandyPaginator(realtors, 5, request=request)

    # статистика просмотров и входов
    for i, realtor in enumerate(paginator.current_page.object_list):
        try:
            paginator.current_page.object_list[i].stats = Stat.objects.filter(user=realtor.user).order_by().values('user')\
                .annotate(ad_views=Sum('ad_views'), ad_contacts_views=Sum('ad_contacts_views'), entrances=Sum('entrances'))[0]
        except IndexError:
            paginator.current_page.object_list[i].stats = None

    return render(request, 'agency/realtors.jinja.html', locals())
Ejemplo n.º 13
0
def saved_properties(request):
    items_list = SavedAd.objects.filter(user=request.user).order_by('-created')
    paginator = HandyPaginator(items_list, 10, request=request)
    title = _(u'Сохраненные объявления')
    return render(request, 'profile/saved_properties.jinja.html', locals())
Ejemplo n.º 14
0
def my_properties(request, agency_realtors=None):
    # возможность подглядывать в личные кабинеты пользователей
    if request.user.is_staff and request.GET.get('override_user'):
        from custom_user.models import User
        request.user = User.objects.get(pk=request.GET.get('override_user'))

    # временное исключение для юзера. который не хочет видить объявления риелторов у себя в кабине
    if request.user.id == 114818:
        items_list = Ad.objects.filter(user=request.user).exclude(status=211)
    else:
        items_list = Ad.objects.filter(
            user__in=request.user.get_owned_users(request)).exclude(status=211)

    ads_groups_counts = {
        'active': 0,
        'inactive': 0,
        'rejected': 0,
        'vip': 0,
        'import': 0,
        '': 0,
    }
    for values in items_list.values(
            'vip_type', 'status', 'moderation_status',
            'xml_id').order_by().annotate(count=Count('id')):
        ads_groups_counts[''] += values['count']

        if values['moderation_status']:
            ads_groups_counts['rejected'] += values['count']
        elif values['status'] == 1:
            ads_groups_counts['active'] += values['count']
        elif values['status'] == 210:
            ads_groups_counts['inactive'] += values['count']

        if values['vip_type']:
            ads_groups_counts['vip'] += values['count']

        if values['xml_id']:
            ads_groups_counts['import'] += values['count']

    # TODO: может вообще сделать только по -id сортировку?
    items_list = items_list.select_related(
        'user',
        'region').prefetch_related('photos').order_by('-updated', '-pk')

    class FilterForm(forms.Form):
        status = forms.ChoiceField(required=False,
                                   choices=(
                                       ('', _(u'Все объявления')),
                                       ('active', _(u'Активные')),
                                       ('inactive', _(u'Неактивные')),
                                       ('vip', _(u'VIP')),
                                       ('rejected', _(u'Отклоненные')),
                                       ('import', _(u'Импорт')),
                                   ))
        deal_type = forms.ChoiceField(
            required=False,
            choices=(
                ('', _(u'Все типы сделки')),
                ('sale', _(u'Продажа')),
                ('rent', _(u'Долгосрочная аренда')),
                ('rent_daily', _(u'Посуточно')),
                # ('newhomes', _(u'Новостройка')),
            ))
        property_type = forms.ChoiceField(required=False,
                                          choices=(
                                              ('', _(u'Вся недвижимость')),
                                              ('flat', _(u'Квартира')),
                                              ('room', _(u'Комната')),
                                              ('house', _(u'Дом')),
                                              ('plot', _(u'Участок')),
                                              ('commercial',
                                               _(u'Коммерческая')),
                                              ('garages', _(u'Гаражи')),
                                          ))
        search = forms.CharField(required=False)

    filter_form = FilterForm(request.GET)
    if not filter_form.is_valid():
        redirect(reverse('profile_my_properties'))

    # Статус объявления
    status = filter_form.cleaned_data['status']

    if status == 'rejected':
        items_list = items_list.filter(moderation_status__isnull=False)
    elif status == 'active':
        items_list = items_list.filter(status=1)
    elif status == 'inactive':
        items_list = items_list.filter(status=210)
    elif status == 'vip':
        items_list = items_list.filter(pk__in=VipPlacement.objects.filter(
            is_active=True).values('basead'))
    elif status == 'import':
        items_list = items_list.exclude(xml_id=None)

    # Тип сделки
    deal_type = filter_form.cleaned_data['deal_type']
    if deal_type:
        items_list = items_list.filter(deal_type=deal_type)

    # Тип недвижимости
    property_type = filter_form.cleaned_data['property_type']
    if property_type:
        items_list = items_list.filter(property_type=property_type)

    search = filter_form.cleaned_data['search'].strip()
    if search:
        if search.isdigit():
            items_list = items_list.filter(id=search)

            # при поиске по ID сбрасываются другие фильтры
            filter_form = FilterForm({'search': search})
            # в шаблонах используется cleaned_data
            filter_form.is_valid()
        else:
            items_list = items_list.filter(address__icontains=search)

    paginator = HandyPaginator(items_list,
                               10,
                               request=request,
                               per_page_variants=[5, 10, 20, 50])

    views_by_ad = get_views_for_ads(paginator.current_page.object_list)

    from ad.choices import DEACTIVATION_REASON_CHOICES

    vips = {}
    for vip in VipPlacement.objects.filter(
            is_active=True,
            basead__ad__user__in=request.user.get_owned_users(request)):
        vips[vip.basead_id] = vip

    title = _(u'Мои объявления')
    template = 'profile/my_properties.jinja.html' if not request.own_agency else 'agency/agency_ads.jinja.html'
    return render(request, template, locals())
Ejemplo n.º 15
0
def my_buildings(request):
    """
    Профиль застройщика: Мои новостройки
    """

    if request.user.has_perm('newhome.newhome_admin'):
        newhomes = Newhome.objects.all().order_by('-modified', '-created')

    else:
        newhomes = Newhome.objects.filter(user=request.user).exclude(
            status=211).order_by('-modified', '-created')

    newhomes = newhomes.prefetch_related(
        'priority_phones', 'newhome_photos').select_related('region')

    # Выставляем изменнеый почтовый ящик по работе с заявками на конкретную новостройку
    if request.method == 'POST':
        action = request.POST.get('action', '')
        accept_actions = ['email', 'remove', 'activate', 'deactivate']

        if action in accept_actions:
            for newhome in newhomes.filter(
                    pk__in=request.POST.getlist('newhome[]')):
                if action == 'email':
                    # Меняем email / телефон ответственного лица
                    newhome.priority_email = request.POST.get(
                        u'email-{:d}'.format(newhome.pk))
                    newhome.save()

                    phones = request.POST.getlist(u'phone-{:d}[]'.format(
                        newhome.pk))
                    if phones:
                        newhome.priority_phones.clear()
                        for phone in phones:
                            if phone.strip('+'):
                                phone, created = Phone.objects.get_or_create(
                                    number=phone.strip('+'))
                                newhome.priority_phones.add(phone)

                    messages.success(
                        request, _(u'Контактные данные по объекту обновлены'))

                elif action == 'activate':
                    # Активируем новостройку
                    if newhome.moderation_status and not newhome.fields_for_moderation:
                        messages.error(
                            request,
                            _(u'Пожалуйста, исправьте замечания перед активации объекта'
                              ))

                    elif newhome.user.get_balance() > get_lead_price(
                            'callrequest', 'newhomes', 'high'):
                        newhome.status = 1
                        newhome.is_published = True
                        newhome.save(
                        )  # Включение лидогенерации проходит в сигналах

                        messages.success(request,
                                         _(u'Объект успешно активирован'))

                    else:
                        messages.error(
                            request,
                            _(u'Не хватает средств для активации объекта'))

                elif action == 'deactivate':
                    # Деактивируем новостройку
                    newhome.status = 210
                    newhome.is_published = False
                    newhome.save()
                    messages.success(request,
                                     _(u'Объект успешно деактивирован'))

                elif action == 'remove':
                    # Удаляем новостройку
                    newhome.status = 211
                    newhome.is_published = False
                    newhome.save()
                    messages.success(request, _(u'Объект успешно удален'))

        return HttpResponseRedirect(
            request.META.get('HTTP_REFERER',
                             reverse('profile_newhome_my_buildings')))

    # Фильтруем объявления
    filter_form = NewhomeFilterForm(request.GET)

    if not filter_form.is_valid():
        return HttpResponseRedirect(reverse('profile_newhome_my_buildings'))

    # Статус объявления
    status = filter_form.cleaned_data['status']

    if status == 'active':
        ads_list = Newhome.objects.filter(pk__in=newhomes.values_list(
            'pk', flat=True),
                                          status=1).values_list('pk',
                                                                flat=True)
        newhomes = newhomes.filter(pk__in=ads_list)

    elif status == 'inactive':
        ads_list = Newhome.objects.filter(pk__in=newhomes.values_list(
            'pk', flat=True),
                                          status=210).values_list('pk',
                                                                  flat=True)
        newhomes = newhomes.filter(pk__in=ads_list)

    elif status == 'removed':
        ads_list = Newhome.objects.filter(pk__in=newhomes.values_list(
            'pk', flat=True),
                                          status=211).values_list('pk',
                                                                  flat=True)
        newhomes = newhomes.filter(pk__in=ads_list)

    # Поисковая строка
    search = filter_form.cleaned_data['search'].strip()
    if search:
        newhomes_filter = Q()

        # Фильтр по названию
        newhomes_filter |= Q(name__icontains=search)

        # Фильтр по владельцу (email)
        newhomes_filter |= Q(user__email__icontains=search)

        # Фильтр по ответственному за объект
        newhomes_filter |= Q(priority_email__icontains=search)

        newhomes = newhomes.filter(newhomes_filter)

    # Включаем пагинацию
    paginator = HandyPaginator(newhomes,
                               10,
                               request=request,
                               per_page_variants=[5, 10, 20, 50])

    return render(request, 'newhome/cabinet/my-buildings.jinja.html', locals())