Ejemplo n.º 1
0
def my_payments(request):
	context = user_edit_vars(request.user)
	context['page_title'] = u'Все Ваши платежи'
	context['payments'] = request.user.payment_moneta_set.select_related('response').order_by('-added_time')
	if not context['is_admin']:
		context['payments'] = context['payments'].filter(is_active=True)
	return render(request, "payment/my_payments.html", context)
Ejemplo n.º 2
0
def result_details(request, result_id=None):
    result = get_object_or_404(models.Result, pk=result_id)
    race = result.race
    event = race.event
    user = request.user
    context = user_edit_vars(user, series=event.series)
    context['page_title'] = u'{}: {} на забеге {}, {}'.format(
        result.strName(), result, event.name, event.dateFull())
    context['result'] = result
    context['race'] = race
    context['event'] = event
    context['series'] = event.series
    context['splits'] = result.split_set.select_related('distance').order_by(
        'distance__length')
    context['splits_exist'] = context['splits'].exists()
    context['races'] = views_race.event_races_for_context(event)

    if result.runner and result.runner.user:
        documents = models.Document.objects.filter(
            event=event, created_by=result.runner.user)
        context['reviews'] = documents.filter(
            document_type=models.DOC_TYPE_IMPRESSIONS).order_by('date_posted')
        context['photos'] = documents.filter(
            document_type=models.DOC_TYPE_PHOTOS).order_by('date_posted')
    return render(request, 'results/result_details.html', context)
Ejemplo n.º 3
0
def klb_make_individual_payment(request, year):
	context = user_edit_vars(request.user)
	year = models.int_safe(year)
	if not models.is_active_klb_year(year, context['is_admin']):
		messages.warning(request, u'Сейчас нельзя заявиться в КЛБМатч–{}'.format(year))
		return redirect(reverse('results:klb_match_summary', kwargs={'year': year}))
	participant = models.Klb_participant.objects.filter(klb_person__runner__user_id=request.user.id, match_year=year).first()
	if not participant:
		messages.warning(request, u'Вы ещё не заявлены в КЛБМатч–{}'.format(year))
		return redirect(reverse('results:klb_application', kwargs={'year': year}))
	person = participant.klb_person
	if participant.paid_status != models.PAID_STATUS_NO:
		messages.warning(request, u'Вы уже оплатили участие в КЛБМатче–{}'.format(year))
		return redirect(person)
	if participant.team and not participant.team.club.members_can_pay_themselves:
		messages.warning(request, u'Ваше участие в КЛБМатче может оплатить только капитан команды «{}»; Вам достаточно передать деньги ему.'.format(
			participant.team.name))
		return redirect(person)
	payment = models.Payment_moneta.objects.create(
		amount=models_klb.get_participation_price(year),
		description=u'Оплата за себя: {} {}'.format(person.fname, person.lname),
		user=request.user,
		sender=request.user.get_full_name(),
	)
	payment.refresh_from_db()
	payment.transaction_id = DESCRIPTION_PREFIX + unicode(payment.id)
	payment.signature = get_payment_md5(payment)
	payment.save()

	participant.payment = payment
	participant.save()
	models.write_log('klb_make_individual_payment: Redirecting to {}'.format(get_redirect_url(payment)))
	return redirect(get_redirect_url(payment))
Ejemplo n.º 4
0
def fail(request):
	context = user_edit_vars(request.user)
	payment = None
	transaction_id = request.GET.get('MNT_TRANSACTION_ID')
	if transaction_id:
		context['payment'] = models.Payment_moneta.objects.filter(transaction_id=transaction_id, user=request.user).first()
	context['user_has_payments'] = request.user.payment_moneta_set.exists()
	context['page_title'] = u'Платёж не прошёл'
	return render(request, "payment/fail.html", context)
Ejemplo n.º 5
0
def news_details(request, news_id=None):
    news = get_object_or_404(models.News, pk=news_id)
    context = user_edit_vars(request.user)
    context['news'] = news
    context['page_title'] = news.title
    if context['is_admin']:
        context['social_pages'] = models.Social_page.objects.filter(
            district__isnull=True)
        # context['posts'] = models.Social_news_post.objects.filter(news=news).order_by('-date_posted')
    else:
        news.n_views += 1
        news.save()
    return render(request, 'results/news_details.html', context)
