Exemple #1
0
    def post(self, request, uidb64, token, *args, **kwargs):
        user = self.get_user(uidb64)
        if self.check_user_and_token(user, token):
            form = SetPasswordForm(user, request.POST)
            if form.is_valid():
                form.save()

                if len(user.email):
                    # Формируем параметры email
                    param_email = {
                        'to': [user.email],
                        'context': {
                            'user': model_to_dict(user, fields=[field.name for field in user._meta.fields]),
                        },
                        'subject': APP_SUBJECT_TO_RESTORE_PASSWORD,
                        'tpl_name': 'mail/password_email_confirm.html',
                    }

                    # Отправляем email
                    send_template_mail.apply_async(kwargs=param_email)

                return HttpResponseRedirect(reverse('reset_confirm'))

            else:
                return HttpResponse(render_page('confirm_passwd', {'error': dict(((i[0], i[1][0]) for i in form.errors.items()))}))

        return HttpResponse(render_page('confirm_passwd', {'error': {'token': True}}))
Exemple #2
0
 def get(self, *args, **kwargs):
     today = timezone.datetime.now()
     data = {}
     casts = casts_models.Casts.objects.filter(start__gte=today - timezone.timedelta(hours=3)).order_by('start')[:12]
     data['casts'] = vbCast(casts).data
     data['casts_tags'] = []
     return HttpResponse(render_page('casts_list', data))
Exemple #3
0
    def post(self, request, *args, **kwargs):
        form = PasswordResetForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email', False)

            active_users = User.objects.filter(username__iexact=email, email__isnull=False, is_active=True)
            for user in active_users:
                # Save hash
                o_hash = UsersHash(user=user, hash_type=APP_USER_HASH_PASSWD)
                o_hash.save()

                # Формируем параметры email
                param_email = {
                    'to': [user.email],
                    'context': {
                        'url': 'http://{host}{url}'.format(
                            host=HOST,
                            url=reverse('reset_pwd', args=(urlsafe_base64_encode(str(user.id)), o_hash.hash_key)),
                        ),
                        'user': model_to_dict(user, fields=[field.name for field in user._meta.fields]),
                    },
                    'subject': APP_SUBJECT_TO_RESTORE_PASSWORD,
                    'tpl_name': 'mail/password_email_restore.html',
                }

                # Отправляем email
                send_template_mail.apply_async(kwargs=param_email)

            return HttpResponseRedirect(reverse('reset_done'))

        else:
             HttpResponse(render_page('reset_passwd', {'error': u'Введите корректный email'}))
Exemple #4
0
    def get(self, request, **kwargs):
        resp_dict = {
            'user': vbUserProfile(request.user.profile).data,
            'error': request.GET.get('e', None)
        }

        return HttpResponse(render_page('profile', resp_dict))
Exemple #5
0
def index_view(request):
    # Выбираем 4 новых фильма, у которых есть локации
    NEW_FILMS_CACHE_KEY = 'new_films'
    resp_dict_serialized = cache.get(NEW_FILMS_CACHE_KEY)
    # Расчитываем новинки, если их нет в кеше
    if resp_dict_serialized is None:
        o_film = film_model.Films.get_newest_films()

        # Фильмы показывались => ставим флаг просмотрено в true
        for film in o_film:
            film.was_shown = True
            film.save()

        # Сериализуем новинки и конвертируем результат в строку
        resp_dict_data = vbFilm(o_film,
                                require_relation=False,
                                extend=True,
                                many=True).data
        resp_dict_serialized = json.dumps(resp_dict_data,
                                          cls=DjangoJSONEncoder)

        # Положим результат в кеш
        cache.set(NEW_FILMS_CACHE_KEY, resp_dict_serialized, 86400)

    else:
        resp_dict_data = json.loads(resp_dict_serialized)

    # Найдем relation для фильмов, если пользователь авторизован
    if request.user.is_authenticated():
        o_user = film_model.UsersFilms.objects.filter(
            user=request.user,
            film__in=[item['id'] for item in resp_dict_data])
        o_user = reindex_by(o_user, 'film_id', True)

        for index, item in enumerate(resp_dict_data):
            if item['id'] in o_user:
                resp_dict_data[index]['relation'] = o_user[
                    item['id']].relation_for_vb_film

    # Выборка списка жанров из кеша, если есть
    genres_cache_key = film_model.Genres.get_cache_key()
    genres_data = cache.get(genres_cache_key)

    if genres_data is None:
        try:
            genres_data = list(film_model.Genres.get_grouped_genres())
            cache.set(genres_cache_key, genres_data, 86400)
        except:
            genres_data = []

    # Формируем ответ
    data = {
        'films_new': resp_dict_data,
        'filter_genres': genres_data,

        # Список рекомендуемых фильмов
        'films': get_recommend_film(request),
    }

    return HttpResponse(render_page('index', data), status.HTTP_200_OK)
