コード例 #1
0
ファイル: views.py プロジェクト: qkhan/NewEcommerce
def checkout_address_create_view(request):
    form = AddressForm(request.POST or None)
    context = {"form": form}
    next_ = request.GET.get('next')
    next_post = request.POST.get('next_url')
    redirect_path = next_ or next_post or None
    address_type = request.POST.get('address_type')
    print("Address Type:", address_type)
    print("next_post", next_post)
    print("redirect_path", redirect_path)
    if form.is_valid():
        print(form.cleaned_data)
        print("REQUEST")
        print(request)
        instance = form.save(commit=False)
        #address_type = form.cleaned_data.get("address_type", "shipping")

        billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(
            request)
        if billing_profile is not None:
            instance.billing_profile = billing_profile
            instance.address_type = address_type
            instance.save()
        else:
            print("Error here")
            return redirect("cart:checkout")

        request.session[address_type + "_address_id"] = instance.id
        print("Address Type: {0} | ID: {1}".format(address_type, instance.id))
        if is_safe_url(redirect_path, request.get_host()):
            return redirect(redirect_path)
        else:
            return redirect("cart:checkout")

    return redirect("cart:checkout")
コード例 #2
0
def address_check(request):
    if request.method == 'POST':
        form = AddressForm(request.POST)
        next_post = request.POST.get('next')
        billing_profile, bill_created = BillingProfile.objects.new_or_get(
            request)
        cart_obj, cart_create = Cart.objects.new_or_get(request)
        order_obj, order_create = Order.objects.new_or_get(
            billing_profile=billing_profile, cart_obj=cart_obj)

        address_type = request.POST.get('address_type')
        if form.is_valid():
            address = form.save(commit=False)

            address.address_type = address_type
            address.billing_profile = billing_profile
            address.save()

            if address_type == 'shipping':

                order_obj.shipping_address = address
                order_obj.save()
            else:
                order_obj.billing_address = address
                order_obj.save()
            return redirect(next_post)
    else:
        form = AddressForm()
    return redirect('carts:cart_checkout')
コード例 #3
0
def checkout_address_create_view(request):
    address_form = AddressForm(request.POST or None)
    context = {'form': address_form}
    _next = request.GET.get('next')
    _next_post = request.POST.get('next')
    redirect_path = _next or _next_post or None
    if address_form.is_valid():
        print(request.POST)
        print(address_form.cleaned_data)
        instance = address_form.save(commit=False)
        billing_profile, _ = BillingProfile.objects.new_or_get(request)
        if billing_profile is not None:
            address_type = request.POST.get('address_type', 'shipping')
            instance.billing_profile = billing_profile
            instance.address_type = address_type
            instance.save()
            request.session[address_type + '_address_id'] = instance.id
            print(address_type + '_address_id',
                  request.session[address_type + '_address_id'])
        else:
            print('Error occured')
            redirect('cart:checkout')

        if is_safe_url(redirect_path, request.get_host()):
            return redirect(redirect_path)
    return redirect('cart:checkout')
コード例 #4
0
ファイル: views.py プロジェクト: h4yfans/eCommerce-Web-App
def checkout_address_create_view(request):
    form = AddressForm(request.POST or None)
    next_ = request.GET.get('next')
    next_post = request.POST.get('next')
    redirect_path = next_ or next_post or None
    if form.is_valid():
        print(request.POST)
        instance = form.save(commit=False)
        billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request)

        if billing_profile is not None:
            address_type = request.POST.get('address_type', 'shipping')
            instance.billing_profile = billing_profile
            instance.address_type = request.POST.get('address_type', 'shipping')
            instance.save()

            request.session[address_type + '_address_id'] = instance.id
            print(address_type + '_address_id')

        else:
            print('Error address not saved')
            return redirect('cart:checkout')

        if is_safe_url(redirect_path, request.get_host()):
            return redirect(redirect_path)
    return redirect('cart:checkout')
コード例 #5
0
def checkout_address_create_view(request):
    form = AddressForm(request.POST or None)
    context = {"form": form}
    next_ = request.GET.get("next")
    next_post = request.POST.get("next")
    redirect_path = next_ or next_post or None
    if form.is_valid():
        print(request.POST)
        instance = form.save(commit=False)
        billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(
            request)
        if billing_profile is not None:
            address_type = request.POST.get("address_type", 'shipping')
            instance.billing_profile = billing_profile
            instance.address_type = request.POST.get('address_type',
                                                     'shipping')
            instance.save()

            request.session[address_type + "_address_id"] = instance.id
            print(request.session[address_type + "_address_id"])
        else:
            # TODO put a real error here that the address didn't save
            print("Error trying to save address")
            return redirect("cart:checkout")

        if is_safe_url(redirect_path, request.get_host()):
            return redirect(redirect_path)
        else:
            return redirect("cart:checkout")
    return redirect("cart:checkout")
コード例 #6
0
def checkout_address_create_view(request):
    form = AddressForm(request.POST or None)
    context = {"form": form}
    next_ = request.GET.get("next")
    next_post = request.POST.get("next")
    redirect_path = next_ or next_post or None
    if form.is_valid():
        instance = form.save(commit=False)
        billing_profile, billing_profile_created = BillinigProfile.objects.new_or_get(
            request)
        if billing_profile is not None:
            address_type = request.POST.get("address_type", "shipping")
            instance.billing_profile = billing_profile
            instance.address_type = address_type
            instance.save()
            request.session[address_type + "_address_id"] = instance.id
        else:
            return redirect("cart:checkout")
        print(request.POST)
        if is_safe_url(redirect_path, request.get_host()):
            print(redirect_path)
            return redirect(redirect_path)
        else:
            return redirect("cart:checkout")
    return redirect("cart:checkout")
コード例 #7
0
def address_update(request):
    if request.method == 'POST':
        # Is this a shipping or billing address????
        address_type = request.POST.get('address_type')
        address_id = request.POST.get('address')
        print('address', address_id)

        address = Address.objects.get(id=address_id)

        billing_profile, bill_created = BillingProfile.objects.new_or_get(
            request)
        cart_obj, cart_created = Cart.objects.new_or_get(request)
        order_obj, order_created = Order.objects.new_or_get(
            billing_profile=billing_profile, cart_obj=cart_obj)

        form = AddressForm(request.POST)
        if form.is_valid():

            # Now we have to associate to the order
            if address_type == 'shipping':
                # How do we get the order?
                order_obj.shipping_address = address
                order_obj.save()
            if address_type == 'billing':
                order_obj.billing_address = address
                order_obj.save()
            return redirect('carts:cart_checkout')
    else:
        return redirect('carts:cart_checkout')
