Example #1
0
def add_bus_rating(request):
    if request.method == "POST":
        try:
            business = Business.objects.get(id=request.POST["bid"])
        except Business.DoesNotExist:
            print("bus does not exist!")
            return HttpResponse("{'success': 'false'}")

        rat = request.POST["rating"]
        try:
            rating = Rating.objects.get(business=business, user=request.user)
        except Rating.DoesNotExist:
            logger.debug("In vote create a new rating!")
            rating = Rating(business=business, user=request.user, rating=rat)
        else:
            Rating.objects.filter(business=business, user=request.user).delete()
            rating = Rating(business=business, user=request.user, rating=rat)

        rating.save()
        response_data = dict()
        response_data["bid"] = str(request.POST["bid"])
        response_data["success"] = "true"
        response_data["rating"] = rat
        context = {}
        business.rating = rating.rating
        context["business"] = get_single_bus_data(business, request.user)
        return render_to_response("ratings/listing/rate_data.html", context)
        # return HttpResponse("{'success':'true', 'rating': '" + str(rat) + "'}")
    else:
        raise Http404("What are you doing here?")
Example #2
0
def generate_nmf_test(numFactors, density):
    allUsers = User.objects.all()
    allBusinsses = Business.objects.all()
    random.seed(666)
    newP = []
    for u in range(0, allUsers.count()):
        if u not in newP:
            newP.append([])
        for k in range(0, numFactors):
            rif = random.uniform(0, 1)
            newP[u].append(rif)

    newQ = []
    for k in range(0, numFactors):
        newQ.append([])
        for j in range(0, allBusinsses.count()):
            rif = random.uniform(0, 1)
            newQ[k].append(rif)

    initR = dot(newP, newQ)

    i = 0
    for u in allUsers:
        j = 0
        for b in allBusinsses:
            chance = random.uniform(0, 1)
            if(chance < density):
                rat = Rating(business=b, username=u, rating=float(initR[i][j]))
                rat.save()
            j = j + 1
    i = i + 1
def import_ratings(apps, schema_editor):
    with open('ratings/data/ratings.csv', encoding='latin-1') as f:
        ratings = csv.reader(f, delimiter="\t")
        for row in ratings:
            rater = Rater.objects.get(id=row[0])
            movie = Movie.objects.get(id=row[1])
            rating = Rating(rater=rater, movie=movie, score=row[2])
            rating.save()
Example #4
0
def rateItemInDb(item, user, value):
  # logger.debug("Adding rating: item [%s], user [%s], value [%s]" % (item, user, value))
  try:
    rating = Rating.objects.get(user=user, item=item)
    rating.value = value
  except (Rating.DoesNotExist):
    rating = Rating(user=user, item=item, value=value)

  rating.save()
def get_rating(apps, schema_editor):
    rating = apps.get_model("ratings", "Rating")
    with open('../ml-100k/u.data', 'r') as f:
        data = csv.reader(f, delimiter='\t')
        for row in data:
            rater = Rater.objects.get(id=row[0])
            movie = Movie.objects.get(id=row[1])

            rating = Rating(rater=rater, movie=movie, rating=row[2])
            rating.save()
Example #6
0
def add(request):
    if request.method == "POST":
        form = NewProfForm(request.POST)
        if form.is_valid():
            prof = form.cleaned_data
            name = prof["name"]
            marks = prof["marks"]
            obj = Rating(professor=name, rating=marks)
            obj.save()
            print("redirecting...")
            return redirect("rating")
        else:
            return render(request, "rating/add.html"), {"form": form}
    return render(request, "ratings/add.html", {"form": NewProfForm()})
Example #7
0
def rateItem(request, item_id):
	item = get_object_or_404(Item, pk=item_id)
	value = request.POST['value']
	user = request.user

	# Update the rating if it exists, otherwise create it
	try:
		rating = Rating.objects.get( user=user, item=item )
		rating.value = value
	except (Rating.DoesNotExist):
		rating = Rating( user=user, item=item, value=value )

	rating.save()

	return HttpResponseRedirect(reverse('ratings:viewItem', args=(item.id, )))