Exemple #6
0
    def post(self, *args, **kwargs):
        register_form = CustomRegisterForm(data=self.request.POST)
        if register_form.is_valid():
            user = register_form.save()
            kw = {
                'token': user.auth_token.key,
                '_': timezone.now().date().strftime("%H%M%S"),
            }

            url_redirect = url_with_querystring(reverse('tokenize'), **kw)
            # url = "http://{host}{url}".format(host=self.request.get_host(), url=url_redirect)
            # context = {'user': user, 'redirect_url': url}
            #
            # kw = dict(subject=APP_SUBJECT_TO_CONFIRM_REGISTER,
            #           tpl_name='confirmation_register.html',
            #           context=context,
            #           to=[user.email])
            # send_template_mail.apply_async(kwargs=kw)

            transaction.commit()
            return redirect(url_redirect)

        else:
            transaction.rollback()
            resp_dict = {'error': dict(((i[0], i[1][0]) for i in register_form.errors.items()))}
            return HttpResponse(render_page('register', resp_dict))
Exemple #7
0
 def post(self, request, **kwargs):
     uprofile_form = UsersProfileForm(data=request.POST, instance=request.user)
     if uprofile_form.is_valid():
         try:
             uprofile_form.save()
         except Exception as e:
             return HttpResponse(render_page('profile', {'error': e}))
     return redirect('profile_view')
Exemple #8
0
def feed_view(request):
    if request.user.is_authenticated():
        # Сериализуем
        try:
            o_feed = vbFeedElement(calc_feed(request.user.id), many=True).data
        except Exception, e:
            raise Http404

        return HttpResponse(render_page('feed', {'feed': o_feed}))
Exemple #9
0
def send_template_mail(subject, tpl_name, context, to, jade_render=False):
    if jade_render:
        tpl = render_page(tpl_name, context, False)
    else:
        tpl = render_to_string(tpl_name, context)

    msg = EmailMultiAlternatives(subject=subject, to=to)
    msg.attach_alternative(tpl, 'text/html')
    msg.send()
Exemple #10
0
    def get(self, *args, **kwargs):
        if self.request.user.is_authenticated():
            # Сериализуем
            try:
                o_feed = vbFeedElement(calc_feed(self.request.user.id), many=True).data
            except Exception, e:
                raise Http404

            return HttpResponse(render_page('feed', {'feed': o_feed}))
Exemple #11
0
    def get(self, *args, **kwargs):
        resp_dict = film_to_view(kwargs['film_id'], similar=True)

        # Trailer
        trailer = film_model.FilmExtras.get_trailer_by_film(kwargs['film_id'], first=True)
        if not trailer is None:
            resp_dict['trailer'] = trailer.url

        return HttpResponse(render_page('film', {'film': resp_dict}))