コード例 #8
0
def edit_address(request):
    address_id = request.GET.get("address_id")
    address_edit = request.GET.get("address_edit")
    address_delete = request.GET.get("address_delete")
    address_obj = Address.objects.get(id=address_id)
    if request.user.is_authenticated:
        if address_obj in request.user.billingprofile.address_set.all():
            if address_edit:
                form = AddressForm(instance=Address.objects.get(id=address_id))
                if request.method == 'POST':
                    form = AddressForm(request.POST or None)
                    if form.is_valid():
                        address_obj.address_line_1 = form.cleaned_data.get("address_line_1")
                        address_obj.address_line_2 = form.cleaned_data.get("address_line_2")
                        address_obj.city = form.cleaned_data.get("city")
                        address_obj.country = form.cleaned_data.get("country")
                        address_obj.state = form.cleaned_data.get("state")
                        address_obj.postal_code = form.cleaned_data.get("postal_code")
                        address_obj.save()
                        return render(request, 'accounts/account_info.html', {'address_id': address_id, 'address_delete': address_delete, 'form': form})
                    else:
                        return render(request, 'accounts/change_address.html', {'address_id': address_id, 'address_delete': address_delete, 'form': form})
            elif address_delete:
                address_obj.delete()
                return render(request, 'accounts/account_info.html', {'address_id': address_id, 'address_delete': address_delete})
        else:
            raise Http404
    else:
        raise Http404
    return render(request, 'accounts/change_address.html', {'address_id': address_id, 'address_delete': address_delete, 'form': form})
コード例 #9
0
ファイル: views.py プロジェクト: ndneighbor/bookmart
def addressview(request, user_id, address_id=None):
    address = None
    addresses_list = Address.objects.all().filter(user=user_id)

    if address_id:
        try:
            address = Address.objects.get(pk=address_id)
            addresses_list = Address.objects.filter(user=user_id).exclude(
                pk=address_id)
        except:
            return rendermessage(
                request, 'Error', 'Shipping does not exist', '',
                reverse('users:addresses', args=[str(user_id)]),
                'shipping addresses page')

    if request.method == "POST":
        if address:
            addressform = AddressForm(request.POST, instance=address)
        else:
            addressform = AddressForm(request.POST, initial=request.POST)

        if addressform.is_valid():
            newaddress = addressform.save(commit=False)
            newaddress.user_id = user_id
            newaddress.save()
            return rendermessage(
                request, 'New address confirmation',
                'Shipping address added succefully', '',
                reverse('users:addresses',
                        args=[str(user_id)]), 'addresses page')

        return rendermessage(
            request, 'Shipping address | Error', 'Shipping address ',
            'There was an error adding the shipping address. ' +
            addressform.error_message,
            reverse('users:addresses',
                    args=[str(user_id)]), 'shipping addresses page')
    else:  # GET
        if address:
            addressform = AddressForm(instance=address)
            button_text = 'Modify shiping address'
            page_title = address.name
        else:
            addressform = AddressForm()
            button_text = 'Add new shipping address'
            page_title = 'New'

    return render(
        request, 'addresses/addresses.html', {
            'user_id': user_id,
            'address': address,
            'page_title': page_title,
            'form': addressform,
            'addresses_list': addresses_list,
            'button_text': button_text,
        })
コード例 #10
0
def user_address_update(request):
    billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(
        request)
    print(billing_profile)
    address_qs = None
    if billing_profile is not None:
        if request.user.is_authenticated():
            address_qs = Address.objects.filter(
                billing_profile=billing_profile)
        try:
            shipping_address = Address.objects.get(
                billing_profile=billing_profile.id, address_type='shipping')
        except Address.DoesNotExist:
            print("Show message to user, Address is gone?")
            return redirect("cart:cart")
        try:
            billing_address = Address.objects.get(
                billing_profile=billing_profile.id, address_type='billing')
        except Address.DoesNotExist:
            print(" Address is gone?")
            return redirect("cart:cart")
        # shipping_address = Address.objects.get(id=27)
        # import pdb; pdb.set_trace()
        form1 = AddressForm(prefix='form1',
                            instance=shipping_address,
                            data=request.POST or None)
        form2 = AddressForm(prefix='form2',
                            instance=billing_address,
                            data=request.POST or None)

        if request.method == 'POST':
            import pdb
            pdb.set_trace()
            if form2.is_valid():
                form2.save()
            if form1.is_valid():
                form1.save()

    return render(request, 'account-details.html', {
        'form1': form1,
        'form2': form2
    })
コード例 #11
0
ファイル: views.py プロジェクト: toulene69/callyourmedic
def hospital_new(request,org_id=0):
    error = None
    args = {}
    if isUserLogged(request):
        if isUserRequestValid(request,org_id):
            if request.POST:
                formHospital = PortalHospitalCreationForm(request.POST)
                formAddress = AddressForm(request.POST)
                if formHospital.is_valid() & formAddress.is_valid():
                    organisation = Organisation.objects.get(org_id__exact = org_id)
                    branchCode = formHospital.cleaned_data['hospital_branch_code']
                    hospitalPresent = list(Hospital.objects.filter(hospital_branch_code__iexact = branchCode))
                    if len(hospitalPresent) >0 :
                        error = 'Branch code already exists. Please insert a unique code!'
                    else:
                        try:
                            with transaction.atomic():
                                address = formAddress.save()
                                hospital = formHospital.save(commit=False)
                                hospital.hospital_address = address
                                hospital.hospital_org = organisation
                                hospital.hospital_status = True
                                settings = HospitalSettings()
                                settings.settings_status = True
                                settings.save()
                                hospital.hospital_settings = settings
                                hospital.save()
                            args['new_hospital_added'] = hospital.hospital_name
                            args['new_hospital_id'] = hospital.hospital_id
                            return render(request,'w_dashboard_hospital.html',args)
                        except:
                            traceback.print_exc()
                            error = 'Error saving new hospital!'
                else:

                    print(formHospital.errors)
                    print(formAddress.errors)
                    error = 'Error creating new hospital. Form submitted is invalid'
            else:
                formHospital = PortalHospitalCreationForm()
                formAddress = AddressForm()
        else:
            error = 'Invalid request!'
        args.update(csrf(request))
        args['formHospital'] = formHospital
        args['formAddress'] = formAddress
        args['error'] = error
        return render(request,'w_new_hospital.html',args)
    else:
        return userSessionExpired()
