Example #1
0
def login_form(request):
    """Creates context for a login form custom template
    and sends it for validation."""
    if 'login' and 'password' in request.POST:
        return {'allauth_login_form': LoginForm(request.POST)}
    else:
        return {'allauth_login_form': LoginForm()}
Example #2
0
def user_login(request):
    """
    Функция авторизации по ajax
    """
    if request.is_ajax:
        print('ajax')
        login_form = LoginForm(request.POST)
        login = request.POST.get('login')
        password = request.POST.get('password')
        if login_form.is_valid():
            user = auth.authenticate(username=login, password=password)
            print(user)
            if user and user.is_active:
                auth.login(request, user)
                data = {'reload': True}
                return JsonResponse(data)

        context = {
            'reload': False,
            'login_form': login_form,
            'signup_form': SignupForm,
        }
        context.update(csrf(request))
        html_content = loader.render_to_string(
            template_name='include/user/user.html', context=context)
        data = {'html_content': html_content}
        return JsonResponse(data)
    else:
        return Http404
Example #3
0
def home(request):
    if request.user.is_authenticated():
        s = Session.objects.get(session_key=request.session.session_key)
        t = Tracker.objects.create(session=s, source='2')
        if request.user.userprofile.workplace_type in ['A', 'B']:
            return render(request, 'home.html')
        elif request.user.userprofile.workplace_type in ['C', 'O']:
            return redirect('/feed')
        else:
            return redirect('/set/')
    else:
        q = request.GET.get('q')
        try:
            s = Session.objects.get(session_key=request.session.session_key)
        except Exception:
            s = None
        t = Tracker.objects.create(session=s, source=q)
        if request.GET.get('audience') == 'team':
            return render(request, 'cover_team.html', {
                'form_signup': SignupForm(),
                'form_login': LoginForm()
            })
        else:
            return render(request, 'cover.html', {
                'form_signup': SignupForm(),
                'form_login': LoginForm()
            })
Example #4
0
    def post(self, request, *args, **kwargs):
        """POSTリクエスト用のメソッド"""
        # リクエストからフォームを作成
        form = LoginForm(request.POST)
        # バリデーション(ユーザーの認証も合わせて実施)
        if not form.is_valid():
            # バリデーションNGの場合はログイン画面のテンプレートを再表示
            return render(request, 'accounts/login.html', {'form': form})

        # ユーザーオブジェクトをフォームから取得
        user = form.get_user()

        # ログイン処理(取得したユーザーオブジェクトをセッションに保存 & ユーザーデータを更新)
        auth_login(request, user)

        # ログイン後処理(ログイン回数を増やしたりする。本来は user_logged_in シグナルを使えばもっと簡単に書ける)
        user.post_login()

        # ロギング
        logger.info("User(id={}) has logged in.".format(user.id))

        # フラッシュメッセージを画面に表示
        messages.info(request, "ログインしました。")

        # ダッシュボード画面にリダイレクト
        return redirect(reverse('dashborad:index'))
def ajax_login(request):
    if request.is_ajax() and request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            login(request, request.user)
            data = {'status': 'success'}
        else:
            data = json.loads(errors_to_json(form.errors))
        return json_result(request, data)
    else:
        return render_to_response("account/ajax_login.html", {}, context_instance=RequestContext(request))
Example #6
0
def modal_login(request, **kwargs):
    
   # redirect_field_name = kwargs.pop("next")
    if request.method == "POST":
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            next = request.POST.get("next","/food/")
            login_form.login(request, redirect_url=next)
            return HttpResponse(next)
        redirect_field_name, redirect_field_value = "next", request.referer
        response = render(request,"login_error.html",locals())
        response.status_code = 400 
        return response
Example #7
0
def login(request):
    categories = Category.objects.all()
    cart = Cart(request)
    if request.method == "POST":
        form = LoginForm(request=request, data=request.POST)
        if form.is_valid():
            return redirect('shop:index')
    else:
        form = LoginForm()

    return render(request, 'registration/login.html', {
        'form': form,
        'categories': categories,
        'cart': cart
    })