Exemple #12
0
    def get(self, *args, **kwargs):
        # Выбираем 4 новых фильма, у которых есть локации
        NEW_FILMS_CACHE_KEY = 'new_films'
        resp_dict_serialized = cache.get(NEW_FILMS_CACHE_KEY)
        # Расчитываем новинки, если их нет в кеше
        if resp_dict_serialized is None:
            o_film = film_model.Films.get_newest_films()

            # Фильмы показывались => ставим флаг просмотрено в true
            for film in o_film:
                film.was_shown = True
                film.save()

            # Сериализуем новинки и конвертируем результат в строку
            resp_dict_data = vbFilm(o_film, require_relation=False, extend=True, many=True).data
            resp_dict_serialized = json.dumps(resp_dict_data, cls=DjangoJSONEncoder)

            # Положим результат в кеш
            cache.set(NEW_FILMS_CACHE_KEY, resp_dict_serialized, 86400)

        else:
            resp_dict_data = json.loads(resp_dict_serialized)

        # Найдем relation для фильмов, если пользователь авторизован
        if self.request.user.is_authenticated():
            o_user = film_model.UsersFilms.objects.filter(
                user=self.request.user, film__in=[item['id'] for item in resp_dict_data]
            )
            o_user = reindex_by(o_user, 'film_id', True)

            for index, item in enumerate(resp_dict_data):
                if item['id'] in o_user:
                    resp_dict_data[index]['relation'] = o_user[item['id']].relation_for_vb_film

        # Топ комментариев к фильмам  пользователей
        comments = content_model.Comments.get_top_comments_with_rating(struct=True)

        # Выборка списка жанров из кеша, если есть
        genres_cache_key = film_model.Genres.get_cache_key()
        genres_data = cache.get(genres_cache_key)

        if genres_data is None:
            try:
                genres_data = list(film_model.Genres.get_grouped_genres())
                cache.set(genres_cache_key, genres_data, 86400)
            except:
                genres_data = []

        # Формируем ответ
        data = {
            'films_new': resp_dict_data,
            'filter_genres': genres_data,
            'comments': comments,
            'films': get_recommend_film(self.request),
        }

        return HttpResponse(render_page('index', data), status.HTTP_200_OK)
Exemple #13
0
def film_view(request, film_id, *args, **kwargs):
    resp_dict, o_film = film_to_view(film_id)
    resp_dict['similar'] = calc_similar(o_film)

    # Trailer
    trailer = film_model.FilmExtras.get_trailer_by_film(film_id, first=True)
    if not trailer is None:
        resp_dict['trailer'] = trailer.url

    return HttpResponse(render_page('film', {'film': resp_dict}))
Exemple #14
0
def playlist_view(request, film_id=None, *args, **kwargs):
    if not film_id:
        film_id = 1

    if request.user.is_authenticated():
        # Init data
        film_data = {}
        playlist = {'id': 0}
        film_id = int(film_id)

        # Выборка плейлиста
        playlist_data = film_model.Films.objects.\
            filter(uf_films_rel__user=request.user.id, uf_films_rel__status=APP_USERFILM_STATUS_PLAYLIST).\
            order_by('uf_films_rel__created')

        # Обработка плейлиста
        len_playlist = len(playlist_data)
        if len_playlist > 0:
            if film_id > len(playlist_data) or film_id < 1:
                return redirect('playlist_film_view', film_id=1)

            def arrow_data(data, f_id):
                return {'id': f_id, 'name': data.name}

            if film_id < len(playlist_data):
                playlist['next'] = arrow_data(playlist_data[film_id],
                                              film_id + 1)

            if film_id > 1:
                playlist['previous'] = arrow_data(playlist_data[film_id - 2],
                                                  film_id - 1)

            film = playlist_data[film_id - 1]
            film_data, o_film = film_to_view(film.id)

        # Update playlist
        playlist.update({
            'id': film_id,
            'film': film_data,
            'total_cnt': len_playlist,
            'items': vbFilm(playlist_data, many=True).data,

            # Список рекомендуемых фильмов
            'films': get_recommend_film(request),
        })

        return HttpResponse(
            render_page('playlist', {
                'playlist': playlist,
                'film': film_data
            }))

    return redirect('login_view')
Exemple #15
0
    def post(self, request, **kwargs):
        form = UsersProfileForm(data=request.POST, files=request.FILES, instance=request.user)
        if form.is_valid():
            profile = form.save(commit=False, send_email=True)
            image = form.cleaned_data['avatar']

            if isinstance(profile, dict):
                t = vbUserProfile(request.user.profile).data
                t.update(request.POST.dict())
                return HttpResponse(render_page('profile', {'user': t, 'error': profile}))
            
            if image:
                up = UsersPics.objects.create(user=request.user, type=APP_USER_PIC_TYPE_LOCAL)
                up.image = image  # чтобы в имени был id
                up.save()
                profile.userpic_id = up.pk
            profile.save()

            return HttpResponse(render_page('profile', {'user': vbUserProfile(profile).data}))

        return redirect('profile_view')