コード例 #12
0
ファイル: views.py プロジェクト: ReznikovRoman/airbnb-clone
class RealtyLocationEditView(LoginRequiredMixin,
                             RealtySessionDataRequiredMixin,
                             generic.base.TemplateResponseMixin, generic.View):
    """View for editing Realty location (part of the multi-step form).

    Step-2
    """
    template_name = 'realty/realty/creation_steps/step_2_location.html'

    required_session_data = get_keys_with_prefixes(
        names=get_required_fields_from_form_with_model(forms_with_models=[
            FormWithModel(RealtyGeneralInfoForm, Realty),
        ], ),
        prefix=REALTY_FORM_SESSION_PREFIX,
    )
    location_form: AddressForm = None
    session_handler: SessionHandler = None

    def dispatch(self, request: HttpRequest, *args, **kwargs):
        self.session_handler = SessionHandler(
            session=request.session,
            keys_collector_name=REALTY_FORM_KEYS_COLLECTOR_NAME,
            session_prefix=REALTY_FORM_SESSION_PREFIX,
        )
        initial = self.session_handler.get_items_by_keys(
            keys=get_field_names_from_form(AddressForm))
        self.location_form = AddressForm(request.POST or None, initial=initial)
        return super(RealtyLocationEditView,
                     self).dispatch(request, *args, **kwargs)

    def get(self, request: HttpRequest, *args, **kwargs):
        return self.render_to_response(
            context={'location_form': self.location_form})

    def post(self, request: HttpRequest, *args, **kwargs):
        if self.location_form.is_valid():
            self.session_handler.create_or_update_items(
                data=self.location_form.cleaned_data)
            return redirect(reverse('realty:new_realty_description'))

        return self.render_to_response(context={
            'location_form': self.location_form,
        })
コード例 #13
0
def checkout(request):
    cart_obj, cart_created = Cart.objects.new_or_get(request)
    order_obj = None
    if cart_created or cart_obj.products.count() == 0:
        return redirect('carts:cart')
    guest_form = GuestForm()
    address_form = AddressForm(request.POST or None)
    billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(
        request)
    if address_form.is_valid():
        instance = address_form.save(commit=False)
        instance.billing_profile = billing_profile
        instance.save()
        request.session['delivery_address_id'] = instance.id
    delivery_address_id = request.session.get('delivery_address_id', None)
    address_qs = None
    if billing_profile is not None:
        address_qs = Address.objects.filter(billing_profile=billing_profile)
        if address_qs.count() >= 1:
            address_qs = address_qs.first()
        order_obj, order_obj_created = Order.objects.new_or_get(
            billing_profile, cart_obj)
        if delivery_address_id:
            order_obj.delivery_address = Address.objects.get(
                id=delivery_address_id)
            del request.session['delivery_address_id']
            order_obj.save()
    if request.method == 'POST':
        is_done = order_obj.check_done()
        if is_done:
            order_obj.mark_paid()
            request.session['cart_items_total'] = 0
            del request.session['cart_id']
            return redirect('carts:success')
    my_dict = {
        'order': order_obj,
        'cart': cart_obj,
        'billing_profile': billing_profile,
        'address_form': address_form,
        'address_qs': address_qs,
    }
    return render(request, 'carts/checkout.html', my_dict)
コード例 #14
0
ファイル: views.py プロジェクト: Galyopa/eCommerce
def checkout_address_create_view(request):
    address_form = AddressForm(request.POST or None)
    context = {'form': address_form}
    next_ = request.GET.get('next')
    next_post = request.POST.get('next')
    redirect_path = next_ or next_post or None
    if address_form.is_valid():
        instance = address_form.save(commit=False)
        billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(
            request)
        if billing_profile is not None:
            address_type = request.POST.get('address_type', 'shipping')
            instance.billing_profile = billing_profile
            instance.address_type = address_type
            instance.save()
            request.session[address_type + "_address_id"] = instance.id
        else:
            return redirect('cart:checkout_url')
        if is_safe_url(redirect_path, request.get_host()):
            return redirect(redirect_path)
    return redirect('cart:checkout_url')
コード例 #15
0
    def post(self, request):
        form = SignUpForm(request.POST)
        addressform = AddressForm(request.POST)
        benefit_agree = request.POST.get("agree-benefit", False)
        kakao_farmer_agree = request.POST.get("agree-kakao-farmer", False)
        kakao_comment_agree = request.POST.get("agree-kakao-comment", False)
        print(form.is_valid())
        if form.is_valid():
            print("hello")
            form.save()
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")
            user = authenticate(request, username=username, password=password)
            consumer = Consumer.objects.create(
                user=user,
                grade=1,
                benefit_agree=False if not benefit_agree else True,
                kakao_farmer_agree=False if not kakao_farmer_agree else True,
                kakao_comment_agree=False if not kakao_comment_agree else True,
            )

            if addressform.is_valid():
                print(addressform.cleaned_data["is_jeju_mountain"])
                address = addressform.save(commit=False)
                address.user = user
                address.is_default = True
                address.save()

                consumer.default_address = address
                consumer.save()

            if user is not None:
                login(request, user=user)
                return redirect(reverse("core:main"))

        ctx = {
            "form": form,
            "addressform": addressform,
        }
        return render(request, "users/signup.html", ctx)
コード例 #16
0
ファイル: views.py プロジェクト: shafique-md18/efarmer
def checkout_address_create(request):
    next_ = request.GET.get('next', None)
    next_post = request.POST.get('next', None)
    redirect_to = next_ or next_post
    if request.method == 'POST':
        form = AddressForm(request.POST)
        if form.is_valid() and request.user.is_authenticated:
            model_instance = form.save(commit=False)
            model_instance.address_type = form.cleaned_data.get('address_type') or 'shipping'
            model_instance.billing_profile = BillingProfile.objects.filter(user=request.user).first()
            model_instance.save()
            if redirect_to and is_safe_url(redirect_to, 
                    allowed_hosts=request.get_host(),
                    require_https=request.is_secure()):
                return redirect(redirect_to)
            return redirect('home')
    else:
        form = AddressForm()
        context = {
            'shipping_address_form': form,
        }
        return render(request, 'carts/create_address.html', context)
コード例 #17
0
def checkout_address_create_view(request):
    next_ = request.GET.get('next')
    next_post = request.POST.get('next')
    redirect_path = next_ or next_post or None

    if request.method == 'POST':
        form = AddressForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(
                request)
            # address_type = request.POST.get('address_type', 'shipping')
            instance.billing_profile = billing_profile
            # instance.address_type = address_type
            instance.save()

            request.session["shipping_address_id"] = instance.id

            if is_safe_url(redirect_path, request.get_host()):
                return redirect(redirect_path)
            else:
                return redirect('carts:checkout')
    return redirect("carts:checkout")