Ejemplo n.º 6
0
def make_payment(request, payment_id):
	payment = get_object_or_404(models.Payment_moneta, pk=payment_id, is_active=True)
	context = user_edit_vars(request.user)
	if (payment.user_id != request.user.id) and not context['is_admin']:
		messages.warning(request, u'Заказ с номером {} — не Ваш. Оплатить его может только его создатель.'.format(payment.transaction_id))
		return redirect('results:my_payments')
	if payment.is_paid:
		messages.success(request, u'Заказ с номером {} на сумму {} ₽ уже оплачен'.format(payment.transaction_id, payment.amount))
		return redirect('results:my_payments')
	if payment.is_dummy:
		messages.success(request, u'Заказ с номером {} — ненастоящий. Не нужно его оплачивать.'.format(payment.transaction_id))
		return redirect('results:my_payments')
	return redirect(get_redirect_url(payment))
Ejemplo n.º 7
0
def reg_cart(request, registrant_id=None):
	context = user_edit_vars(request.user)
	race = None
	if registrant_id:
		registrant = models.Registrant.objects.filter(pk=registrant_id, is_paid=False).first()
		race = registrant.race
	context['registrants'] = request.user.registrant_set.filter(is_paid=False).select_related(
		'race__event__series__city__region__country', 'race__event__city__region__country').order_by(
		'race__event__start_date', 'race__event__name', 'lname')
	context['race'] = race
	context['registrant'] = registrant
	context['page_title'] = u'Оплата регистраций'
	context['total_sum'] = context['registrants'].aggregate(Sum('price'))['price__sum']
	return render(request, 'registration/cart.html', context)
Ejemplo n.º 8
0
def reg_delete(request, registrant_id):
	context = user_edit_vars(request.user)
	if context['is_admin']:
		registrant = get_object_or_404(models.Registrant, pk=registrant_id)
	else:
		registrant = get_object_or_404(models.Registrant, pk=registrant_id, user=request.user)

	race = registrant.race
	event = race.event

	if registrant.is_paid:
		messages.warning(request, u'Регистрация бегуна {} {} на забег {} уже оплачена и не может быть отменена. Придётся бежать!'.format(
			registrant.fname, registrant.lname, race.name_with_event()))
		return redirect(event)

	models.log_obj_create(request.user, event.registration, models.ACTION_REGISTRANT_DELETE, child_object=registrant, comment=u'При отмене регистрации')
	messages.success(request, u'Регистрация бегуна {} {} на забег {} успешно отменена'.format(registrant.fname, registrant.lname, race.name_with_event()))
	registrant.delete()
	return redirect(event)
Ejemplo n.º 9
0
def runner_details(request, runner_id, show_full_page=False):
    runner = get_object_or_404(models.Runner, pk=runner_id)
    context = user_edit_vars(request.user)
    klb_person = runner.klb_person
    # ak_person = runner.ak_person
    user = runner.user
    context['runner'] = runner

    context.update(
        get_filtered_results_dict(request, runner, runner.has_many_distances,
                                  klb_person is not None, show_full_page))
    context.update(
        get_lists_for_club_membership(request.user, runner,
                                      context['is_admin']))
    if klb_person:
        context['klb_person'] = klb_person
        context['n_klb_results'] = klb_person.klb_result_set.count()
    runner_name = u'{} {}'.format(runner.fname, runner.lname) if (
        context['is_admin']
        or not runner.private_data_hidden) else u'(имя скрыто)'
    context['page_title'] = u'{}: все результаты'.format(runner_name)

    return render(request, 'results/runner_details.html', context)
Ejemplo n.º 10
0
def medal_payment(request, year=models_klb.MEDAL_PAYMENT_YEAR):
	user = request.user
	context = user_edit_vars(user)
	context['page_title'] = u'Заказ памятных медалей участника КЛБМатча–{}'.format(models_klb.MEDAL_PAYMENT_YEAR)

	if 'btnPayment' in request.POST:
		form = MedalOrderForm(request.POST, user=user)
		if form.is_valid():
			if user.is_authenticated():
				form.instance.created_by = user
			form.save()
			return make_medal_payment(request, form.instance)
		else:
			messages.warning(request, u'Пожалуйста, исправьте ошибки в форме')
	else:
		form = MedalOrderForm(user=user)
	context['form'] = form
	context['year'] = year if (year == 2018) else models_klb.MEDAL_PAYMENT_YEAR
	context['MEDAL_PRICE'] = models_klb.MEDAL_PRICE
	context['PLATE_PRICE'] = models_klb.PLATE_PRICE
	context['initial_total'] = models_klb.MEDAL_PRICE # + models_klb..PLATE_PRICE
	context['user_is_authenticated'] = request.user.is_authenticated()
	return render(request, 'payment/medal_request_form_2018.html' if (year == 2018) else 'payment/medal_request_form_closed.html', context)