Exemple #16
0
    def get(self, request, *args, **kwargs):
        key = request.GET.get(APP_USER_ACTIVE_KEY, None)
        if key is None:
            raise Http404

        user_hash = UsersHash.get_by_hash(hash_key=key, hash_type=[APP_USER_HASH_EMAIL, APP_USER_HASH_REGISTR])
        if user_hash is None:
            raise Http404

        profile = user_hash.user.profile
        profile.confirm_email = True
        profile.save()

        return HttpResponse(render_page('confirm_email', {}))
Exemple #17
0
    def post(self, *args, **kwargs):
        login_form = AuthenticationForm(data=self.request.POST)
        if login_form.is_valid():
            user = login_form.get_user()
            kw = {
                'token': user.auth_token.key,
                '_': timezone.now().date().strftime("%H%M%S")
            }
            if self.request.META['HTTP_HOST'] == HOST and not HOST+'/login' in self.request.META['HTTP_REFERER']:
                kw.update(back_url=self.request.META['HTTP_REFERER'])
            url = url_with_querystring(reverse('tokenize'), **kw)
            return HttpResponseRedirect(url)

        else:
            return HttpResponse(render_page('login', {'error': u'Введите корректный логин или пароль'}))
Exemple #18
0
 def get(self, *args, **kwargs):
     cast_id = int(kwargs.get('cast_id', None))
     today = timezone.datetime.now()
     data = {}
     cast = casts_models.Casts.objects.get(id=cast_id)
     chat_items = casts_models.CastsChatsMsgs.objects.filter(cast_id=cast_id)
     msgs_list = []
     for item in chat_items:
         user = {'id': item.user.id, 'name': u' '.join([item.user.first_name, item.user.last_name]), 'avatar': ""}
         msgs_list.append({'user': user, 'text': item.text})
     other_casts = casts_models.Casts.objects.filter(start__gte=today - timezone.timedelta(hours=3)).order_by('start').exclude(id=cast_id)[:12]
     data['cast'] = vbCast(cast).data
     data['cast']['chat_items'] = msgs_list
     data['online_casts'] = vbCast(other_casts).data
     return HttpResponse(render_page('cast', data))
Exemple #19
0
    def get(self, *args, **kwargs):
        try:
            user_id = self.kwargs['user_id']
        except KeyError:
            return HttpResponseBadRequest()

        try:
            user = User.objects.get(pk=user_id)
        except User.DoesNotExist:
            raise Http404

        try:
            uvb = vbUser(user, extend=True, genres=True, friends=True)
            days = (timezone.now() - uvb.data['regdate']).days
            how_long = numeral.get_plural(days, (u'день', u'дня', u'дней'))

            default_user = uvb.data
            default_user.update({
                'regdate': uvb.data['regdate'].strftime("%Y-%m-%d"),
                'how_long': how_long
            })

            films = Films.objects.filter(uf_films_rel__user=user, uf_films_rel__subscribed=APP_USERFILM_SUBS_TRUE)
            films = Paginator(films, APP_USERS_API_DEFAULT_PER_PAGE).page(APP_USERS_API_DEFAULT_PAGE)
            vbf = vbFilm(films.object_list, many=True)

            actors = Persons.objects.filter(up_persons_rel__user=user, pf_persons_rel__p_type=APP_PERSON_ACTOR).distinct('id')
            actors = Paginator(actors, APP_USERS_API_DEFAULT_PER_PAGE).page(APP_USERS_API_DEFAULT_PAGE)
            vba = vbPerson(actors.object_list, many=True)

            directors = Persons.objects.filter(up_persons_rel__user=user, pf_persons_rel__p_type=APP_PERSON_DIRECTOR).distinct()
            directors = Paginator(directors, APP_USERS_API_DEFAULT_PER_PAGE).page(APP_USERS_API_DEFAULT_PAGE)
            vbd = vbPerson(directors.object_list, many=True)

            # Сериализуем
            o_feed = vbFeedElement(calc_feed(user.id), many=True).data

            default_user.update({
                'films': vbf.data,
                'actors': vba.data,
                'feed': o_feed,
                'directors': vbd.data,
            })

            return HttpResponse(render_page('user', {'user': default_user}))

        except Exception as e:
            return HttpResponseServerError(e)