コード例 #18
0
def address_create(request):
    if request.method == 'POST':

        form = AddressForm(request.POST)

        # Is this a shipping or billing address????
        address_type = request.POST.get('address_type')
        print('address_type', address_type)

        billing_profile, bill_created = BillingProfile.objects.new_or_get(
            request)
        cart_obj, cart_created = Cart.objects.new_or_get(request)
        order_obj, order_created = Order.objects.new_or_get(
            billing_profile=billing_profile, cart_obj=cart_obj)

        if form.is_valid():

            address = form.save(commit=False)
            # print('Form and Address', type(form), form)
            # print('Address', type(address), address)

            address.billing_profile = billing_profile
            address.address_type = address_type
            address.save()

            # Now we have to associate to the order
            if address_type == 'shipping':
                # How do we get the order?
                order_obj.shipping_address = address
                order_obj.save()
            if address_type == 'billing':
                order_obj.billing_address = address
                order_obj.save()
            return redirect('carts:cart_checkout')
    else:
        return redirect('carts:cart_checkout')
コード例 #19
0
def payment_method_create_view(request):
    cart_obj, new_obj = ShopCart.objects.get_or_new(request)
    billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(
        request)
    # get sale_obj
    sale_obj, sale_obj_created = Sale.objects.new_or_get(
        billing_profile, cart_obj)
    if request.method == 'POST' and request.is_ajax():
        form = AddressForm(request.POST or None)
        if form.is_valid():
            instance = form.save(commit=False)
            remember = form.cleaned_data.get('remember_address')
            if billing_profile:
                instance.addressBillingProfile = billing_profile
                instance.addressType = 'billing'
                instance.save()

                request.session[instance.addressType +
                                "_address_id"] = instance.id
                token = request.POST.get('token')
                if token:
                    new_card_obj, new_card_error = Card.objects.add_new(
                        billing_profile, token, instance, remember)
                    if new_card_obj:
                        sale_obj.salePaymentCard = new_card_obj
                        sale_obj.saleBillingAddress = instance
                        sale_obj.save()
                        return JsonResponse(
                            {'message': 'Success! Your card was added.'})
                    else:
                        print('deleted address')
                        form.instance.delete()
                        del request.session['billing_address_id']
                        return JsonResponse({'message': str(new_card_error)})

    elif request.method == 'POST':
        form = CardIDForm(request.POST or None)
        if form.is_valid():
            card = form.cleaned_data['cID']
            if card:
                # get card_obj
                # change: add try thing for error handling?
                card_obj = Card.objects.get(
                    id=card,
                    billingProfile=billing_profile,
                    cardActive=True,
                )
                # add card to sale
                sale_obj.salePaymentCard = card_obj
                # add corresponding address to sale
                billing_address_qs = Address.objects.filter(
                    addressBillingProfile=billing_profile,
                    addressLine1=card_obj.cardAddressLine1,
                    addressLine2=card_obj.cardAddressLine2,
                    addressCity=card_obj.cardCity,
                    addressState=card_obj.cardState,
                    addressPostalCode=card_obj.cardPostalCode,
                    addressName=card_obj.cardName,
                )
                if billing_address_qs.count() == 1:
                    print('found address')
                    # add address to sale
                    sale_obj.saleBillingAddress = billing_address_qs.first()
                    # save sale
                    sale_obj.save()
                else:
                    print('no matching address')
                return redirect('shopcart:checkout')
            else:
                return redirect('shopcart:home')
        else:
            pass
    return HttpResponse('error', status_code=401)
コード例 #20
0
ファイル: views.py プロジェクト: toulene69/callyourmedic
def doctor_new(request, org_id=0):
    error = None
    args = {}
    if isUserLogged(request):
        if isUserRequestValid(request,org_id):
            if request.POST:
                formAddress = AddressForm(request.POST)
                formDocDetails = PortalDoctorDetailsForm(request.POST)
                formDocRegistration = PortalDoctorRegistrationForm(org_id,request.POST)
                print "POST Request"
                if (formDocRegistration.is_valid() & formDocDetails.is_valid() & formAddress.is_valid()):
                    print "Form Valid"
                    email = formDocRegistration.cleaned_data['doctor_email']
                    hospitalID = formDocRegistration.cleaned_data['hospital_choice']
                    deptID = formDocRegistration.cleaned_data['dept_choice']
                    registeredDoc = DoctorRegistration.objects.filter(doctor_org = org_id, doctor_email__iexact = email)
                    if len(registeredDoc)==0 :

                        try:
                            randomPassword = None
                            organisation = Organisation.objects.get(org_id = org_id)
                            hospital = Hospital.objects.get(hospital_org = org_id, hospital_id = hospitalID)
                            department = Department.objects.get(department_org = org_id, department_id = deptID)
                            with transaction.atomic():
                                docReg = formDocRegistration.save(commit=False)
                                docDet = formDocDetails.save(commit=False)
                                docAddress = formAddress.save()

                                docReg.doctor_org = organisation
                                docReg.doctor_department = department
                                docReg.doctor_hospital = hospital
                                docReg.doctor_status = True
                                randomPassword = generateRandomPassword()
                                docReg.doctor_password = getPasswordHash(randomPassword)
                                docReg.save()
                                docReg.doctor_code = generateDoctorCode(org_id,hospital.hospital_branch_code,docReg.doctor_id)
                                docReg.save()

                                docDet.doctor_address = docAddress
                                docDet.doctor_id = docReg
                                docDet.save()

                            send_mail_to_doctor(docReg,randomPassword,organisation.org_identifier)

                            args['new_doctor_added'] = docDet.doctor_first_name+' '+docDet.doctor_last_name
                            args['new_doctor_id'] = docReg.doctor_id
                            return render(request,'w_dashboard_doctor.html',args)
                        except:
                            traceback.print_exc()
                            error = "Error while adding doctor"
                    else:
                        print registeredDoc
                        error = "Doctor Email Id is already registered! Please try a unique email id."
                else:
                    traceback.print_exc()
                    error = "Invalid form!"
            else:
                formAddress = AddressForm()
                formDocDetails = PortalDoctorDetailsForm()
                formDocRegistration = PortalDoctorRegistrationForm(org_id)
        else:
            error = "Invalid Request!"
            formAddress = AddressForm()
            formDocDetails = PortalDoctorDetailsForm()
            formDocRegistration = PortalDoctorRegistrationForm(org_id)
        args.update(csrf(request))
        args['error'] = error
        args['formAddress'] = formAddress
        args['formDocDetails'] = formDocDetails
        args['formDocRegistration'] = formDocRegistration
        return render(request,'w_new_doctor.html',args)
    else:
        return userSessionExpired()