Example #8
0
    def test_results_200(self):
        self.assertEqual(self.room.users.count(), 1)
        self.assertEqual(self.room.users.first(), self.admin)
        Rating.objects.bulk_create([
            Rating(user=self.admin, movie=movie, score=5)
            for movie in list(self.room.movies.all())
        ])
        self.assertTrue(self.room.users_are_ready)
        self.assertEqual(self.room.results.count(), 0)

        url = f'{self.URL}/{self.room.slug}/results'
        r = self.client.get(url, **self.http_admin_auth)
        self.assertEqual(r.status_code, 200)
        r_json = r.json()
        self.assertEqual(len(r_json), 2)
        self.assertEqual(r_json['slug'], self.room.slug)
        self.assertEqual(len(r_json['results']), constants.RESULTS_MOVIES)
        self.room.refresh_from_db()
        self.assertEqual(self.room.results.count(), constants.RESULTS_MOVIES)

        # can be called again
        r_2 = self.client.get(url, **self.http_admin_auth)
        self.assertEqual(r_2.status_code, 200)
        r_2_json = r_2.json()
        self.assertEqual(r_2_json, r_json)
    def test_rating_str(self):
        # test that rating model string is what you expect
        test_name = Rating(
            reviewer=self.user1,
            rating=3
        )

        self.assertEqual(str(test_name), "{0} by {1}".format(test_name.rating, self.user1.username))
Example #10
0
    def test_get_or_create_results(self):
        room = Room.objects.create_room(**{
            'slug': self.slug,
            'admin': self.user
        })
        self.assertEqual(list(room.results.all()), [])
        user_2 = User.objects.create_user(**USER_CHI)
        room.sync_user(user_2)
        admin_rated_count = room.users.rated_count(room)[0]['rated_count']
        user_2_rated_count = room.users.rated_count(room)[1]['rated_count']
        self.assertTrue(admin_rated_count < constants.CHALLENGE_MOVIES)
        self.assertTrue(user_2_rated_count < constants.CHALLENGE_MOVIES)

        self.assertEqual(room.users_are_ready, False)
        with self.assertRaises(RoomUsersNotReady):
            room.get_or_create_results()

        Rating.objects.bulk_create([
            Rating(user=self.user, movie=movie, score=1)
            for movie in list(room.movies.all())
        ])
        admin_rated_count = room.users.rated_count(room)[0]['rated_count']
        self.assertEqual(admin_rated_count, constants.CHALLENGE_MOVIES)

        self.assertEqual(room.users_are_ready, False)
        with self.assertRaises(RoomUsersNotReady):
            room.get_or_create_results()

        Rating.objects.bulk_create([
            Rating(user=user_2, movie=movie, score=1)
            for movie in list(room.movies.all())
        ])
        user_2_rated_count = room.users.rated_count(room)[1]['rated_count']
        self.assertEqual(user_2_rated_count, constants.CHALLENGE_MOVIES)

        self.assertEqual(room.users_are_ready, True)
        results = room.get_or_create_results()
        room.refresh_from_db()
        self.assertEqual(list(room.results.all()), list(results.all()))
        self.assertEqual(results.count(), constants.RESULTS_MOVIES)

        results_2 = room.get_or_create_results()
        self.assertEqual(list(results_2.all()), list(results.all()))
Example #11
0
    def do_rating(self, user_from, rating, comment=None):
        self.check_user_can_rate(user_from)
        relation_type, user = self.target_rating(user_from)

        category = settings.RATINGS_STEP_FEEDBACK
        Rating.update(
            rating_context=self,
            rating_object=user,
            user=user_from,
            rating=rating,
            category=category,
            comment=comment,
        )
        signal_post_overall_rating_team_step_save.send(
            sender=self.__class__,
            team_step=self,
            user=user,
            relation_type=relation_type)
        return rating