Example #8
0
def profile(request):
    """ Display the user's profile. """
    profile = get_object_or_404(UserProfile, user=request.user)

    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            messages.success(request, 'Profile updated successfully')
        else:
            messages.error(request,
                           'Update failed. Please ensure the form is valid.')
    else:
        form = UserProfileForm(instance=profile)
    orders = profile.orders.all()
    fav_list = Favourite.objects.filter(user=request.user, status=True)

    template = 'profiles/profile.html'
    context = {
        'form': form,
        'orders': orders,
        'fav_list': fav_list,
        'on_profile_page': True,
        'login_form': LoginForm(),
    }

    return render(request, template, context)
Example #9
0
    def get_context_data(self, **kwargs):
        context_data = super(StudentInfoView, self).get_context_data(**kwargs)
        reg = self.temporaryRegistration

        context_data.update({
            'reg':
            reg,
            'payAtDoor':
            reg.payAtDoor,
            'currencySymbol':
            getConstant('general__currencySymbol'),
            'subtotal':
            sum([x.price for x in reg.temporaryeventregistration_set.all()]),
        })

        if reg.payAtDoor or self.request.user.is_authenticated or not getConstant(
                'registration__allowAjaxSignin'):
            context_data['show_ajax_form'] = False
        else:
            # Add a login form and a signup form
            context_data.update({
                'show_ajax_form': True,
                'login_form': LoginForm(),
                'signup_form': SignupForm(),
            })

        return context_data
Example #10
0
def index(request):
    """
    This view provides the landing page for zhehe application

    Containing two forms:
        - Signin
        - Newsletter

    And several other information regarding the application.
    Also access to user registration etc.

    :param request: Django request Object
    :type request: django.core.handlers.wsgi.WSGIRequest
    :return: Django render object containing HttpResponse
    :rtype: django.http.response.HttpResponse
    """
    template_name: str = 'zhehe_user_app/zhehe_index/skeleton.html'
    newsletter_form = Newsletter()
    signin_form = LoginForm()
    if request.method == 'POST':
        newsletter_form = Newsletter(request.POST)
        if newsletter_form.is_valid():
            print(newsletter_form.cleaned_data)
        else:
            print(newsletter_form.errors)
    return render(request=request,
                  template_name=template_name,
                  status=200,
                  context={
                      'newsletter': newsletter_form,
                      'signin': signin_form
                  })
Example #11
0
def home(request):
    if not request.user.is_authenticated():
        login_form = LoginForm()
    else:
        login_form = None

    return render(request, 'core/home.html', {'form': login_form})
Example #12
0
def create_password(request, token):
    if request.user.is_authenticated():
        return redirect('order:details', token=token)
    order = get_object_or_404(Order, token=token)
    email = order.user_email
    form_data = request.POST.copy()
    if form_data:
        form_data.update({'email': email})
    register_form = PasswordForm(form_data or None)
    if User.objects.filter(email=email).exists():
        login_form = LoginForm(initial={'login': email})
    else:
        login_form = None
    if register_form.is_valid():
        register_form.save(request)
        password = form_data.get('password1')
        auth_user = auth.authenticate(email=email, password=password)
        if auth_user is not None:
            auth.login(request, auth_user)
        attach_order_to_user(order, auth_user)
        return redirect('order:details', token=token)
    ctx = {
        'form': register_form,
        'email': email,
        'order': order,
        'login_form': login_form
    }
    return TemplateResponse(request, 'order/create_password.html', ctx)
Example #13
0
    def get(self, request):
        search_query = request.GET.get('search', '')

        if search_query:
            products_list = Product.objects.filter(
                Q(title__icontains=search_query)
                | Q(text__icontains=search_query))
        else:
            products_list = Product.objects.filter(available=True)

        paginator = Paginator(products_list, 2)
        page_number = request.GET.get('page', 1)
        page, prev_url, next_url = product_paginator(paginator, page_number)
        formlogin = LoginForm()

        category = get_object_or_404(Category)

        context = {
            'category': category,
            'page_object': page,
            'next_url': next_url,
            'prev_url': prev_url,
            'formlogin': formlogin,
        }

        return render(request, 'index.html', context)
Example #14
0
def add_login_form(context):
    """Return LoginForm is user is not already logged in."""
    from allauth.account.forms import LoginForm
    user = context['request'].user
    if not user.is_authenticated():
        context['login_form'] = LoginForm()
        return context