コード例 #21
0
def org_new(request):
	error = None
	args = {}
	if isUserLogged(request):
		usr_details = request.session['usr_details']
		if request.POST:
			formOrg = CYMOrganisationCreationForm(request.POST)
			formAddress = AddressForm(request.POST)
			if formOrg.is_valid() & formAddress.is_valid():

				address = Address()
				organisation = Organisation()
				settings = OrgSettings()
				address.address_line1 = formAddress.cleaned_data['address_line1']
				address.address_line2 = formAddress.cleaned_data['address_line2']
				address.address_city = formAddress.cleaned_data['address_city']
				address.address_state = formAddress.cleaned_data['address_state']
				pin = formAddress.cleaned_data['address_pincode']
				address.address_pincode = pin
				address.address_status = True

				organisation.org_name = formOrg.cleaned_data['org_name']
				organisation.org_brand = formOrg.cleaned_data['org_brand']
				organisation.org_phone = formOrg.cleaned_data['org_phone']
				organisation.org_active = formOrg.cleaned_data['org_active']
				organisation.org_emailid = formOrg.cleaned_data['org_emailid']
				settings.orgsettings_status = formOrg.cleaned_data['org_active']
				try:
					with transaction.atomic():
						address.save()
						settings.save()
						organisation.org_address = address
						organisation.org_settings = settings
						organisation.save()
						organisation.org_billing_id = organisation.org_id
						identifier = str(organisation.org_id) + '_' + organisation.org_brand
						organisation.org_identifier = identifier.replace(" ", "")
						organisation.save()
						success = createSuperUserAndGroup(organisation.org_emailid,organisation.org_phone,organisation,'Super Admin',organisation.org_identifier)
						if success:
							print 'Super User Created'
						else:
							print 'Error while creating super user'
						send_mail_to_org_admin(organisation)
					args['usr_details'] = usr_details
					args['new_org_added'] = organisation.org_name
					args['new_org_id'] = organisation.org_id
					return render_to_response('org_dashboard.html',args)
				except IntegrityError:
					traceback.print_exc()
					error = 'Error creating new organisation'
			else:
				error = 'Error creating new organisation. Invalid form!'
		else:
			formOrg = CYMOrganisationCreationForm()
			formAddress = AddressForm()
		args.update(csrf(request))
		args['formOrg'] = formOrg
		args['formAddress'] = formAddress
		args['usr_details'] = usr_details
		args['error'] = error
		return render_to_response('org_new.html',args)
	else:
		return userSessionExpired()