Ejemplo n.º 11
0
def reg_step1(request, event_id):
	event = get_object_or_404(models.Event, pk=event_id)
	context = user_edit_vars(request.user)
	registration = get_object_or_404(models.Registration, event__id=event_id, is_open=True)

	reg_is_open, message = check_if_reg_is_open(registration)
	if not reg_is_open:
		messages.warning(request, message)
		return redirect(event)
	
	if 'frmRegistrantRace_submit' in request.POST:
		frmRegistrantRace = forms.RegistrantAndRaceForm(request.POST, user=request.user, event=event)
		if frmRegistrantRace.is_valid():
			return redirect('results:reg_step2', race_id=frmRegistrantRace.cleaned_data['race'].id, registrant_id=frmRegistrantRace.cleaned_data['registrant'])
		else:
			messages.warning(request, u"Пожалуйста, заполните все поля в форме.")
	else:
		frmRegistrantRace = forms.RegistrantAndRaceForm(user=request.user, event=event)
	context['frmRegistrantRace'] = frmRegistrantRace
	context['event'] = event
	context['series'] = event.series
	context['registration'] = registration
	context['page_title'] = u'Регистрация на {}. Шаг 1'.format(event.name)
	return render(request, 'registration/reg_step1.html', context)
Ejemplo n.º 12
0
def main_page(request):
    context = user_edit_vars(request.user)
    context['all_news'] = models.News.objects.select_related(
        'event__city__region__country', 'event__series__city__region__country',
        'event__series__city_finish__region__country').filter(
            is_for_social=False).order_by('-date_posted')[:N_FIRST_NEWS]
    context['is_authenticated'] = request.user.is_authenticated

    today = datetime.date.today()
    year = today.year if (today.month > 1 or today.day > 16) else (today.year -
                                                                   1)
    if not models.is_active_klb_year(year):
        year = models.CUR_KLB_YEAR

    teams = models.Klb_team.objects.filter(year=year).exclude(
        number=models.INDIVIDUAL_RUNNERS_CLUB_NUMBER).select_related(
            'club__city__region__country')

    context['year'] = year
    context['klb_categories'] = []
    context['klb_categories'].append({
        'name':
        u'Абсолютный зачёт',
        'teams':
        teams.order_by('place', 'name')[:N_FIRST_TEAMS],
        'link':
        reverse('results:klb_match_summary', kwargs={'tab': 'all'}),
    })
    context['klb_categories'].append({
        'name':
        u'Средние клубы',
        'teams':
        teams.filter(place_medium_teams__isnull=False).order_by(
            'place_medium_teams', 'name')[:N_FIRST_TEAMS],
        'link':
        reverse('results:klb_match_summary', kwargs={'tab': 'medium'}),
    })
    context['klb_categories'].append({
        'name':
        u'Малые клубы',
        'teams':
        teams.filter(place_small_teams__isnull=False).order_by(
            'place_small_teams', 'name')[:N_FIRST_TEAMS],
        'link':
        reverse('results:klb_match_summary', kwargs={'tab': 'small'}),
    })

    context['participants'] = models.Klb_participant.objects.filter(
        match_year=year, place__isnull=False,
        n_starts__gt=0).order_by('place').select_related(
            'klb_person__city__region__country', 'team')[:N_FIRST_PERSONS]
    context['absolute_table_link'] = models.Klb_age_group.objects.get(
        match_year=year, gender=models.GENDER_UNKNOWN).get_absolute_url()

    if not context['is_authenticated']:
        context['n_events_in_past'] = get_stat_value('n_events_in_past')
        context['n_events_in_future'] = get_stat_value('n_events_in_future')
        # context['n_events_this_week'] = get_stat_value('n_events_this_week')
        context['n_events_this_month_RU_UA_BY'] = get_stat_value(
            'n_events_this_month_RU_UA_BY')
        context['n_results'] = get_stat_value('n_results')
        context['n_results_with_runner'] = get_stat_value(
            'n_results_with_runner')
    return render(request, 'results/main_page.html', context=context)