Example #15
0
    def get_context_data(self, **kwargs):
        context_data = super(StudentInfoView, self).get_context_data(**kwargs)

        context_data.update({
            'regInfo':
            self.request.session[REG_VALIDATION_STR].get('regInfo', {}),
            'payAtDoor':
            self.request.session[REG_VALIDATION_STR].get('payAtDoor', False),
            'currencySymbol':
            getConstant('general__currencySymbol'),
        })

        # Add the Series, Event, and DanceRole objects to the context data based on what was submitted
        # through the form.
        subtotal = 0

        for k, v in context_data['regInfo'].get('events', {}).items():
            event = Event.objects.prefetch_related('pricingTier').get(id=k)

            dropin_keys = [x for x in v.keys() if x.startswith('dropin_')]
            if dropin_keys:

                name = _('DROP IN: %s' % event.name)
                base_price = event.getBasePrice(dropIns=len(dropin_keys))
            else:
                name = event.name
                base_price = event.getBasePrice(
                    payAtDoor=context_data['payAtDoor'])

            subtotal += base_price

            if v.get('role'):
                role_name = DanceRole.objects.get(id=v.get('role')).name
            else:
                role_name = None

            context_data['regInfo']['events'][k].update({
                'name':
                name,
                'role_name':
                role_name,
                'base_price':
                base_price,
            })

        context_data['subtotal'] = subtotal

        if context_data[
                'payAtDoor'] or self.request.user.is_authenticated or not getConstant(
                    'registration__allowAjaxSignin'):
            context_data['show_ajax_form'] = False
        else:
            # Add a login form and a signup form
            context_data.update({
                'show_ajax_form': True,
                'login_form': LoginForm(),
                'signup_form': SignupForm(),
            })

        return context_data
Example #16
0
def home(request):
    if not request.user.is_authenticated:
        login_form = LoginForm()
        login_form.fields['login'].widget.attrs.pop("autofocus", None)
    else:
        login_form = None

    return render(request, 'core/home.html', {'form': login_form})
Example #17
0
def login(request, checkout):
    """
    Allows user to choose if he wants to login before checkout or continue
    as an anonymous user
    """
    if request.user.is_authenticated:
        return redirect('checkout:index')
    form = LoginForm()
    ctx = {'form': form}
    return TemplateResponse(request, 'checkout/login.html', ctx)
Example #18
0
 def get(self, request, *args, **kwargs):
     if request.user.is_authenticated():
         buildings = request.user.building_set.all()
         context = {'object_list': buildings}
         return render(request, 'dashboard/buildings/list_building.html',
                       context)
     else:
         form = LoginForm()
         context = {'form': form}
         return render(request, 'account/login.html', context)
Example #19
0
    def get_context_data(self, **kwargs):
        if 'form' in self.request.session and 'login_form' in self.request.session:
            ctx = {}
            if self.request.session['form']:
                ctx['form'] = SignupForm(self.request.session['form'])
                ctx['form'].is_valid()
            else:
                ctx['form'] = SignupForm()
            if self.request.session['login_form']:
                ctx['login_form'] = LoginForm(self.request.session['login_form'])
                ctx['login_form'].is_valid()

            else:
                ctx['login_form'] = LoginForm()
            del self.request.session['form']
            del self.request.session['login_form']
        else:
            ctx = super(SignupView, self).get_context_data(**kwargs)
            ctx['login_form'] = LoginForm()
        return ctx
Example #20
0
def addLoginForm(request):
    # let us customize the login form!
    loginForm = LoginForm()
    loginForm.fields['password'].widget.attrs.update(
        {'class': 'mdl-textfield__input'})
    loginForm.fields['login'].widget.attrs.update(
        {'class': 'mdl-textfield__input'})
    loginForm.fields['remember'].widget.attrs.update(
        {'class': 'mdl-checkbox__input'})

    return {'login_form': loginForm}
Example #21
0
def login(request):
    # template based on allauth login page
    t = loader.get_template("courses/login.html")
    c = {'login_form': LoginForm(), 'signup_url': reverse("account_signup")}

    if 'shibboleth' in django.conf.settings.INSTALLED_APPS:
        c['shibboleth_login'] = reverse("shibboleth:login")
    else:
        c['shibboleth_login'] = False

    return HttpResponse(t.render(c, request))
Example #22
0
    def get(self, request, *args, **kwargs):
        """GETリクエスト用のメソッド"""
        # すでにログインしている場合はショップ画面へリダイレクト
        if request.user.is_authenticated:
            return redirect(reverse('dashborad:index'))

        context = {
            'form': LoginForm(),
        }
        # ログイン画面用のテンプレートに値が空のフォームをレンダリング
        return render(request, 'accounts/login.html', context)