Exemple #20
0
    def get(self, *args, **kwargs):
        try:
            user_id = self.kwargs['user_id']
        except KeyError:
            return HttpResponseBadRequest()

        try:
            user = User.objects.get(pk=user_id)
        except User.DoesNotExist:
            raise Http404

        try:
            uvb = vbUser(user, extend=True, genres=True, friends=True)
            days = (timezone.now() - uvb.data['regdate']).days
            how_long = numeral.get_plural(days, (u'день', u'дня', u'дней'))

            default_user = uvb.data
            default_user.update({
                'regdate': uvb.data['regdate'].strftime("%Y-%m-%d"),
                'how_long': how_long
            })

            films = Films.objects.filter(uf_films_rel__user=user, uf_films_rel__subscribed=APP_USERFILM_SUBS_TRUE)
            films = Paginator(films, APP_USERS_API_DEFAULT_PER_PAGE).page(APP_USERS_API_DEFAULT_PAGE)
            vbf = vbFilm(films.object_list, many=True)

            actors = Persons.objects.filter(up_persons_rel__user=user, pf_persons_rel__p_type=APP_PERSON_ACTOR).distinct('id')
            actors = Paginator(actors, APP_USERS_API_DEFAULT_PER_PAGE).page(APP_USERS_API_DEFAULT_PAGE)
            vba = vbPerson(actors.object_list, many=True)

            directors = Persons.objects.filter(up_persons_rel__user=user, pf_persons_rel__p_type=APP_PERSON_DIRECTOR).distinct()
            directors = Paginator(directors, APP_USERS_API_DEFAULT_PER_PAGE).page(APP_USERS_API_DEFAULT_PAGE)
            vbd = vbPerson(directors.object_list, many=True)

            # Сериализуем
            o_feed = vbFeedElement(calc_feed(user.id), many=True).data

            default_user.update({
                'films': vbf.data,
                'actors': vba.data,
                'feed': o_feed,
                'directors': vbd.data,
            })

            return HttpResponse(render_page('user', {'user': default_user}))

        except Exception as e:
            return HttpResponseServerError(e)
Exemple #21
0
    def get(self, *args, **kwargs):
        film_id = kwargs.get('film_id', 1)
        if self.request.user.is_authenticated():
            # Init data
            film_data = {}
            playlist = {'id': 0}
            film_id = int(film_id)

            # Выборка плейлиста
            playlist_data = film_model.Films.objects.\
                filter(uf_films_rel__user=self.request.user.id, uf_films_rel__status=APP_USERFILM_STATUS_PLAYLIST).\
                order_by('uf_films_rel__created')

            # Обработка плейлиста
            len_playlist = len(playlist_data)
            if len_playlist > 0:
                if film_id > len(playlist_data) or film_id < 1:
                    return redirect('playlist_film_view', film_id=1)

                def arrow_data(data, f_id):
                    return {'id': f_id, 'name': data.name}

                if film_id < len(playlist_data):
                    playlist['next'] = arrow_data(playlist_data[film_id], film_id+1)

                if film_id > 1:
                    playlist['previous'] = arrow_data(playlist_data[film_id-2], film_id-1)

                film = playlist_data[film_id-1]
                film_data = film_to_view(film.id)

            # Update playlist
            playlist.update({
                'id': film_id,
                'film': film_data,
                'total_cnt': len_playlist,
                'items': vbFilm(playlist_data, many=True).data,

                # Список рекомендуемых фильмов
                'films': get_recommend_film(self.request),
            })

            return HttpResponse(render_page('playlist', {'playlist': playlist, 'film': film_data}))

        return redirect('login_view')