Example #12
0
        def test_rating_recipe_calculate_account_stars(self, api_client):
            first_recipe = RecipeFactory()
            recipe_author = first_recipe.author
            api_client.force_authenticate(recipe_author)

            second_recipe = RecipeFactory.build()
            data = {
                'title': {second_recipe.title},
                'description': {second_recipe.description},
                'flavor_type': {second_recipe.flavor_type}, 
            }
            api_client.post(create_recipe_url, data)
            second_recipe = Recipe.objects.all().get(title=second_recipe.title)

            data = {
                'recipe': first_recipe.id,
                'stars': 5
            }

            api_client.post(rating_rate_url, data)
            
            data = {
                'recipe': second_recipe.id,
                'stars': 0
            }
            api_client.post(rating_rate_url, data)
            api_client.logout()


            second_user = UserFactory()
            api_client.force_authenticate(second_user)
            data = {
                'recipe': first_recipe.id,
                'stars': 5
            }
            api_client.post(rating_rate_url, data)

            data = {
                'recipe': second_recipe.id,
                'stars': 5
            }
            api_client.post(rating_rate_url, data)
            api_client.logout()


            first_recipe = Recipe.objects.all().get(title=first_recipe.title)
            second_recipe = Recipe.objects.all().get(title=second_recipe.title)
            user = UserAccount.objects.all().get(id=recipe_author.id)

            assert first_recipe.stars == '5.0'
            assert second_recipe.stars == '2.5'
            assert Rating.get_account_stars_score(user=user) == 3.75
            assert user.stars == '3.75'
def calculate_scores_for_all_options(event, poll):
    options = Option.objects.filter(poll=poll)
    return_dict = {"poll": poll, "event": event}
    if Rating.objects.filter(poll=poll):
        return_dict["raters"] = Rating.number_of_raters(poll)
        return_dict["categories"] = Category.objects.filter(poll=poll)
        return_dict["options"] = []
        for option in options:
            scores = calculate_scores_for_single_option(poll, option)
            return_dict["options"].append({"title": option.title,
                "scores": scores[0], "final_score": scores[1]})
    else:
        return_dict["no_ratings"] = True
    return return_dict
Example #14
0
    def get_new_ratings(self, game, ranks):
        new_ratings = []
        for rank in ranks:
            player_rating = self.get_player_game_rating(game, rank)

            opponent_ranks = ranks.exclude(player=rank.player)
            opponent_ratings = [
                self.get_player_game_rating(game, opponent_rank)
                for opponent_rank in opponent_ranks
            ]
            new_ratings.append(
                (rank.player, player_rating[1] + sum(Rating.get_adjustments(player_rating, opponent_ratings)))
            )

        return new_ratings
Example #15
0
    def do_rating(self, user_from, rating, comment=None):
        from ..tasks import PostAnswerRatingTask

        act_action.send(
            user_from,
            verb=settings.FORUM_ACTION_RATING_POST,
            action_object=self)

        category = settings.RATINGS_ANSWER_ADVISOR
        Rating.update(
            rating_context=self,
            rating_object=self,
            user=user_from,
            rating=rating,
            category=category,
            comment=comment,
        )

        signal_post_overall_rating_answer_save.send(
            sender=self.__class__,
            answer=self)

        new_action_answer.send(
            sender=self.__class__,
            instance=self,
            action=settings.FORUM_ACTION_RATING_POST,
        )

        kwargs = {}
        kwargs['eta'] = increase_date(seconds=settings.FORUM_NEW_POST_DELAY)
        PostAnswerRatingTask().s(
            answer_pk=self.pk,
            rating=rating,
        ).apply_async(**kwargs)

        return rating
Example #16
0
def avaliarSubmit(request, idAvalia):
    url = request.META.get('HTTP_REFERER')
    user = request.user
    try:
        historico = HistoricoAlugados.objects.get(id=idAvalia)
    except ObjectDoesNotExist:
        return render(request, 'home/termosdeuso.html')

    usuario = ''
    locadorUser = ''
    locatarioUser = ''
    if user == historico.locador:
        historico.avaliadoPeloLocador = True
        historico.save()
        usuario = historico.locatario
    if user == historico.locatario:
        historico.avaliadoPeloLocatario = True
        historico.save()
        usuario = historico.locador

    if request.method == 'POST':
        form = RatingForm(request.POST)
        if form.is_valid():            
            data = Rating()             
            data.de = user
            data.para = usuario
            data.text = form.cleaned_data['text']
            data.rate = form.cleaned_data['rate']
            data.save()           
            messages.info(request, 'Agradecemos a sua avaliação!')

    user = request.user
    avaliacoes = HistoricoAlugados.objects.filter(Q(locador=user) | Q(locatario=user) & Q(encerrado=True))
    arrayPendentes = []
    for avaliacao in avaliacoes:
        if user == avaliacao.locador:

            if avaliacao.avaliadoPeloLocador == False:
                arrayPendentes.append(avaliacao)
        if user == avaliacao.locatario:

            if avaliacao.avaliadoPeloLocatario == False:
                arrayPendentes.append(avaliacao)

    return render(request, 'user/avaliacoesPendentes.html', {'avaliacoes': arrayPendentes})