Ejemplo n.º 13
0
def runners(request, lname='', fname=''):
    context = user_edit_vars(request.user)
    # runners = models.Runner.objects.select_related('klb_person', 'user__user_profile', 'ak_person').annotate(
    # 	Count('result')).order_by('lname', 'fname')
    runners = models.Runner.objects.select_related('user__user_profile',
                                                   'city__region__country')
    if not context['is_admin']:
        runners = runners.filter(n_starts__gt=0)
    list_title = u"Участники забегов"
    conditions = []
    initial = {}
    ordering = 'length_cur_year'  # 'finishes_cur_year'
    form = None

    lname = lname.strip()
    fname = fname.strip()
    if lname or fname:
        initial['lname'] = lname
        initial['fname'] = fname
    elif any(s in request.GET
             for s in ['btnSearchSubmit', 'page', 'ordering']):
        form = forms.RunnerForm(request.GET)
        if form.is_valid():
            lname = form.cleaned_data['lname'].strip()
            fname = form.cleaned_data['fname'].strip()

            birthday_from = form.cleaned_data['birthday_from']
            if birthday_from:
                runners = runners.filter(
                    Q(birthday_known=True, birthday__gte=birthday_from)
                    | Q(birthday_known=False,
                        birthday__year__gt=birthday_from.year))
                conditions.append(u"с датой рождения не раньше " +
                                  birthday_from.isoformat())

            birthday_to = form.cleaned_data['birthday_to']
            if birthday_to:
                runners = runners.filter(
                    Q(birthday_known=True, birthday__lte=birthday_to)
                    | Q(birthday_known=False,
                        birthday__year__lt=birthday_to.year))
                conditions.append(u"с датой рождения не позже " +
                                  birthday_to.isoformat())

            if context['is_admin']:
                if form.cleaned_data['is_in_klb']:
                    runners = runners.filter(klb_person__isnull=False)
                    conditions.append(u"участвовавшие в КЛБМатчах")

                if form.cleaned_data['is_user']:
                    if context['is_admin']:
                        runners = runners.filter(user__isnull=False)
                    else:
                        runners = runners.filter(
                            user__user_profile__is_public=True)
                    list_title += u", зарегистрированные на сайте"

                # if form.cleaned_data['is_ak_person']:
                # 	runners = runners.filter(ak_person__isnull=False)
                # 	conditions.append(u"из базы АК55")

                if form.cleaned_data['is_in_parkrun']:
                    runners = runners.filter(parkrun_id__isnull=False)
                    conditions.append(u"участвовавшие в паркранах")
            else:
                runners = runners.filter(private_data_hidden=False)
            if 'ordering' in request.GET:
                ordering = request.GET['ordering']
    if form is None:
        form = forms.RunnerForm(initial=initial)

    lname = lname.replace('/', '')
    fname = fname.replace('/', '')
    if lname and fname:
        runners = runners.filter(
            Q(lname__istartswith=lname, fname__istartswith=fname)
            | Q(lname__istartswith=fname, fname__istartswith=lname))
        conditions.append(u"с фамилией «" + lname + u"*»")
        conditions.append(u"с именем «" + fname + u"*»")
    elif lname:
        runners = runners.filter(lname__istartswith=lname)
        conditions.append(u"с фамилией «" + lname + u"*»")
    elif fname:
        runners = runners.filter(fname__istartswith=fname)
        conditions.append(u"с именем «" + fname + u"*»")

    ordering_list = []
    if ordering == 'finishes_all':
        ordering_list.append('-n_starts')
    elif ordering == 'length_all':
        ordering_list.append('-total_length')
    elif ordering == 'time_all':
        ordering_list.append('-total_time')
    elif ordering == 'finishes_cur_year':
        ordering_list.append('-n_starts_{}'.format(
            models.CUR_RUNNERS_ORDERING_YEAR))
    elif ordering == 'length_cur_year':
        ordering_list.append('-total_length_{}'.format(
            models.CUR_RUNNERS_ORDERING_YEAR))
    elif ordering == 'time_cur_year':
        ordering_list.append('-total_time_{}'.format(
            models.CUR_RUNNERS_ORDERING_YEAR))
    elif ordering == 'name':
        ordering_list.append('lname')
        ordering_list.append('fname')
    elif ordering == 'city':
        ordering_list.append('city__name')
    elif ordering == 'birthday':
        ordering_list.append('birthday')
        # runners = runners.exclude(birthday=None)
    for x in ['lname', 'fname']:
        if x not in ordering_list:
            ordering_list.append(x)
    runners = runners.order_by(*ordering_list)

    context['list_title'] = list_title + " " + ", ".join(conditions)
    context['form'] = form
    context['page_title'] = u'Поиск по участникам забегов'
    context['ordering'] = ordering
    context['lname'] = lname
    context['fname'] = fname
    context['cur_stat_year'] = models.CUR_RUNNERS_ORDERING_YEAR
    return paginate_and_render(request, 'results/runners.html', context,
                               runners)