コード例 #22
0
def mypage(request, cat):

    try:
        consumer = request.user.consumer
    except ObjectDoesNotExist:
        return redirect(reverse("core:main"))

    cat_name = str(cat)
    print(cat_name)

    if request.method == "GET":
        consumer_nickname = consumer.user.nickname
        sub_farmers = consumer.subs.all()  # pagenation 필요

        preparing_num, delivery_num, complete_num, cancel_num = 0, 0, 0, 0
        print(sub_farmers)
        if sub_farmers.exists() is False:
            print("구독자는 없다")
        questions = consumer.questions.order_by("-create_at")  # pagenation 필요
        print(questions)
        if questions.exists() is False:
            print("질문은 없다")
        try:
            groups = consumer.order_groups.all().exclude(status="waiting")
            print(groups)
            if groups.exists() is False:
                print("여기안와?")
                raise NoRelatedInstance
            for group in groups:
                details = group.order_details.all()
                print(details)
                preparing_num += details.filter(status="preparing").count()
                # print(preparing_num)
                delivery_num += details.filter(status="shipping").count()
                # print(delivery_num)
                complete_num += details.filter(
                    status="delivery_complete").count()
                # print(complete_num)
                cancel_num += details.filter(status="cancel").count()
        except NoRelatedInstance:
            preparing_num = 0
            delivery_num = 0
            complete_num = 0
            cancel_num = 0

        # 구독 농가
        subs = consumer.subs.all().order_by("-create_at").all()
        if subs is None:
            subs_count = 0
        else:
            subs_count = subs.count()
        print("구독자 수 " + (str)(subs_count))

        # 상품 Q&A
        now = timezone.localtime()
        one_month_before = now + timedelta(days=-30)
        print(one_month_before)

        questions = (consumer.questions.filter(
            create_at__gt=one_month_before).order_by("-create_at").all())
        print((type)(questions))

        for q in questions:
            print(type(q))

        ctx = {
            "consumer_nickname": consumer_nickname,
            "sub_farmers": sub_farmers,
            "questions": questions,
            "preparing_num": preparing_num,
            "delivery_num": delivery_num,
            "complete_num": complete_num,
            "cancel_num": cancel_num,
            "subs_count": subs_count,
            "subs": subs,
            "questions": questions,
        }

        if cat_name == "orders":
            # page = int(request.GET.get("page", 1))
            start_date = request.GET.get("s_date", None)
            end_date = request.GET.get("e_date", None)
            # page_size = 5

            if start_date == "None":
                start_date = None
            if end_date == "None":
                end_date = None

            print("start_date의 정체")
            print(start_date)
            print("end_date의 정체")
            print(end_date)

            if (start_date is None) and (end_date is None):
                # 주문관리 페이지에 처음 들어온 경우
                start_date = None
                end_date = None
                order_groups = groups.exclude(status="wait")
            else:
                # 날짜 필터링에서 조회 버튼을 누른 경우
                if start_date == "":
                    # filter start_date input에 아무런 value가 없을 경우
                    start_date = datetime.datetime.now(
                        tz=get_current_timezone()).date()
                else:
                    start_date = datetime.datetime.strptime(
                        start_date, "%Y-%m-%d").date()

                if end_date == "":
                    # filter end_date input에 아무런 value가 없음 경우
                    end_date = datetime.datetime.now(
                        tz=get_current_timezone()).date()
                    t = datetime.time(23, 59, 59)
                    converted_end_date = datetime.datetime.combine(end_date, t)

                else:
                    # end_date 23:59분까지 filter 해주기 위해서 시간까지 있는 converted_end_date로 변환
                    # ctx로 넘겨줄 때는 end_date를 넘겨주어야 함
                    converted_end_date = end_date + " 23:59:59"
                    print("바꾼 날짜는")
                    print(end_date)
                    converted_end_date = datetime.datetime.strptime(
                        converted_end_date, "%Y-%m-%d %H:%M:%S")

                order_groups = (groups.filter(
                    order_at__lte=converted_end_date,
                    order_at__gte=start_date).exclude(
                        status="wait").order_by("-order_at"))

            print(f"start_date : {start_date}")
            print(f"end_date : {end_date}")

            print(order_groups)
            if order_groups.exists():
                order_details = order_groups[0].order_details.all()
                print(order_groups.count())
                if order_groups.count() > 1:
                    for group in order_groups[1:]:
                        print(group.order_details.all())
                        order_details = order_details | group.order_details.all(
                        )
                order_details = order_details.order_by(
                    "-order_group__order_at")
                paginator = Paginator(order_details, 6)
                page = request.GET.get("page")
                order_details = paginator.get_page(page)
            else:
                order_details = None

            print("진짜")
            print(order_details)

            ctx_orders = {
                "order_details": order_details,
                "order_details_exist":
                len(order_details) if order_details else 0,
                "start_date": str(start_date),
                "end_date": str(end_date),
            }
            ctx.update(ctx_orders)
            return render(request, "users/mypage_orders.html", ctx)
        elif cat_name == "wishes":
            page = int(request.GET.get("page", 1))
            page_size = 5

            wishes = consumer.wishes.filter(
                product__open=True).order_by("-create_at")
            print(wishes)

            wishes_count = wishes.count()
            total_pages = ceil(wishes_count / page_size)
            offset = page * page_size - page_size
            wishes = wishes[offset:page * page_size]
            print(wishes)

            ctx_wishes = {
                "page": page,
                "total_pages": range(1, total_pages + 1),
                "wishes": wishes,
            }
            ctx.update(ctx_wishes)
            return render(request, "users/mypage_wishes.html", ctx)
        elif cat_name == "cart":
            carts = (consumer.carts.all().order_by("-create_at").filter(
                product__open=True))
            print(carts)

            ctx_carts = {
                "carts": carts,
            }
            ctx.update(ctx_carts)
            return render(request, "users/mypage_carts.html", ctx)
        elif cat_name == "rev_address":
            print("왔댜")
            get_arg = request.GET.get("type", None)
            update_pk = request.GET.get("pk", None)
            if get_arg == "add":
                if request.method == "GET":
                    addressform = AddressForm()
                    ctx_add_rev_address = {
                        "addressform": addressform,
                    }
                    ctx.update(ctx_add_rev_address)
                    return render(request, "users/mypage_add_rev_address.html",
                                  ctx)
            elif get_arg == "update":
                address = Address.objects.get(pk=update_pk)
                addressform = AddressForm(instance=address)
                ctx_add_rev_address = {
                    "addressform": addressform,
                }
                ctx.update(ctx_add_rev_address)
                return render(request, "users/mypage_add_rev_address.html",
                              ctx)
            else:
                rev_addresses = request.user.addresses.all().order_by(
                    "-create_at")
                ctx_rev_address = {
                    "rev_addresses": rev_addresses,
                }
                ctx.update(ctx_rev_address)
                return render(request, "users/mypage_rev_address.html", ctx)
        elif cat_name == "info":
            user = consumer.user

            info = {
                "first_name": user.first_name,
                "last_name": user.last_name,
                # 'number':number,
                "email": user.email,
                "nickname": user.nickname,
                "profile_image": user.profile_image,
            }

            ctx.update(info)
            return render(request, "users/mypage_info.html", ctx)

    else:
        address_type = request.GET.get("type", None)
        print("post에 왔다")
        addressform = AddressForm(request.POST)
        user = request.user
        if addressform.is_valid():
            # [address UPDATE POST] 배송지 추가 페이지에서 새로운 배송지 등록 시, backend logic
            if address_type == "add":
                address = addressform.save(commit=False)
                address.user = user
                address.is_default = False
                address.save()
            # [address UPDATE POST] 기존에 등록된 배송지 수정 시, backend logic
            elif address_type == "update":
                update_pk = request.GET.get("pk", None)
                address = Address.objects.get(pk=update_pk)
                print(address)
                address.full_address = addressform.cleaned_data["full_address"]
                address.detail_address = addressform.cleaned_data[
                    "detail_address"]
                address.extra_address = addressform.cleaned_data[
                    "extra_address"]
                address.sido = addressform.cleaned_data["sido"]
                address.fsigungu = addressform.cleaned_data["sigungu"]
                address.save()
                print(address)

            return redirect(
                reverse("users:mypage", kwargs={"cat": "rev_address"}))
        else:
            # 404 페이지 제작 후 여기에 넣어야함
            return redirect(reverse("core:main"))