Example #17
0
def test_get_recipe_avg_rating_score(api_client):
    new_recipe = RecipeFactory()
    api_client.force_authenticate(new_recipe.author)
    new_recipe = Recipe.objects.all().get(id__exact=new_recipe.id)
    data = {'recipe': new_recipe.id, 'stars': 5}
    api_client.post(rating_create_url, data)
    api_client.logout()

    new_user = UserFactory()
    api_client.force_authenticate(new_user)
    data = {'recipe': new_recipe.id, 'stars': 1}
    api_client.post(rating_create_url, data)

    recipe_avg_stars = Rating.get_recipe_stars_score(recipe=new_recipe)

    assert recipe_avg_stars == 3.0
Example #18
0
def test_get_account_stars_score(api_client):
    user = UserFactory()
    api_client.force_authenticate(user)

    first_recipe = RecipeFactory.build()
    create_recipe_url = reverse('recipes:create')
    data = {
        'title': {first_recipe.title},
        'description': {first_recipe.description},
        'flavor_type': {first_recipe.flavor_type},
    }
    api_client.post(create_recipe_url, data)

    second_recipe = RecipeFactory.build()
    data = {
        'title': {second_recipe.title},
        'description': {second_recipe.description},
        'flavor_type': {second_recipe.flavor_type},
    }
    api_client.post(create_recipe_url, data)

    first_recipe = Recipe.objects.all().get(title__exact=first_recipe.title)
    data = {'recipe': first_recipe.id, 'stars': 5}
    api_client.post(rating_create_url, data)
    second_recipe = Recipe.objects.all().get(title__exact=second_recipe.title)
    data = {'recipe': second_recipe.id, 'stars': 0}
    api_client.post(rating_create_url, data)

    second_user = UserFactory()
    api_client.force_authenticate(second_user)

    data = {'recipe': first_recipe.id, 'stars': 1}
    api_client.post(rating_create_url, data)
    data = {'recipe': second_recipe.id, 'stars': 3}
    api_client.post(rating_create_url, data)

    account_avg_stars = Rating.get_account_stars_score(user=user)

    assert account_avg_stars == 2.25
Example #19
0
        def test_rating_recipe_calculate_recipe_stars(self, api_client):
            recipe = RecipeFactory()
            first_user = UserFactory()
            api_client.force_authenticate(first_user)

            data = {
                'recipe': recipe.id,
                'stars': 4
            }
            api_client.post(rating_rate_url, data)
            api_client.logout()

            second_user = UserFactory()
            api_client.force_authenticate(second_user)
            data = {
                'recipe': recipe.id,
                'stars': 2
            }
            api_client.post(rating_rate_url, data)
            recipe = Recipe.objects.all().get(id=recipe.id)

            assert recipe.stars == '3.0'
            assert recipe.stars == str(Rating.get_recipe_stars_score(recipe=recipe))