Ejemplo n.º 14
0
def results(request, lname='', fname='', disconnected=False):
    context = user_edit_vars(request.user)
    # if not context['is_admin']:
    # 	raise Http404()
    context['list_title'] = u"Все результаты на забегах"
    today = datetime.date.today()
    conditions = []
    form_params = {}
    initial = {}
    form = None
    use_default_params = True
    make_simple_search = False

    if 'frmSearch_claim' in request.POST:
        if context['is_admin']:
            results_claimed, runner = claim_results(request)
            if results_claimed:
                messages.success(
                    request,
                    u'К бегуну {} успешно привязано результатов: {}'.format(
                        runner, results_claimed))
        else:
            messages.warning(
                request,
                u'Привязывать результаты к бегуну могут только администраторы')

    if lname:
        use_default_params = False
        make_simple_search = True
        form_params['lname'] = lname.strip()
        initial['lname'] = form_params['lname']
    if fname:
        use_default_params = False
        make_simple_search = True
        form_params['fname'] = fname.strip()
        initial['fname'] = form_params['fname']
    if disconnected:
        form_params['disconnected'] = True
        initial['disconnected'] = True
    if ('btnSearchSubmit'
            in request.POST) or ('frmSearch_claim'
                                 in request.POST) or ('page' in request.POST):
        form = forms.ResultForm(request.POST)
        if form.is_valid():
            use_default_params = False
            form_params = {
                key: val
                for (key, val) in form.cleaned_data.iteritems() if val
            }
        else:
            form = None
    if not form_params:
        form = None
    if use_default_params:
        month_before = today - datetime.timedelta(days=31)
        form_params['date_from'] = month_before
        context[
            'list_title'] = u"Все результаты за последний месяц ({})".format(
                models.dates2str(month_before, today))

    if make_simple_search:
        results = models.Result.objects
    else:
        events = models.Event.objects.filter(invisible=False,
                                             cancelled=False,
                                             start_date__lte=today)
        if not set(form_params.keys()).isdisjoint(
                set([
                    'city', 'region', 'country', 'race_name', 'date_from',
                    'date_to'
                ])):
            if 'city' in form_params:
                context['city'] = form_params['city']
                events, conditions = views_race.filterEventsByCity(
                    events, conditions, form_params['city'])
            elif 'region' in form_params:
                events, conditions = views_race.filterEventsByRegion(
                    events, conditions, form_params['region'])
            elif 'country' in form_params:
                events, conditions = views_race.filterEventsByCountry(
                    events, conditions, form_params['country'])
            if 'race_name' in form_params:
                events, conditions = views_race.filterEventsByName(
                    events, conditions, form_params['race_name'])
            if 'date_from' in form_params:
                events, conditions = views_race.filterEventsByDateFrom(
                    events, conditions, form_params['date_from'])
            if 'date_to' in form_params:
                events, conditions = views_race.filterEventsByDateTo(
                    events, conditions, form_params['date_to'])

        races = models.Race.objects.filter(
            event__in=set(events.values_list('id', flat=True)))
        if ('distance' in form_params) or ('distance_from'
                                           in form_params) or ('distance_to'
                                                               in form_params):
            if 'distance' in form_params:
                races, conditions = views_race.filterRacesByDistance(
                    races, conditions, form_params['distance'])
            if 'distance_from' in form_params:
                races, conditions = views_race.filterRacesByDistanceFrom(
                    races, conditions, form_params['distance_from'])
            if 'distance_to' in form_params:
                races, conditions = views_race.filterRacesByDistanceTo(
                    races, conditions, form_params['distance_to'])
        if ('result_from' in form_params) or ('result_to' in form_params):
            races = races.exclude(distance__distance_type=models.TYPE_MINUTES)

        results = models.Result.objects.filter(
            race__in=set(races.values_list('id', flat=True)))
    result_args = {}
    # ak_args = {}
    if 'lname' in form_params:
        result_args['lname__istartswith'] = form_params['lname']
        # ak_args['lname__istartswith'] = form_params['lname']
        conditions.append(u"с фамилией спортсмена «{}*»".format(
            form_params['lname']))
    if 'fname' in form_params:
        result_args['fname__istartswith'] = form_params['fname']
        # ak_args['fname__istartswith'] = form_params['fname']
        conditions.append(u"с именем спортсмена «{}*»".format(
            form_params['fname']))
    if 'midname' in form_params:
        result_args['midname__istartswith'] = form_params['midname']
        # ak_args['midname__istartswith'] = form_params['midname']
        conditions.append(u"с отчеством спортсмена «{}*»".format(
            form_params['midname']))
    if 'club' in form_params:
        result_args['club_name__istartswith'] = form_params['club']
        # ak_args['club_raw__istartswith'] = form_params['club']
        conditions.append(u"из клуба «{}*»".format(form_params['club']))
    if 'result_from' in form_params:
        result_args['result__gte'] = models.int_safe(
            form_params['result_from']) * 100
        conditions.append(u'с результатом не меньше {} секунд'.format(
            form_params['result_from']))
    if 'result_to' in form_params:
        result_args['result__lte'] = models.int_safe(
            form_params['result_to']) * 100
        result_args['status'] = models.STATUS_FINISHED
        conditions.append(u'с результатом не больше {} секунд'.format(
            form_params['result_to']))
    if 'disconnected' in form_params:
        result_args['runner'] = None
        conditions.append(u"не привязанные к людям")
    if result_args:
        # if ak_args:
        # 	ak_person_ids = models_ak.Ak_person_v2.objects.filter(**ak_args).values_list('id', flat=True)
        # 	results = results.filter(Q(**result_args) | Q(ak_person__in=list(ak_person_ids)))
        # else:
        results = results.filter(**result_args)
    # results = results.filter(Q(**result_args))
    results = results.select_related('race__event', 'city__region',
                                     'race__distance').order_by(
                                         '-race__event__start_date',
                                         'race__event__name',
                                         'race__distance__distance_type',
                                         '-race__distance__length', 'race__id',
                                         'status', 'place')
    if form is None:
        form = forms.ResultForm(initial=initial)
    context['list_title'] = context['list_title'] + " " + ", ".join(conditions)
    context['form'] = form
    context['page_title'] = context['list_title']
    return paginate_and_render(request,
                               'results/results.html',
                               context,
                               results,
                               add_results_with_splits=True)