コード例 #23
0
ファイル: views.py プロジェクト: EM124/test
def register_page(request):
    if request.user.is_authenticated() and (request.user.admin
                                            or request.user.manager
                                            or request.user.employee):
        form = RegisterForm(request.POST or None)
        address = AddressForm(request.POST or None)
        kid = KidForm(request.POST or None)
        instance = None
        if request.user.admin:
            instance = User.objects.all()
        elif request.user.manager:
            instance = User.objects.all().filter(admin=False)

        daycare = DaycareForm(request.user)
        context = {
            "form": form,
            "address": address,
            "daycare": daycare,
            "kid": kid,
            "instance": instance,
        }
        if request.POST:
            if request.POST['choices'] == 'admin':
                if form.is_valid() and address.is_valid():
                    name_age_pairs = zip(
                        request.POST.getlist('child_first_name'),
                        request.POST.getlist('child_last_name'),
                        request.POST.getlist('gender'))
                    profile = User()
                    profile.email = form.cleaned_data['email']
                    profile.set_password(form.cleaned_data["password1"])
                    #profile.password = form.cleaned_data['password2']
                    profile.adult_first_name = form.cleaned_data[
                        'adult_first_name']
                    profile.adult_last_name = form.cleaned_data[
                        'adult_last_name']
                    profile.active = True
                    profile.admin = True
                    profile.staff = True
                    profile.manager = False
                    profile.employee = False
                    profile.parent = False
                    address_profile = Address()
                    address_profile.address_line_1 = address.cleaned_data[
                        'address_line_1']
                    address_profile.address_line_2 = address.cleaned_data[
                        'address_line_2']
                    address_profile.city = address.cleaned_data['city']
                    address_profile.country = address.cleaned_data['country']
                    address_profile.province = address.cleaned_data[
                        'postal_code']
                    address_profile.postal_code = address.cleaned_data[
                        'province']
                    address_profile.home_phone = address.cleaned_data[
                        'home_phone']
                    address_profile.cell_phone = address.cleaned_data[
                        'cell_phone']
                    address_profile.save()
                    profile.user_address = address_profile
                    profile.save()
                    all_selected_daycares = request.POST.getlist('daycare')
                    if all_selected_daycares is not None:
                        for data in all_selected_daycares:
                            temporary_daycare = Daycare.objects.get(name=data)
                            profile.daycare.add(temporary_daycare.id)
                    profile.save()
                    if kid.is_valid() and name_age_pairs is not None:
                        data_dicts = [{
                            'child_first_name': child_first_name,
                            'child_last_name': child_last_name,
                            'gender': gender
                        } for child_first_name, child_last_name, gender in
                                      name_age_pairs]
                        for data in data_dicts:
                            if data['child_first_name'] != "" and data[
                                    'child_last_name'] != "":
                                profile_kid = Kid()
                                profile_kid.parent = profile
                                profile_kid.child_first_name = data[
                                    'child_first_name']
                                profile_kid.child_last_name = data[
                                    'child_last_name']
                                profile_kid.gender = data['gender']
                                profile_kid.save()
                return redirect("/register/")
            elif request.POST['choices'] == 'manager':
                if form.is_valid() and address.is_valid():
                    name_age_pairs = zip(
                        request.POST.getlist('child_first_name'),
                        request.POST.getlist('child_last_name'),
                        request.POST.getlist('gender'))
                    profile = User()
                    profile.email = form.cleaned_data['email']
                    profile.set_password(form.cleaned_data["password1"])
                    #profile.password = form.cleaned_data['password2']
                    profile.adult_first_name = form.cleaned_data[
                        'adult_first_name']
                    profile.adult_last_name = form.cleaned_data[
                        'adult_last_name']
                    profile.active = True
                    profile.admin = False
                    profile.staff = False
                    profile.employee = False
                    profile.manager = True
                    profile.parent = False
                    address_profile = Address()
                    address_profile.address_line_1 = address.cleaned_data[
                        'address_line_1']
                    address_profile.address_line_2 = address.cleaned_data[
                        'address_line_2']
                    address_profile.city = address.cleaned_data['city']
                    address_profile.country = address.cleaned_data['country']
                    address_profile.province = address.cleaned_data[
                        'postal_code']
                    address_profile.postal_code = address.cleaned_data[
                        'province']
                    address_profile.home_phone = address.cleaned_data[
                        'home_phone']
                    address_profile.cell_phone = address.cleaned_data[
                        'cell_phone']
                    address_profile.save()
                    profile.user_address = address_profile
                    profile.save()
                    all_selected_daycares = request.POST.getlist('daycare')
                    if all_selected_daycares is not None:
                        for data in all_selected_daycares:
                            temporary_daycare = Daycare.objects.get(name=data)
                            profile.daycare = Daycare.objects.get(
                                id=temporary_daycare.id)
                    profile.save()
                    if kid.is_valid() and name_age_pairs is not None:
                        data_dicts = [{
                            'child_first_name': child_first_name,
                            'child_last_name': child_last_name,
                            'gender': gender
                        } for child_first_name, child_last_name, gender in
                                      name_age_pairs]
                        for data in data_dicts:
                            if data['child_first_name'] != "" and data[
                                    'child_last_name'] != "":
                                profile_kid = Kid()
                                profile_kid.parent = profile
                                profile_kid.child_first_name = data[
                                    'child_first_name']
                                profile_kid.child_last_name = data[
                                    'child_last_name']
                                profile_kid.gender = data['gender']
                                profile_kid.save()
                return redirect("/register/")
            elif request.POST['choices'] == 'employee':
                if form.is_valid() and address.is_valid():
                    name_age_pairs = zip(
                        request.POST.getlist('child_first_name'),
                        request.POST.getlist('child_last_name'),
                        request.POST.getlist('gender'))
                    profile = User()
                    profile.email = form.cleaned_data['email']
                    profile.set_password(form.cleaned_data["password1"])
                    #profile.password = form.cleaned_data['password2']
                    profile.adult_first_name = form.cleaned_data[
                        'adult_first_name']
                    profile.adult_last_name = form.cleaned_data[
                        'adult_last_name']
                    profile.active = True
                    profile.admin = False
                    profile.staff = False
                    profile.manager = False
                    profile.employee = True
                    profile.parent = False
                    address_profile = Address()
                    address_profile.address_line_1 = address.cleaned_data[
                        'address_line_1']
                    address_profile.address_line_2 = address.cleaned_data[
                        'address_line_2']
                    address_profile.city = address.cleaned_data['city']
                    address_profile.country = address.cleaned_data['country']
                    address_profile.province = address.cleaned_data[
                        'postal_code']
                    address_profile.postal_code = address.cleaned_data[
                        'province']
                    address_profile.home_phone = address.cleaned_data[
                        'home_phone']
                    address_profile.cell_phone = address.cleaned_data[
                        'cell_phone']
                    address_profile.save()
                    profile.user_address = address_profile
                    profile.save()
                    all_selected_daycares = request.POST.getlist('daycare')
                    if all_selected_daycares is not None:
                        for data in all_selected_daycares:
                            temporary_daycare = Daycare.objects.get(name=data)
                            profile.daycare = Daycare.objects.get(
                                id=temporary_daycare.id)
                    profile.save()
                    if kid.is_valid() and name_age_pairs is not None:
                        data_dicts = [{
                            'child_first_name': child_first_name,
                            'child_last_name': child_last_name,
                            'gender': gender
                        } for child_first_name, child_last_name, gender in
                                      name_age_pairs]
                        for data in data_dicts:
                            if data['child_first_name'] != "" and data[
                                    'child_last_name'] != "":
                                profile_kid = Kid()
                                profile_kid.parent = profile
                                profile_kid.child_first_name = data[
                                    'child_first_name']
                                profile_kid.child_last_name = data[
                                    'child_last_name']
                                profile_kid.gender = data['gender']
                                profile_kid.save()
                return redirect("/register/")
            elif request.POST['choices'] == 'parent':
                if form.is_valid() and address.is_valid():
                    name_age_pairs = zip(
                        request.POST.getlist('child_first_name'),
                        request.POST.getlist('child_last_name'),
                        request.POST.getlist('gender'))
                    profile = User()
                    profile.email = form.cleaned_data['email']
                    profile.set_password(form.cleaned_data["password1"])
                    #profile.password = form.cleaned_data['password2']
                    profile.adult_first_name = form.cleaned_data[
                        'adult_first_name']
                    profile.adult_last_name = form.cleaned_data[
                        'adult_last_name']
                    profile.active = True
                    profile.admin = False
                    profile.staff = False
                    profile.manager = False
                    profile.employee = False
                    profile.parent = True
                    address_profile = Address()
                    address_profile.address_line_1 = address.cleaned_data[
                        'address_line_1']
                    address_profile.address_line_2 = address.cleaned_data[
                        'address_line_2']
                    address_profile.city = address.cleaned_data['city']
                    address_profile.country = address.cleaned_data['country']
                    address_profile.province = address.cleaned_data[
                        'postal_code']
                    address_profile.postal_code = address.cleaned_data[
                        'province']
                    address_profile.home_phone = address.cleaned_data[
                        'home_phone']
                    address_profile.cell_phone = address.cleaned_data[
                        'cell_phone']
                    address_profile.save()
                    profile.user_address = address_profile
                    profile.save()
                    all_selected_daycares = request.POST.getlist('daycare')
                    if all_selected_daycares is not None:
                        for data in all_selected_daycares:
                            temporary_daycare = Daycare.objects.get(name=data)
                            profile.daycare = Daycare.objects.get(
                                id=temporary_daycare.id)
                    profile.save()
                    if kid.is_valid() and name_age_pairs is not None:
                        data_dicts = [{
                            'child_first_name': child_first_name,
                            'child_last_name': child_last_name,
                            'gender': gender
                        } for child_first_name, child_last_name, gender in
                                      name_age_pairs]
                        for data in data_dicts:
                            if data['child_first_name'] != "" and data[
                                    'child_last_name'] != "":
                                profile_kid = Kid()
                                profile_kid.parent = profile
                                profile_kid.child_first_name = data[
                                    'child_first_name']
                                profile_kid.child_last_name = data[
                                    'child_last_name']
                                profile_kid.gender = data['gender']
                                profile_kid.save()
                return redirect("/register/")
            else:
                pass
    else:
        return redirect("/")
    return render(request, "accounts/register.html", context)