Example #20
0
def average_rating_for_zipcode(request, zipcode):
    """
    Get average rating values for zipcode.
    """
    ratings = Rating.objects.filter(zipcode=zipcode)
    ratings_count = ratings.count()

    if(ratings_count == 0):
    	return Response(status=status.HTTP_404_NOT_FOUND)

    # Get all rated values
    total_sum = 0.0
    culture_sum = 0.0
    infrastructure_sum = 0.0
    green_sum = 0.0
    safety_sum = 0.0
    for rating in ratings:
    	total_sum += rating.total
    	culture_sum += rating.culture
    	infrastructure_sum += rating.infrastructure
    	green_sum += rating.green
    	safety_sum += rating.safety

    # Get rounded average values
    total_average = int(round(total_sum / ratings_count))
    culture_average = int(round(culture_sum / ratings_count))
    infrastructure_average = int(round(infrastructure_sum / ratings_count))
    green_average = int(round(green_sum / ratings_count))
    safety_average = int(round(safety_sum / ratings_count))

    # Create a new Rating object with average values
    average_rating = Rating(zipcode=zipcode, user_id='average', 
    	total=total_average, culture=culture_average, infrastructure=infrastructure_average,
    	green=green_average, safety=safety_average)

    serializer = RatingSerializer(average_rating)
    return Response(serializer.data)
Example #21
0
    def test_room_ratings_count(self):
        movies_2018 = [
            Movie.objects.create(title=f'title_{i}', year=2018)
            for i in range(CHALLENGE_MOVIES)
        ]
        movies_2019 = [
            Movie.objects.create(title=f'title_{i}', year=2019)
            for i in range(CHALLENGE_MOVIES)
        ]
        user_1 = User.objects.create_session_user(USER_CHI['name'])
        user_2 = User.objects.create_session_user(USER_JOAO['name'])
        room = Room.objects.create(admin=user_1, slug='slug')
        room.sync_user(user_1)
        room.sync_user(user_2)
        room.movies.set(movies_2018)
        self.assertEqual(room.users.count(), 2)
        self.assertEqual(room.movies.count(), CHALLENGE_MOVIES)

        # 2018 movies ratings
        ratings = [
            Rating(user=user_1, movie=movies_2018[0], score=1),
            Rating(user=user_1, movie=movies_2018[3], score=2),
            Rating(user=user_1, movie=movies_2018[8], score=3),

            # 2019 movie ratings
            Rating(user=user_1, movie=movies_2019[1], score=1),
            Rating(user=user_1, movie=movies_2019[7], score=3),

            # user 2
            Rating(user=user_2, movie=movies_2019[0], score=1),
        ]
        Rating.objects.bulk_create(ratings)

        User.objects.create_session_user('not in the room')
        self.assertEqual(User.objects.count(), 3)

        qs = User.objects.rated_count(room=room)
        self.assertEqual(qs.count(), 2)
        self.assertIn({'name': USER_CHI['name'], 'rated_count': 3}, qs)
        self.assertIn({'name': USER_JOAO['name'], 'rated_count': 0}, qs)
Example #22
0
def test_get_search_url():
    assert Rating.get_search_url() == reverse('ratings:search')
Example #23
0
def test_get_create_url():
    assert Rating.get_create_url() == reverse('ratings:create')
Example #24
0
import pytest
from django.urls import reverse

from factories import RatingFactory, RecipeFactory, UserFactory
from ratings.models import Rating
from recipes.models import Recipe

pytestmark = pytest.mark.django_db
rating_create_url = Rating.get_create_url()


def test__str__():
    new_rating = RatingFactory()

    assert new_rating.__str__() == str(new_rating.author)


def test_get_delete_url():
    new_rating = RatingFactory()

    assert new_rating.get_delete_url() == reverse('ratings:delete',
                                                  kwargs={"pk": new_rating.id})


def test_get_create_url():
    assert Rating.get_create_url() == reverse('ratings:create')


def test_get_search_url():
    assert Rating.get_search_url() == reverse('ratings:search')
Example #25
0
# TODO add tests for MIN and MAX values of stars 
# TODO test perform_create

import pytest
from django.urls import reverse

from accounts.models import UserAccount
from factories import RatingFactory, RecipeFactory, UserFactory
from ratings.models import Rating
from recipes.models import Recipe

pytestmark = pytest.mark.django_db

rating_rate_url = Rating.get_create_url()
rating_search_url = Rating.get_search_url()
create_recipe_url = Recipe.get_create_url()
class TestRatingCreateView:
    class TestAuthenticatedUsers:
        def test_rating_page_render(self, api_client):
            new_user = UserFactory()
            api_client.force_authenticate(new_user)

            response = api_client.get(rating_rate_url) 

            assert response.status_code == 405
        
        def test_rate_post_request(self, api_client):
            new_user = UserFactory()
            api_client.force_authenticate(new_user)
            new_recipe = RecipeFactory()
            new_recipe = Recipe.objects.all().get(id__exact=new_recipe.id)