Ejemplo n.º 15
0
def reg_step2(request, race_id, registrant_id):
	race = get_object_or_404(models.Race, pk=race_id)
	event = race.event
	context = user_edit_vars(request.user)
	registration = get_object_or_404(models.Registration, event__id=event.id, is_open=True)
	registrant_id = models.int_safe(registrant_id)

	reg_is_open, message = check_if_reg_is_open(registration, race)
	if not reg_is_open:
		messages.warning(request, message)
		return redirect(event)

	kwargs = {'registration': registration, 'registrant_id': registrant_id}
	registrant = models.Registrant(race=race, user=request.user, registers_himself=(registrant_id == 0), created_by=request.user)

	if 'frmRegistration_submit' in request.POST:
		frmRegistration = forms.RegistrationForm(request.POST, instance=registrant, **kwargs)
		if frmRegistration.is_valid():
			registrant = frmRegistration.save()
			cleaned_data = frmRegistration.cleaned_data

			if cleaned_data.get('save_registrant_data'):
				saved_registrant = models.Saved_registrant(user=request.user)
				for field in saved_registrant.__class__._meta.get_fields():
					if field.name not in ['id', 'user', 'created_time']:
						try:
							setattr(saved_registrant, field.name, cleaned_data.get(field.name))
						except:
							pass
				saved_registrant.save()
				models.log_obj_create(request.user, saved_registrant, models.ACTION_CREATE, comment=u'При регистрации на забег {} (id {})'.format(
					event, event.id))

			price = registrant.race_cost.cost
			for question in race.get_reg_question_set_for_today():
				field_name = 'question_{}'.format(question.id)
				if question.multiple_answers:
					answers = cleaned_data.get(field_name)
					for answer in answers:
						choice = question.reg_question_choice_set.filter(is_visible=True, pk=answer).first()
						if choice:
							models.Reg_answer.objects.create(registrant=registrant, reg_question_choice=choice, created_by=request.user)
							price += choice.cost
				else:
					answer = cleaned_data.get(field_name)
					if answer:
						choice = question.reg_question_choice_set.filter(is_visible=True, pk=answer).first()
						if choice:
							models.Reg_answer.objects.create(registrant=registrant, reg_question_choice=choice, created_by=request.user)
							price += choice.cost
			registrant.price = price
			registrant.save()
			models.log_obj_create(request.user, registration, models.ACTION_REGISTRANT_CREATE, child_object=registrant, comment=u'При регистрации')
			return redirect('results:reg_step3', race_id=race.id, registrant_id=registrant.id)
		else:
			messages.warning(request, u"Пожалуйста, исправьте ошибки в форме.")
	else:
		frmRegistration = forms.RegistrationForm(instance=registrant, **kwargs)
	context['frmRegistration'] = frmRegistration
	context['event'] = event
	context['race'] = race
	context['registration'] = registration
	context['page_title'] = u'Регистрация на {}. Шаг 2'.format(event.name)
	return render(request, 'registration/reg_step2.html', context)