コード例 #24
0
ファイル: views.py プロジェクト: ReznikovRoman/airbnb-clone
class RealtyEditView(LoginRequiredMixin, RealtySessionDataRequiredMixin,
                     generic.base.TemplateResponseMixin, generic.View):
    """View for creating or updating a single Realty."""
    template_name = 'realty/realty/form.html'

    realty: Realty = None
    address: Address = None
    realty_images: 'CustomDeleteQueryset[RealtyImage]' = None

    is_creating_new_realty: bool = True  # True if we are creating new Realty, False otherwise
    realty_form: RealtyForm = None
    address_form: AddressForm = None
    realty_address_initial: dict = None
    realty_info_initial: dict = None

    session_handler: SessionHandler = None

    def dispatch(self,
                 request: HttpRequest,
                 realty_id: Optional[int] = None,
                 *args,
                 **kwargs):
        self.session_handler = SessionHandler(
            session=request.session,
            keys_collector_name=REALTY_FORM_KEYS_COLLECTOR_NAME,
            session_prefix=REALTY_FORM_SESSION_PREFIX,
        )

        if realty_id:  # if we are editing an existing Realty object
            self.realty = get_object_or_404(Realty, id=realty_id)

            # if a current user is not the host of the Realty
            if not hasattr(request.user, 'host') or \
                    self.realty.host != request.user.host:
                return redirect(reverse('realty:all'))

            self.address = self.realty.location
            self.is_creating_new_realty = False
            self.realty_images = self.realty.images.all()
            self.required_session_data = []
        else:
            self.required_session_data = get_keys_with_prefixes(
                names=get_required_fields_from_form_with_model(
                    forms_with_models=[
                        FormWithModel(RealtyGeneralInfoForm, Realty),
                        FormWithModel(AddressForm, Address),
                        FormWithModel(RealtyDescriptionForm, Realty),
                    ], ),
                prefix=REALTY_FORM_SESSION_PREFIX,
            )

            self.realty_info_initial = self.session_handler.get_items_by_keys(
                keys=get_field_names_from_form(RealtyForm))
            # handle m2m field
            self.realty_info_initial[
                'amenities'] = get_amenity_ids_from_session(
                    self.session_handler)

            self.realty_address_initial = self.session_handler.get_items_by_keys(
                keys=get_field_names_from_form(AddressForm))

        self.realty_form = RealtyForm(
            data=request.POST or None,
            instance=self.realty,
            initial=self.realty_info_initial,
        )
        self.address_form = AddressForm(
            data=request.POST or None,
            instance=self.address,
            initial=self.realty_address_initial,
        )
        return super(RealtyEditView, self).dispatch(request, realty_id, *args,
                                                    **kwargs)

    def get(self,
            request: HttpRequest,
            realty_id: Optional[int] = None,
            *args,
            **kwargs):
        realty_image_formset = RealtyImageFormSet(
            queryset=get_images_by_realty_id(realty_id))

        return self.render_to_response(
            context={
                'realty_form': self.realty_form,
                'address_form': self.address_form,
                'realty_image_formset': realty_image_formset,
                'is_creating_new_realty': self.is_creating_new_realty,
                'realty_images': self.realty_images,
                'max_realty_images_count': MAX_REALTY_IMAGES_COUNT,
            })

    def post(self,
             request: HttpRequest,
             realty_id: Optional[int] = None,
             *args,
             **kwargs):
        realty_image_formset = RealtyImageFormSet(
            data=request.POST,
            files=request.FILES,
            queryset=get_images_by_realty_id(realty_id),
        )

        if self.realty_form.is_valid():
            new_realty: Realty = self.realty_form.save(commit=False)

            set_realty_host_by_user(realty=new_realty, user=request.user)

            if self.address_form.is_valid():
                new_address: Address = self.address_form.save()
                new_realty.location = new_address

                if not realty_id:  # if it is not a new Realty
                    self.session_handler.flush_keys_collector()

                new_realty.save(update_fields=["location"])

                self.realty_form.save_m2m()  # save many to many fields

                if realty_image_formset.is_valid():
                    valid_image_formsets = [
                        image_formset for image_formset in realty_image_formset
                        if image_formset.cleaned_data
                    ]
                    for image_form in valid_image_formsets:
                        new_image: RealtyImage = image_form.save(commit=False)
                        new_image.realty = new_realty
                        new_image.save(update_fields=["realty"])

            # TODO: Redirect to Host's listings dashboard
            return redirect(reverse('realty:all'))

        return self.render_to_response(
            context={
                'realty_form': self.realty_form,
                'address_form': self.address_form,
                'realty_image_formset': realty_image_formset,
                'is_creating_new_realty': self.is_creating_new_realty,
                'realty_images': self.realty_images,
                'max_realty_images_count': MAX_REALTY_IMAGES_COUNT,
            })