Example #23
0
def upload_media(request):
    """Upload media view"""

    from allauth.account.forms import LoginForm

    form = LoginForm()
    context = {}
    context["form"] = form
    context["can_add"] = user_allowed_to_upload(request)
    can_upload_exp = settings.CANNOT_ADD_MEDIA_MESSAGE
    context["can_upload_exp"] = can_upload_exp

    return render(request, "cms/add-media.html", context)
Example #24
0
def login(request):
    """
    A view to render the login page
    """
    login_form = LoginForm()
    signup_form = SignupForm()

    context = {
        'login_form': login_form,
        'signup_form': signup_form,
    }

    return render(request, 'login.html', context)
Example #25
0
def home(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('projects'))
    else:
        if settings.SHIBBOLETH:
            return render(request, 'core/home.html')
        elif settings.ACCOUNT or settings.SOCIALACCOUNT:
            from allauth.account.forms import LoginForm
            return render(request, 'core/home.html', {'form': LoginForm()})
        else:
            from django.contrib.auth.forms import AuthenticationForm
            return render(request, 'core/home.html',
                          {'form': AuthenticationForm()})
Example #26
0
def all_pieces(request):
    """ A view to show all pieces, including sorting and search queries """

    pieces = Piece.objects.all()
    query = None
    categories = None
    sort = None
    direction = None

    if request.GET:
        if 'sort' in request.GET:
            sortkey = request.GET['sort']
            sort = sortkey
            if sortkey == 'name':
                sortkey = 'lower_name'
                pieces = pieces.annotate(lower_name=Lower('name'))
            if sortkey == 'category':
                sortkey = 'category__name'
            if 'direction' in request.GET:
                direction = request.GET['direction']
                if direction == 'desc':
                    sortkey = f'-{sortkey}'
            pieces = pieces.order_by(sortkey)

        if 'category' in request.GET:
            categories = request.GET['category'].split(',')
            pieces = pieces.filter(category__name__in=categories)
            categories = Category.objects.filter(name__in=categories)

        if 'q' in request.GET:
            query = request.GET['q']
            if not query:
                messages.error(request,
                               "You forgot to enter any search criteria!")
                return redirect(reverse('pieces'))

            queries = Q(name__icontains=query) | Q(
                type_of_piece__icontains=query)
            pieces = pieces.filter(queries)

    current_sorting = f'{sort}_{direction}'

    context = {
        'pieces': pieces,
        'search_term': query,
        'current_categories': categories,
        'current_sorting': current_sorting,
        'login_form': LoginForm(),
    }

    return render(request, 'pieces/pieces.html', context)
Example #27
0
def login(request, **kwargs):
    success_url = kwargs.pop("success_url", None)

    if success_url is None:
        success_url = "/"

    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            return form.login(request, redirect_url=success_url)
    else:
        form = LoginForm()

    registerform = SignupForm()

    ctx = {
        "form": form,
        "registerform": registerform,
        "redirect_field_name": "next",
        "redirect_field_value": request.REQUEST.get("next"),
        "apps": SocialApp.objects.all(),
    }
    return render_to_response("users/login.html", RequestContext(request, ctx))
Example #28
0
    def post(self, request):
        serializer = LoginInputSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        login_field = 'email'
        form_login = serializer.validated_data.get('email', '')
        if not form_login:
            form_login = serializer.validated_data.get('username', '')
            if form_login:
                login_field = 'username'

        login_data = {
            'login': form_login,
            'password': serializer.validated_data.get('password')
        }

        with transaction.atomic(), clear_messages(request):
            form = LoginForm(request=request, data=login_data)
            form_valid_or_raise(form, {'login': login_field})
            allauth_response = form.login(request)
            # commit transaction here because an implicit EmailConfirmation object may be created
            # as part of the allauth login process, and we want it to be saved

        with transaction.atomic(), clear_messages(request):
            user = getattr(form, 'user', None)
            token = handle_login_response(allauth_response,
                                          user,
                                          allow_disabled=False)
            profile = getattr(getattr(token, 'user', None), 'profile', None)
            response_serializer = UserTokenResponseSerializer({
                'token':
                token,
                'profile':
                profile
            })
            response = Response(response_serializer.data)
            return response