Exemple #22
0
    def get(self, *args, **kwargs):
        back_url = self.request.GET['back_url'] if 'back_url' in self.request.GET else reverse('index_view')
        token = self.request.GET['token'] if 'token' in self.request.GET else self.request.user.auth_token.key
        try:
            user = Token.objects.get(key=token).user
        except Token.DoesNotExist:
            return HttpResponse(render_page('login', {'error': u'Неверный токен пользователя'}))

        session = create_new_session(user)

        response = HttpResponseRedirect(back_url)
        max_age = 30 * 24 * 60 * 60 # two weeks
        expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
        response.set_cookie('x-token', token, max_age=max_age, expires=expires)
        response.set_cookie('x-session', session.token.key, max_age=max_age, expires=expires)
        response.delete_cookie('sessionid')

        return response
Exemple #23
0
    def post(self, *args, **kwargs):
        data = self.request.POST
        login_form = AuthenticationForm(data=data)
        if login_form.is_valid():
            user = login_form.get_user()
            kw = {
                'token': user.auth_token.key,
                '_': timezone.now().date().strftime("%H%M%S")
            }

            if self.request.META['HTTP_HOST'] == HOST and not HOST+'/login' in self.request.META['HTTP_REFERER']:
                kw.update(back_url=self.request.META['HTTP_REFERER'])

            url = url_with_querystring(reverse('tokenize'), **kw)
            return HttpResponseRedirect(url)

        else:
            return HttpResponse(render_page('login', {'error': u'Введите корректный логин или пароль'}))
Exemple #24
0
    def post(self, *args, **kwargs):
        register_form = CustomRegisterForm(data=self.request.POST)
        if register_form.is_valid():
            committed = False
            try:
                user = register_form.save(send_email=True)
                url_redirect = url_with_querystring(
                    reverse('tokenize'),
                    **{
                        'token': user.auth_token.key,
                        '_': timezone.now().date().strftime("%H%M%S"),
                    }
                )
                transaction.commit()
                committed = True

                return redirect(url_redirect)

            except Exception, e:
                resp_dict = {'error': 'Ошибка в сохранении данных.'}
                return HttpResponse(render_page('register', resp_dict))

            finally:
Exemple #25
0
    def get(self, *args, **kwargs):
        back_url = self.request.GET['back_url'] if 'back_url' in self.request.GET else reverse('index_view')
        token = self.request.GET['token'] if 'token' in self.request.GET else self.request.user.auth_token.key
        try:
            user = Token.objects.get(key=token).user
        except Token.DoesNotExist:
            return HttpResponse(render_page('login', {'error': u'Неверный токен пользователя'}))

        session = create_new_session(user)

        # 30 days in the seconds
        max_age = 30 * 86400

        # Set expires
        expires = datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age)
        expires = datetime.datetime.strftime(expires, "%a, %d-%b-%Y %H:%M:%S GMT")

        # Set Response
        response = HttpResponseRedirect(back_url)
        response.set_cookie('x-token', token, max_age=max_age, expires=expires)
        response.set_cookie('x-session', session.key, max_age=max_age, expires=expires)
        response.delete_cookie('sessionid')

        return response
Exemple #26
0
    def get(self, *args, **kwargs):
        try:
            person = film_model.Persons.objects.get(pk=kwargs['resource_id'])
        except film_model.Persons.DoesNotExist:
            raise Http404

        crutch = vbPerson(person, extend=True).data

        # костыль, до починки парсинга этих данных роботом.
        if not crutch.get('birthdate', False):
            d1 = date(1960, 1, 1)
            d2 = date(1980, 12, 12)
            delta = d2 - d1
            delta = delta.days*24*60*60
            seconds = randrange(delta)
            birthdate = (d1 + timedelta(seconds=seconds))
            crutch['birthdate'] = birthdate.strftime('%d %B %Y')
            crutch['years_old'] = date.today().year - birthdate.year

        # Выбираем фильмографию
        pfs = film_model.PersonsFilms.objects.filter(person=person)[:12]
        crutch['filmography'] = vbFilm([pf.film for pf in pfs], many=True).data

        return HttpResponse(render_page('person', {'person': crutch}))