Example #26
0
from ratings.models import Rating
from ratings.serializers import RatingSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

rating = Rating(route_id=1,
                user_id=1,
                car_rating=4,
                driver_rating=3,
                average_rating=3.5,
                comment='I liked the travel')
rating.save()

rating = Rating(route_id=1,
                user_id=2,
                car_rating=5,
                driver_rating=3,
                average_rating=4,
                comment='The driver was awesome! I wanna marry him')
rating.save()

serializer = RatingSerializer(rating)
serializer.data

content = JSONRenderer().render(serializer.data)
content

from django.utils.six import BytesIO

stream = BytesIO(content)
data = JSONParser().parse(stream)
    s.day = date
    s.location = Location.objects.get(pk=loc)
    s.save()
    for i, (k, v) in enumerate(d.iteritems(), 1):
        if s.pk in v:
            s.paper.add(Paper.objects.get(pk=i))
    s.save()
    
f.close()

## ratings

f = open('/Users/dimitriosalikaniotis/Sites/llc/llc_site/llc/utils/ratings.txt')

for line in f:
    r = Rating()
    try:
        pid = line.strip().split('\t')[0]
        r.paper = Paper.objects.get(pk=pid)
    except:
        pass
    try:
        rid = line.strip().split('\t')[1]
        if rid != "None":
            r.rater = Participant.objects.get(pk=rid)
    except:
        pass
    try:
        r.score = float(line.strip().split('\t')[2])
    except:
        pass