Example #29
0
def mf_login(request):
    form = LoginForm()
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            form.login(request)
            return redirect('mf-index')
    ctx = {
        "page": "login",
        "form": form,
        "registration_open": settings.REGISTRATION_OPEN,
    }
    return render(request, "accounts/login.html", ctx)
Example #30
0
def piece_detail(request, piece_id):
    """ A view to show an individual piece """

    piece = get_object_or_404(Piece, pk=piece_id)
    comments = Comment.objects.filter(piece=piece_id)
    fav_product = Favourite.objects.filter(piece=piece_id).last()

    context = {
        'piece': piece,
        'comments': comments,
        'fav_product': fav_product,
        'login_form': LoginForm(),
    }

    return render(request, 'pieces/piece_detail.html', context)
Example #31
0
def video_login(request, slug):
    if not request.method == 'POST':
        raise Exception('This view is meant to be called via a POST request.')

    video, created = get_or_create_video(slug)
    login_success = False
    outbound_message = dict()
    outbound_message[DATA_KEY] = {}
    form = LoginForm(data=json.loads(request.raw_post_data))

    if form.is_valid():
        user = form.user
        form.login(request)
        login_success = True

        action.send(user, verb='viewed video', action_object=video)

        userSerializer = UserSerializer(user)
        userSerialized = JSONRenderer().render(userSerializer.data)
        outbound_message[DATA_KEY]['user'] = json.loads(userSerialized)
        outbound_message[DATA_KEY]['share_url'] = reverse('profiles-share',
                                                          args=[
                                                              user.username,
                                                              slug,
                                                          ])
    else:
        outbound_message[DATA_KEY]['errors'] = \
            json.loads(errors_to_json(form.errors))

    outbound_message[EVENT_TYPE_KEY] = 'FB_LOGIN'
    outbound_message[CHANNEL_KEY] = \
        '/framebuzz/session/%s' % request.session.session_key
    outbound_message[DATA_KEY]['login_success'] = login_success

    return HttpResponse(json.dumps(outbound_message),
                        content_type="application/json")
Example #32
0
def finance_website(request):
    if request.method == "GET":
        stock = finance_stock(request)
        data = get_stock_price_data(stock)
        script, div = create_stock_price_plot(data)
        bid, ask, range_day, market_cap, beta, estimate, price = get_stock_summary_data(
            stock)

        movers = get_stock_movers(5)
        watchlist_list = Watchlist.objects.filter(user=request.user.id)
        feed = news_feed(stock)
        login_form = LoginForm()
        signup_form = SignupForm()

        context = {
            "stock": stock,
            "bid": bid,
            "ask": ask,
            "range": range_day,
            "market_cap": market_cap,
            "beta": beta,
            "estimate": estimate,
            "the_script": script,
            "the_div": div,
            "movers": movers,
            "watchlist_list": watchlist_list,
            "news": feed,
            "price": price,
            "login_form": login_form,
            "signup_form": signup_form
        }

        return render(request, "finance.html", context)

    else:
        form = WatchlistForm(request.POST)
        form.save()
        return redirect(request.get_full_path())
Example #33
0
def checkout_home(request):
    cart_obj, cart_created = Cart.objects.new_or_get(request)

    if cart_created:
        return redirect('cart:cart')
    else:
        order_obj, new_order_obj = Order.objects.get_or_create(cart=cart_obj)

    user = request.user
    billing_profile = None
    form = LoginForm()

    if user.is_authenticated:
        billing_profile, billing_profile_created = BillingProfile.objects.get_or_create(
            user=user, email=user.email)

    context = {
        'order': order_obj,
        'billing_profile': billing_profile,
        'form': form,
    }

    return render(request, 'carts/checkout.html', context)