Ejemplo n.º 16
0
def all_news(request,
             country_id=None,
             region_id=None,
             city_id=None,
             one_side=0):
    context = user_edit_vars(request.user)
    list_title = u"Новости"
    conditions = []

    all_news = models.News.objects.select_related('event')
    form = forms.NewsSearchForm()

    country = None
    region = None
    city = None
    initial = {}
    context['short_link_city'] = False
    context['short_link_region'] = False
    context['short_link_country'] = False

    if city_id:
        city = get_object_or_404(models.City, pk=city_id)
        initial['country'] = city.region.country
        if city.region.active:
            initial['region'] = city.region
        form = forms.NewsSearchForm(initial=initial)
        context['city'] = city
        context['short_link_city'] = True
    elif region_id:
        region = get_object_or_404(models.Region, pk=region_id)
        form = forms.NewsSearchForm(initial={'region': region})
        context['short_link_region'] = True
    elif country_id:
        country = get_object_or_404(models.Country, pk=country_id)
        form = forms.NewsSearchForm(initial={'country': country})
        context['short_link_country'] = True
    elif (request.method == 'GET') and ('frmSearchNews_submit'
                                        in request.GET) or ('page'
                                                            in request.GET):
        form = forms.NewsSearchForm(request.GET)
        if form.is_valid():
            country = form.cleaned_data['country']
            region = form.cleaned_data['region']
            city = form.cleaned_data['city']

            news_text = form.cleaned_data['news_text']
            if news_text:
                all_news = all_news.filter(
                    Q(title__icontains=news_text)
                    | Q(content__icontains=news_text))
                conditions.append(
                    u"с «{}» в названии или тексте".format(news_text))
            date_from = form.cleaned_data['date_from']
            if date_from:
                all_news = all_news.filter(date_posted__gte=date_from)
                conditions.append(u"не раньше {}".format(
                    date_from.isoformat()))
            date_to = form.cleaned_data['date_to']
            if date_to:
                all_news = all_news.filter(date_posted__lte=date_to)
                conditions.append(u"не позже {}".format(date_to.isoformat()))
            published_by_me = form.cleaned_data['published_by_me']
            if published_by_me:
                all_news = all_news.filter(created_by=request.user)
                conditions.append(u"с автором – мной")

            if (not published_by_me) and (not news_text) and (
                    not date_from) and (not date_to):
                if city_id:
                    context['short_link_city'] = True
                elif region:
                    context['short_link_region'] = True
                elif country:
                    context['short_link_country'] = True

    if country:
        all_news, conditions = filterNewsByCountry(all_news, conditions,
                                                   country)
    if region:
        all_news, conditions = filterNewsByRegion(all_news, conditions, region)
    if city:
        all_news, conditions = filterNewsByCity(all_news, conditions, city)

    if not context['is_admin']:
        all_news = all_news.filter(is_for_social=False)
    all_news = all_news.order_by('-date_posted')
    context['form'] = form
    context['country'] = country
    context['region'] = region
    context['city'] = city
    context['one_side'] = one_side
    context['list_title'] = list_title + " " + ", ".join(conditions)

    return paginate_and_render(request, 'results/news.html', context, all_news)