Example #28
0
def signup(request):
    sign_up_page = request.COOKIES.get(SIGN_UP_PAGE, SIGN_UP_PAGE_FIRST)
    sign_up_get_form = SignUpForm1() if sign_up_page == SIGN_UP_PAGE_FIRST \
        else SignUpForm2() if sign_up_page == SIGN_UP_PAGE_SECOND \
        else SignUpForm3() if sign_up_page == SIGN_UP_PAGE_THIRD \
        else SignUpForm4()

    if request.method == GET:
        sign_up_stage_page = ugettext_lazy("Регистрация - этап {}")
        sign_up_stage_page = sign_up_stage_page.format(sign_up_page)
        submit_value = ugettext_lazy("Далее")
        has_error, error = request.COOKIES.get(SIGN_UP_COOKIE_ERROR, IS_OK), NONE
        if sign_up_page == SIGN_UP_PAGE_SECOND:
            sign_up_get_form.fields[PHONE_NUMBER].initial = "+7"
            submit_value = ugettext_lazy("Получить код")
            if has_error == IS_NOT_OK:
                error = ugettext_lazy("Уже существует аккаунт с таким номером телефона или номер телефона некорректен")
        elif sign_up_page == SIGN_UP_PAGE_THIRD:
            sign_up_get_form.fields[PHONE_NUMBER].initial = request.COOKIES.get(SIGN_UP_COOKIE_PHONE_NUMBER)
            submit_value = ugettext_lazy("Подтвердить код")
            if has_error == IS_NOT_OK:
                error = ugettext_lazy("Введенный код не подтвержден")
        elif sign_up_page == SIGN_UP_PAGE_FOURTH:
            sign_up_get_form.fields[PHONE_NUMBER].initial = request.COOKIES.get(SIGN_UP_COOKIE_PHONE_NUMBER)
            sign_up_get_form.fields[CODE_FOR_PHONE_NUMBER].initial = request.COOKIES.get(SIGN_UP_COOKIE_PHONE_NUMBER_CODE)
            submit_value = ugettext_lazy("Создать аккаунт")
        context = {
            FORM: sign_up_get_form,
            STAGE: sign_up_stage_page,
            SUBMIT_VALUE: submit_value,
            ERROR: error
        }
        response = render(request, "sportsmen/signup.html", context=context)
        response.set_cookie(SIGN_UP_COOKIE_ERROR, IS_OK, max_age=SIGN_UP_PAGE_COOKIE_AGE)
        return response
    elif request.method == POST:
        sign_up_post_form = SignUpForm1(request.POST) if sign_up_page == SIGN_UP_PAGE_FIRST \
                        else SignUpForm2(request.POST) if sign_up_page == SIGN_UP_PAGE_SECOND \
                        else SignUpForm3(request.POST) if sign_up_page == SIGN_UP_PAGE_THIRD \
                        else SignUpForm4(request.POST)
        
        if sign_up_page == SIGN_UP_PAGE_FIRST:
            if sign_up_post_form.is_valid():
                response = redirect("signup")
                response.set_cookie(
                    SIGN_UP_PAGE,
                    SIGN_UP_PAGE_SECOND,
                    max_age=SIGN_UP_PAGE_COOKIE_AGE
                )
                response.set_cookie(
                    SIGN_UP_COOKIE_FIRST_NAME,
                    "|".join(str(ord(element)) for element in sign_up_post_form.cleaned_data[FIRST_NAME]),
                    max_age=SIGN_UP_PAGE_COOKIE_AGE
                )
                response.set_cookie(
                    SIGN_UP_COOKIE_LAST_NAME,
                    "|".join(str(ord(element)) for element in sign_up_post_form.cleaned_data[LAST_NAME]),
                    max_age=SIGN_UP_PAGE_COOKIE_AGE
                )
                response.set_cookie(
                    SIGN_UP_COOKIE_DAY,
                    sign_up_post_form.cleaned_data[DAY],
                    max_age=SIGN_UP_PAGE_COOKIE_AGE
                )
                response.set_cookie(
                    SIGN_UP_COOKIE_MONTH,
                    sign_up_post_form.cleaned_data[MONTH],
                    max_age=SIGN_UP_PAGE_COOKIE_AGE
                )
                response.set_cookie(
                    SIGN_UP_COOKIE_YEAR,
                    sign_up_post_form.cleaned_data[YEAR],
                    max_age=SIGN_UP_PAGE_COOKIE_AGE
                )
                response.set_cookie(
                    SIGN_UP_COOKIE_GENDER,
                    sign_up_post_form.cleaned_data[GENDER],
                    max_age=SIGN_UP_PAGE_COOKIE_AGE
                )
                return response
        elif sign_up_page == SIGN_UP_PAGE_SECOND:
            response = redirect("signup")

            is_valid, country_region, phone_number = True, request.POST.get(COUNTRY_REGION), request.POST.get(PHONE_NUMBER)
            if (country_region == "+380" and len(phone_number) < 18) or \
               (country_region == "+375" and len(phone_number) < 17) or \
               (country_region == "+77" and len(phone_number) < 16) or \
               (country_region == "+7" and len(phone_number) < 16):
                is_valid = False

            if sign_up_post_form.is_valid() and is_valid:
                try:
                    Sportsman.manager.get(phone_number=sign_up_post_form.cleaned_data[PHONE_NUMBER])
                    response.set_cookie(
                        SIGN_UP_COOKIE_ERROR,
                        IS_NOT_OK,
                        max_age=SIGN_UP_PAGE_COOKIE_AGE
                    )
                    return response
                except ObjectDoesNotExist:
                    response.set_cookie(
                        SIGN_UP_PAGE,
                        SIGN_UP_PAGE_THIRD,
                        max_age=SIGN_UP_PAGE_COOKIE_AGE
                    )
                    response.set_cookie(
                        SIGN_UP_COOKIE_PHONE_NUMBER,
                        sign_up_post_form.cleaned_data[PHONE_NUMBER],
                        max_age=SIGN_UP_PAGE_COOKIE_AGE
                    )

                    send_code_to_activate_phone_number.delay(sign_up_post_form.cleaned_data[PHONE_NUMBER])

                    return response
            response.set_cookie(
                SIGN_UP_COOKIE_ERROR,
                IS_NOT_OK,
                max_age=SIGN_UP_PAGE_COOKIE_AGE
            )
            return response

        elif sign_up_page == SIGN_UP_PAGE_THIRD:
            if sign_up_post_form.is_valid():
                code_for_phone_number = sign_up_post_form.cleaned_data[CODE_FOR_PHONE_NUMBER]
                phone_number = request.COOKIES.get(SIGN_UP_COOKIE_PHONE_NUMBER)
                phone_number_verified = send_code_to_verify_phone_number(phone_number, code_for_phone_number)
                response = redirect("signup")

                if phone_number_verified:
                    response.set_cookie(
                        SIGN_UP_PAGE,
                        SIGN_UP_PAGE_FOURTH,
                        max_age=SIGN_UP_PAGE_COOKIE_AGE
                    )
                    response.set_cookie(
                        SIGN_UP_COOKIE_PHONE_NUMBER_CODE,
                        code_for_phone_number,
                        max_age=SIGN_UP_PAGE_COOKIE_AGE
                    )
                else:
                    response.set_cookie(
                        SIGN_UP_COOKIE_ERROR,
                        IS_NOT_OK,
                        max_age=SIGN_UP_PAGE_COOKIE_AGE
                    )
                return response
        elif sign_up_page == SIGN_UP_PAGE_FOURTH:
            if sign_up_post_form.is_valid():
                first_name_cookie = request.COOKIES.get(SIGN_UP_COOKIE_FIRST_NAME).split("|")
                last_name_cookie = request.COOKIES.get(SIGN_UP_COOKIE_LAST_NAME).split("|")
                first_name_cookie = [int(element) for element in first_name_cookie if element]
                last_name_cookie = [int(element) for element in last_name_cookie if element]

                user = User()
                user.save()
                user.username = user.pk
                user.first_name = "".join(map(chr, first_name_cookie))
                user.last_name = "".join(map(chr, last_name_cookie))
                user.set_password(sign_up_post_form.cleaned_data[PASSWORD])
                user.save()
                sportsman = Sportsman()
                sportsman.phone_number = request.COOKIES.get(SIGN_UP_COOKIE_PHONE_NUMBER)
                sportsman.gender = request.COOKIES.get(SIGN_UP_COOKIE_GENDER)
                sportsman.birthday = datetime(
                    int(request.COOKIES.get(SIGN_UP_COOKIE_YEAR)),
                    int(request.COOKIES.get(SIGN_UP_COOKIE_MONTH)),
                    int(request.COOKIES.get(SIGN_UP_COOKIE_DAY))
                ).date()
                sportsman.avatar = "man.png" if request.COOKIES.get(SIGN_UP_COOKIE_GENDER) == "1" else "woman.png"
                sportsman.athlete = user
                sportsman.save()
                rating = Rating()
                rating.athlete = user
                rating.save()
                log_in(request, user)

                response = redirect("sportsmen-index")
                response.set_cookie(
                    SIGN_UP_PAGE,
                    SIGN_UP_PAGE_FIRST,
                    max_age=SIGN_UP_PAGE_COOKIE_AGE
                )
                return response
        return redirect("signup")