Example #34
0
def reservation(request, id):
    service = get_object_or_404(Service, id=id)

    chosen_employee = None
    emp_size = 0
    if not service.is_active():
        raise Http404
    minTime, maxTime = getMinMaxTime(service.service_provider)

    #step2 = request.session['_step'] if '_step' in request.session
    step2 = request.GET.get('step', None)

    # POST
    step = request.POST.get('step', None)

    data = None
    if step:
        try:
            data = pickle.loads(base64.b64decode(request.POST.get('data')))  # Serializes an object from request
        except:
            raise Http404
    elif step2:
        step = step2
        if 'reservation_data' in request.session:
            data = request.session['reservation_data']
        else:
            step = None

    if (request.method != 'POST' and data is None) or step is None:
        #form = ReservationForm(request, workingHours=None, service=None)
        form = ReservationForm(request, workingHours=None, service=service)
        data = {'service_provider_id': service.service_provider_id, 'service_id': service.id}
        return render_to_response('reservations/reservation.html', locals(), context_instance=RequestContext(request))

    workingHours = WorkingHours.objects.filter(service_provider_id=service.service_provider_id)

    #formNonRegisteredUser = NonRegisteredUserForm(prefix='nonRegBtn')
    formNonRegisteredUser = NonRegisteredUserForm(provider=service.service_provider)
    loginForm = LoginForm(prefix='loginBtn')
    signupForm = SignupForm(prefix='signupBtn')

    if step == '1':
        # Service, date, time
        # form = ReservationForm(request.POST, workingHours='gergerre')
        form = ReservationForm(request, request.POST, workingHours=workingHours, service=service)
        if form.is_valid():
            chosen_employee = form.cleaned_data['employees']
            data['date'] = form.cleaned_data['date']
            data['time'] = form.cleaned_data['time']
            data['number'] = form.cleaned_data['number']
            data['employees'] = form.cleaned_data['employees']

            if request.user.is_authenticated():
                data['user_id'] = request.user.id
                data['name'] = request.user.get_full_name()
                data['phone'] = request.user.phone
                data['email'] = request.user.email
                return render_to_response('reservations/confirmation.html', locals(),
                                          context_instance=RequestContext(request))

            return render_to_response('reservations/userinfo.html', locals(), context_instance=RequestContext(request))

        return render_to_response('reservations/reservation.html', locals(), context_instance=RequestContext(request))

    if step == '2':
        if data.get('date') is None or data.get('time') is None:
            raise Http404

        if 'signupBtn' in request.POST:
            signupForm = SignupForm(request.POST, prefix='signupBtn')

            if signupForm.is_valid():
                userr = signupForm.save(request)

                data['user_id'] = userr.id
                data['name'] = userr.get_full_name()
                data['phone'] = userr.phone
                data['email'] = userr.email

                return render_to_response('reservations/confirmation.html', locals(),
                                          context_instance=RequestContext(request))

        if 'loginBtn' in request.POST:
            loginForm = LoginForm(request.POST, prefix='loginBtn')

            if loginForm.is_valid():
                data['user_id'] = loginForm.user.id
                data['name'] = loginForm.user.get_full_name()
                data['phone'] = loginForm.user.phone
                data['email'] = loginForm.user.email

                request.session['reservation_data'] = data
                return loginForm.login(request, redirect_url=reverse('reservation', args=[service.id]) + "?step=2a")

        if 'nonRegBtn' in request.POST:

            formNonRegisteredUser = NonRegisteredUserForm(request.POST, provider=service.service_provider)
            if formNonRegisteredUser.is_valid():
                data['name'] = formNonRegisteredUser.cleaned_data['name']
                data['phone'] = formNonRegisteredUser.cleaned_data['phone']
                data['email'] = formNonRegisteredUser.cleaned_data['email']
                return render_to_response('reservations/confirmation.html', locals(),
                                          context_instance=RequestContext(request))
        return render_to_response('reservations/userinfo.html', locals(), context_instance=RequestContext(request))

    if step == '2a':
        if request.user.is_authenticated():
            return render_to_response('reservations/confirmation.html', locals(),
                                      context_instance=RequestContext(request))

    if step == '3':
        # Confirmation
        if data.get('date') is None or data.get('time') is None:  # or data.get('user_id') is None:
            raise Http404
        if data.get('user_id') is not None:
            ruser = get_object_or_404(User, id=data.get('user_id'))
        else:
            ruser = None

        sync(service.service_provider)

        # Checking again if form for reservation is valid
        chosen_employee = data.get('employees')
        emp_id = None
        if chosen_employee is not None and chosen_employee != '':
            emp_id = chosen_employee.id

        form = ReservationForm(request,
                               {'date': data.get('date'), 'time': data.get('time'), 'employees': emp_id},
                               workingHours=workingHours, service=service)

        if form.is_valid():
            form_emp = None
            if chosen_employee != '':
                form_emp = chosen_employee
            reserve = Reservation(user=ruser, service=service, date=data['date'], time=data['time'],
                                  employee=form_emp)
            # Add backup fields
            reserve.user_fullname = data.get('name')
            reserve.user_phone = data.get('phone')
            reserve.user_email = data.get('email')
            reserve.service_provider = service.service_provider
            reserve.service_name = service.name
            reserve.service_duration = service.duration
            reserve.service_price = service.discounted_price()
            reserve.show_up = False
            if chosen_employee is not None and chosen_employee != '':
                reserve.employee = chosen_employee
            else:
                # if employees assigned to service, randomly choose one who is free
                if service.employees.all().__len__() > 0:
                    today_r = Reservation.objects.filter(employee__in=service.employees.all(), date=reserve.date)
                    # find free employees
                    reserveDt = datetime.datetime.combine(reserve.date, reserve.time)
                    free_emp = list(service.employees.all())
                    free_emp_editable = list(service.employees.all())
                    for emp in free_emp:
                        emp_time = EmployeeWorkingHours.objects.filter(employee=emp.id)[0].get_for_day(emp,
                                                                                                       reserve.date.weekday())
                        if not EmployeeWorkingHours.objects.filter(employee=emp.id)[0].get_for_day(emp,
                                                                                                   reserve.date.weekday()):
                            free_emp_editable.remove(emp)
                        if reserve.time < emp_time.time_from or reserveDt + datetime.timedelta(
                                minutes=reserve.service_duration) > datetime.datetime.combine(reserve.date,
                                                                                              emp_time.time_to):
                            free_emp_editable.remove(emp)
                    for r in today_r:
                        rDt = datetime.datetime.combine(r.date, r.time)
                        if r.active_during(reserveDt):
                            if r.employee in free_emp:
                                free_emp_editable.remove(r.employee)
                                # choose random employee
                    if free_emp_editable:
                        random_employee = free_emp_editable[random.randint(0, len(free_emp_editable) - 1)]
                        reserve.employee = random_employee

            # Save
            reserve.user.notification_type = 'email'
            reserve.save()
            # saving coupon is_valid
            coupons = Coupon.objects.filter(service=service.id)
            coupon_is_used = False
            for coup in coupons:
                if data['number'] == coup.number:
                    coup.is_used = True
                    coup.save()
                    coupon_is_used = True
                    # Validation checking in form

            user_page_link = '%s/u/%s' % (settings.BASE_URL, reserve.service_provider.userpage_link)
            email_to1 = data.get('email')
            email_to2 = service.service_provider.user.email
            if service.service_provider.reservation_confirmation_needed:
                subject = _('Confirmation of service reservation')
                renderedToCustomer = render_to_string('emails/reservation_customer.html',
                                                      {'reservation': reserve, 'link': user_page_link})
                renderedToProvider = render_to_string('emails/reservation_provider.html',
                                                      {'reservation': reserve, 'link': user_page_link})
                message1 = (subject, renderedToCustomer, None, [email_to1])
                message2 = (subject, renderedToProvider, None, [email_to2])
                send_mass_mail((message1, message2), fail_silently=True)
            else:
                subject = _('Confirmation of service reservation')
                renderedToCustomer = render_to_string('emails/reservation_customer.html',
                                                      {'reservation': reserve, 'link': user_page_link})
                send_mail(subject, renderedToCustomer, email_to2, [email_to1],
                          fail_silently=False)

            start = datetime.datetime.combine(reserve.date, reserve.time)
            gcal_params = urllib.urlencode({
                'action': 'TEMPLATE',
                'text': reserve.service_name.encode('utf8'),
                'dates': '%s/%s' % (datetime_to_url_format(start),
                                    datetime_to_url_format(
                                        start + datetime.timedelta(minutes=reserve.service_duration))),
                'details': reserve.service.description.encode('utf8'),
                'location': reserve.service_provider.full_address().encode('utf8'),
                'trp': 'true',
                'sprop': 'E-Narocanje',
                'sprop': 'name:%s' % settings.BASE_URL,
            })
            url_service = settings.BASE_URL + reverse('service', args=(service.id,))

            sync(service.service_provider)

            return render_to_response('reservations/done.html', locals(), context_instance=RequestContext(request))

        # Someone else has made a reservation in the meantime
        return render_to_response('reservations/alreadyreserved.html', locals(),
                                  context_instance=RequestContext(request))
    raise Http404