Exemple #27
0
def person_view(request, resource_id):
    try:
        person = film_model.Persons.objects.get(pk=resource_id)
    except film_model.Persons.DoesNotExist:
        raise Http404

    vbp = vbPerson(person, extend=True)
    crutch = vbp.data  # костыль, до починки парсинга этих данных роботом.
    if not vbp.data['birthdate']:
        d1 = date(1960, 1, 1)
        d2 = date(1980, 12, 12)
        delta = d2 - d1
        delta = delta.days * 24 * 60 * 60
        seconds = randrange(delta)
        birthdate = (d1 + timedelta(seconds=seconds))
        crutch['birthdate'] = birthdate.strftime('%d %B %Y')
        crutch['years_old'] = date.today().year - birthdate.year

    pfs = film_model.PersonsFilms.objects.filter(
        person=person)[:12]  # почему-то 12 первых фильмов. Был пагинатор
    vbf = vbFilm([pf.film for pf in pfs], many=True)
    crutch['filmography'] = vbf.data

    return HttpResponse(render_page('person', {'person': crutch}))
Exemple #28
0
 def get(self, *args, **kwargs):
     return HttpResponse(render_page('register', {}))
Exemple #29
0
 def get(self, *args, **kwargs):
     response = HttpResponse(render_page('login', {}))
     response.delete_cookie("x-session")
     response.delete_cookie("x-token")
     return response
Exemple #30
0
def password_reset_confirm(request):
    return HttpResponse(render_page('confirm_passwd', {'confirm': True}))
Exemple #31
0
def password_reset_done(request):
    return HttpResponse(render_page('reset_passwd', {'send': True}))
Exemple #32
0
 def get(self, *args, **kwargs):
     return HttpResponse(render_page('register', {}))
Exemple #33
0
    return redirect('index_view')


def search_view(request, *args, **kwargs):
    # Устанавливаем ответ по умолчанию и вызываем сериализатор поиска
    resp_dict = {
        'films': [],
    }

    if request.REQUEST.get('text'):
        try:
            resp_dict['films'] = SearchFilmsView.as_view()(
                request, use_thread=True).data
            resp_dict['search_text'] = request.REQUEST.get('text')
        except Exception, e:
            pass

    return HttpResponse(render_page('search', resp_dict))


def get_recommend_film(request):
    try:
        o_recommend = SearchFilmsView.as_view()(request,
                                                use_thread=True,
                                                recommend=True).data
        o_recommend = o_recommend['items']
    except Exception, e:
        o_recommend = []

    return o_recommend
Exemple #34
0
    def get(self, request, uidb64, token, *args, **kwargs):
        user = self.get_user(uidb64)
        if self.check_user_and_token(user, token):
            return HttpResponse(render_page('confirm_passwd', {}))

        return HttpResponse(render_page('confirm_passwd', {'error': {'token': True}}))
Exemple #35
0
 def get(self, *args, **kwargs):
     response = HttpResponse(render_page('login', {}))
     response.delete_cookie("x-session")
     response.delete_cookie("x-token")
     return response
Exemple #36
0
 def get(self, request, **kwargs):
     if isinstance(request.user, AnonymousUser):
         return redirect("login_view")
     resp_dict = {'user': vbUserProfile(request.user.profile).data,
                  'error': request.GET.get('e', None)}
     return HttpResponse(render_page('profile', resp_dict))
Exemple #37
0
    def get(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponse(render_page('reset_passwd', {}))

        raise Http404
Exemple #38
0
 def get(self, *args, **kwargs):
     return HttpResponse(render_page('restore_password', {}))
Exemple #39
0
                return redirect(url_redirect)

            except Exception, e:
                resp_dict = {'error': 'Ошибка в сохранении данных.'}
                return HttpResponse(render_page('register', resp_dict))

            finally:
                if not committed:
                    transaction.rollback()

        else:
            transaction.rollback()
            resp_dict = {'error': dict(((i[0], i[1][0]) for i in register_form.errors.items()))}

            return HttpResponse(render_page('register', resp_dict))


class LoginUserView(View):

    def get(self, *args, **kwargs):
        response = HttpResponse(render_page('login', {}))
        response.delete_cookie("x-session")
        response.delete_cookie("x-token")
        return response

    def post(self, *args, **kwargs):
        data = self.request.POST
        login_form = AuthenticationForm(data=data)
        if login_form.is_valid():
            user = login_form.get_user()