Example #29
0
# {{{ Insert new ratings
Rating.objects.bulk_create([
    Rating(
        period=period,
        player=p['player'],
        prev=p['rating'],
        rating=p['new_ratings']['M'],
        rating_vp=p['new_ratings']['P'],
        rating_vt=p['new_ratings']['T'],
        rating_vz=p['new_ratings']['Z'],
        dev=p['new_devs']['M'],
        dev_vp=p['new_devs']['P'],
        dev_vt=p['new_devs']['T'],
        dev_vz=p['new_devs']['Z'],
        comp_rat=p['perfs']['M'],
        comp_rat_vp=p['perfs']['P'],
        comp_rat_vt=p['perfs']['T'],
        comp_rat_vz=p['perfs']['Z'],
        bf_rating=p['new_ratings']['M'],
        bf_rating_vp=p['new_ratings']['P'],
        bf_rating_vt=p['new_ratings']['T'],
        bf_rating_vz=p['new_ratings']['Z'],
        bf_dev=p['new_devs']['M'],
        bf_dev_vp=p['new_devs']['P'],
        bf_dev_vt=p['new_devs']['T'],
        bf_dev_vz=p['new_devs']['Z'],
        decay=p['rating'].decay +
        1 if p['rating'] and len(p['wins']) == 0 else 0,
    ) for p in players.values() if p['player'].id in insert_ids
])