Example #1
0
def add_address(request):
    if request.method == 'POST':
        form = AddressForm(request.POST)
        if form.is_valid():
            location = Location(house_number=form.cleaned_data['house_number'],
                                street=form.cleaned_data['street'],
                                city_name=form.cleaned_data['city_name'],
                                zip_code=form.cleaned_data['zip_code'])
            location.save()
            coord = find_coordinates(location.house_number, location.street,
                                     location.zip_code, location.city_name)
            location.latitude = float(coord.split(",")[2])
            location.longitude = float(coord.split(",")[3])
            location.save()
            address = Address(user=request.user, location=location)
            address.save()
            request.user.message_set.create(message="Adresse ajoutée.")
            return HttpResponseRedirect('/users/address/edit/%s' % address.id)
        else:
            return render_to_response('users/add_address.html', {'form': form},
                                      RequestContext(request))
    else:
        form = AddressForm()
        return render_to_response('users/add_address.html', {'form': form},
                                  RequestContext(request))
Example #2
0
    def post(self, request):
        try:
            data = json.loads(request.body)
            cart = Cart.objects.filter(user_id=request.user.id).last()
            order_number = self.ID_OFFSET + Order.objects.latest('id').id

            if Address.objects.filter(user_id=request.user.id,
                                      address=data['address']).exists():
                receiver_address = Address.objects.get(
                    user_id=request.user.id, address=data['address']).id

            else:
                user_address = Address(user_id=request.user.id,
                                       address=data['address'],
                                       is_capital_area=self.check_capital_area(
                                           data['address']))
                user_address.save()
                receiver_address = user_address.id

            Order(user_id=request.user.id,
                  cart_id=cart.id,
                  receiver_name=data['receiver_name'],
                  receiver_phone=data['receiver_phone'],
                  delivery_request=data['delivery_request'],
                  order_number=order_number,
                  address_id=receiver_address).save()

            Cart(user=User.objects.get(id=request.user.id)).save()

            return HttpResponse(status=200)

        except KeyError:
            return HttpResponse(status=400)
Example #3
0
def index(request):
    # a = Address(name='home2', location='12354', user_id=1, type=UserType.USER)
    # a.save()
    user = User()
    # a = Address()
    # a.support()
    # print(User.objects.values())
    user = User()
    return ok_response(user.publics_user_serializer(User.objects.all()))
    # return ok_response(PublicUser(User.objects))
    return ok_response(User.objects.annotate(Count('address')).values())
    address = Address()
    # return
    return ok_response(address.support())
Example #4
0
def create_user(request):
    user_data=json.loads(request.POST.get('data'))
    data=user_data['user']
    print type(data)
    username=data['username']
    fname=data['fname']
    lname=data['lname']
    u=User(username=username,fname=fname,lname=lname)
    u.save()
    address=data['address']
    for ad in address:
        a=Address(user_id=u,address=ad)
        a.save()
    return HttpResponse(status=201)
Example #5
0
    def post(self, request):
        name = request.POST.get('name')
        phone = request.POST.get('phone')
        address1 = request.POST.get('address')
        address2 = Address()
        address2.name = name
        address2.user = request.user
        address2.phone = phone
        address2.address = address1
        address2.save()

        return JsonResponse({'res': 1})
Example #6
0
    def done(self, form_list, form_dict, **kwargs):
        """
        Gather the data from the three forms. If the user already exists,
        update the profile, if not create a new user. Then add a new membership.
        """
        login_step = self.get_cleaned_data_for_step('login')
        address_step = self.get_cleaned_data_for_step('user_info')['address']
        profile_step = self.get_cleaned_data_for_step('user_info')['profile']
        membership_step = self.get_cleaned_data_for_step('membership')

        # Renew membership for current user
        if login_step is None:
            u = self.request.user

            # Update the user profile
            profile_form = ProfileForm(profile_step, instance=u.profile)
            u.profile = profile_form.save()
            u.save()
        else:
            # Create a new user from steps 'login' & 'profile'
            u = User(email=login_step['email'])
            u.is_active = False  # Not activated yet
            p = Profile(**profile_step)
            p.save()

            u.profile = p
            u.save()

        # Create or update address info
        addresses = u.profile.address_set.all()
        if len(addresses) > 0:
            add = addresses[0]
            add = AddressForm(address_step, instance=addresses[0])
        else:
            add = Address(**address_step)
            add.profile = u.profile
        add.save()

        # Create a new Membership object
        membership = Membership(**membership_step)
        membership.profile = u.profile
        membership.start_date = membership.next_start_date()
        membership.amount = membership.compute_amount()
        membership.duration = 1  # valid for one year
        membership.save()

        # Send a confirmation email if the user has to pay
        if membership.amount > 0:
            membership.email_user(status="submitted")

        mb_url = self.request.build_absolute_uri(
            reverse('membership-detail', args=[membership.uid]))

        return redirect("membership-detail", membership.uid)
Example #7
0
def address_verify(request,id):
    user = request.user
    product = Product.objects.get(id=id)
    addreses = Address.objects.filter(user=request.user)
    if user.is_authenticated():
        if request.method == 'POST':
            form = AddressForm(request.POST)
            if form.is_valid():
               address = Address(user=request.user, address1=form.cleaned_data['address1'],
                                 address2=form.cleaned_data['address2'],
                                 address3=form.cleaned_data['address3'],
                                 pincode=form.cleaned_data['pincode'],
                                 phone_number=form.cleaned_data['phone_number'])
               address.save()
               return HttpResponseRedirect("/users/address-verify/%d"% int(id))
                
        else:
            form = AddressForm()
            return render(request, "users/address_verify.html",{'id':id, 'addreses':addreses,'form':form})
    else:
        return render(request,'users/login_popup.html')
Example #8
0
def add_address(request):
    if request.method == 'POST':
        form = AddressForm(request.POST)
        if form.is_valid():
            location = Location(house_number=form.cleaned_data['house_number'],
                                street=form.cleaned_data['street'],
                                city_name=form.cleaned_data['city_name'],
                                zip_code=form.cleaned_data['zip_code'])
            location.save()
            coord = find_coordinates(location.house_number,location.street,location.zip_code,location.city_name)
            location.latitude = float(coord.split(",")[2])
            location.longitude = float(coord.split(",")[3])
            location.save()
            address = Address(user=request.user,location=location)
            address.save()
            request.user.message_set.create(message="Adresse ajoutée.")
            return HttpResponseRedirect('/users/address/edit/%s'%address.id)
        else:
            return render_to_response('users/add_address.html', {'form':form},RequestContext(request))
    else:
        form = AddressForm()
        return render_to_response('users/add_address.html', {'form':form},RequestContext(request))
Example #9
0
def address(request):
    user_id = request.user.id
    if request.method == 'GET':
        data = {
            'title': '我的',
            'is_login': True
        }
        user = Users.objects.get(pk=user_id)
        data['username'] = user.u_username
        user_address = Address.objects.filter(a_user_id=user_id).order_by('-a_is_default')
        data['address'] = user_address
        data['cart_num'] = get_cart_num(user_id)
        return render(request, 'user/address.html', context=data)
    elif request.method == "POST":
        name = request.POST.get('name')
        phone = request.POST.get('phone')
        address_detail = request.POST.get('address')
        code = request.POST.get("code")
        if request.POST.get('default'):
            default = True
            address_sure = Address.objects.filter(a_user_id=user_id).get(a_is_default=True)
            address_sure.a_is_default = False
            address_sure.save()
        else:
            default = False
            try:
                address_sure = Address.objects.filter(a_user_id=user_id).get(a_is_default=True)
            except Address.DoesNotExist:
                default = True
        address_obj = Address()
        address_obj.a_name = name
        address_obj.a_phone = phone
        address_obj.a_address = address_detail
        address_obj.a_code = code
        address_obj.a_is_default = default
        address_obj.a_user_id = user_id
        address_obj.save()
        return redirect(reverse('users:address'))
Example #10
0
def save_address(customer, address_fields):
    '''saving address to address model but update if the default is set to True'''
    if address_fields[5]:
        values_to_update = {
            'address1': address_fields[0],
            'address2': address_fields[1],
            'country': address_fields[2],
            'zip_code': address_fields[3]
        }
        address, created = Address.objects.update_or_create(
            customer=customer,
            address_type=address_fields[4],
            default=True,
            defaults=values_to_update)
    else:
        address = Address(customer=customer,
                          address1=address_fields[0],
                          address2=address_fields[1],
                          country=address_fields[2],
                          zip_code=address_fields[3],
                          address_type=address_fields[4],
                          default=address_fields[5])
        address.save()
    return address
Example #11
0
def checkout(request):
    if request.user.is_authenticated and request.user.profile.type == "E":
        messages.warning(request, "You can't order with an employee profile")
        return redirect('users:dashboard')
    cart = request.session['cart_items']
    cart_items = []
    bill_tot = 0
    for key,count in cart.items():
        f = food_item.find(key)
        if f.is_combo:
            f.combo_internals = f.find_combo_internals(f.food_id)
        cart_items.append((f, count));
        bill_tot += count * f.price
    addresses = Address.get_addresses(request.user.profile.customer_id)

    return render(request, 'foods/checkout.html', {'cart':cart_items, 'total_bill':bill_tot, 'addresses':addresses, 'cart_str':json.dumps(cart)})
Example #12
0
    def post(self, request, clientid, *args, **kwargs):
        try:
            client = ClientUser.objects.get(pk=clientid)
            address = Address.objects.get(user=client)
        except ObjectDoesNotExist as e:
            pass
        except MultipleObjectsReturned as e:
            pass

        clientForm = ClientUserForm(request.POST, instance=client)
        addressForm = AddressForm(request.POST,
                                  instance=Address(user=client, pk=address.id))
        if clientForm.is_valid() and addressForm.is_valid():
            clientForm.save()
            addressForm.save()
            return HttpResponseRedirect('/costomer/data/')

        return render(request, self.template_name, self.__context)
Example #13
0
 def post(self, request):
     """Address API GET
     Args:
         country: (str)
         region: (str)
         town: (str)
         neighborhood: (str)
         zip_code: (str)
         street: (str)
         street_number: (str)
         suite_number: (str)
     Description:
         create directions
     """
     user = get_jwt_user(request)
     data = request.data
     req_inf = RequestInfo()
     try:
         if user is not None:
             client = Client.objects.get(user=user)
             address = Address.create(
                 data.get('country'),
                 data.get('region'),
                 data.get('town'),
                 data.get('neighborhood'),
                 data.get('zip_code'),
                 data.get('street'),
                 data.get('street_number'),
                 data.get('suite_number')
             )
             client.addresses.add(address)
             client.save()
             return req_inf.status_200('address created')
         else:
             return req_inf.status_401('token invalido')
     except ObjectDoesNotExist as e:
         return req_inf.status_404(e.args[0])
     except Exception as e:
         return req_inf.status_400(e.args[0])
Example #14
0
    def __create_context(self, user, clientid):
        try:
            client = ClientUser.objects.get(pk=clientid)
            address = Address.objects.get(user=client)
        except ObjectDoesNotExist as e:
            pass
        except MultipleObjectsReturned as e:
            pass

        clientForm = ClientUserForm(request.POST, instance=client)
        addressForm = AddressForm(request.POST,
                                  instance=Address(user=client, pk=address.id))

        if user.is_superuser and user.is_staff:
            self.__context = {
                'formclient': clientForm,
                'formaddress': addressForm
            }
        elif user.is_staff and not user.is_superuser:
            self.__context.update({'formaddress': addressForm})
            self.__context.update()
        elif user.has_perms(
                'view_address') and not user.has_perms('change_address'):
            self.__context = {}
Example #15
0
    def post(self, *args, **kwargs):
        form = CheckoutForm(self.request.POST or None)
        try:
            order = Order.objects.get(user=self.request.user, ordered=False)
            if form.is_valid():
                use_default_delivery = form.cleaned_data.get(
                    'use_default_delivery')
                if use_default_delivery:
                    print("Using the default delivery address")
                    address_qs = Address.objects.filter(
                        user=self.request.user,    
                        default=True
                    )
                    if address_qs.exists():
                        delivery_address = address_qs[0]
                        order.delivery_address = delivery_address
                        order.save()
                    else:
                        messages.info(
                            self.request, "No default delivery address available")
                        return redirect('checkout')
                else:
                    print("User is entering a new delivery address")
                    delivery_address = form.cleaned_data.get(
                        'delivery_address')
                    delivery_station = form.cleaned_data.get(
                        'delivery_station')
                    mobi_number = form.cleaned_data.get(
                        'mobi_number')    

                    if is_valid_form([delivery_address, delivery_station, mobi_number]):
                        delivery_address = Address(
                            user=self.request.user,
                            delivery_address=delivery_address,
                            shipping_station=delivery_station,
                            mobi_number=mobi_number
                        )
                        delivery_address.save()

                        order.delivery_address = delivery_address
                        order.save()

                        set_default_delivery = form.cleaned_data.get(
                            'set_default_delivery')
                        if set_default_delivery:
                            delivery_address.default = True
                            delivery_address.save()

                    else:
                        messages.info(
                            self.request, "Please fill in the required delivery address field")
                        return redirect('checkout')
    
                payment_option = form.cleaned_data.get('payment_option')

                if payment_option == 'M':
                    return redirect(reverse('globalbiz-home'))
                    #return redirect('payment', payment_option='Mpesa')
                elif payment_option == 'P':
                    print('Hey')
                    #self.request.session['order_id'] = order.id
                    #return redirect(reverse('payment:process'))
                    #messages.add_message(self.request, messages.INFO, 'Order Placed!')
                    #return redirect('checkout')
                else:
                    messages.warning(
                        self.request, "Invalid payment option selected")
                    return redirect('checkout')
        except ObjectDoesNotExist:
            messages.warning(self.request, "You do not have an active order")
            return redirect("order-summary")
    def handle(self, *args, **options):
        path = args[0]

        if path.startswith('http'):
            content = json.load(urllib2.urlopen(path))
        else:
            content = json.load(open(path))

        for item in content:
            if not '@' in item['username']:
                print item['username']
                continue

            try:
                user = User.objects.get(id=int(item['id']))
            except User.DoesNotExist:
                user = User(id=int(item['id']))

            user.email = item['username']
            user.password = item['password']
            user.title = item['fullname']
            user.phone = item.get('phone', '')

            birthday = None
            if 'year' in item:
                birthday = datetime.date(int(item['year']), int(item['month']), int(item['mday']))
            user.birthday = birthday

            user.is_active = item['status'] == '1'

            if item['franch'] == '10':
                user.status = User.STATUS_FRANCHISEE
            elif item['retail'] == '10':
                user.status = User.STATUS_CUSTOMER
            elif item['retail'] == '0':
                user.status = User.STATUS_WHOLESALE

            user.save()

            for addr in item['addresses']:
                try:
                    address = Address.objects.get(id=int(addr['id']))
                except Address.DoesNotExist:
                    address = Address(id=int(addr['id']))

                address.user = user
                if not address.city:
                    address.city = addr['city']
                if not address.postal_code:
                    address.postal_code = ''
                if not address.street:
                    address.street = ''
                if not address.house:
                    address.house = ''
                if not address.flat:
                    address.flat = ''
                if not address.phone:
                    address.phone = addr.get('to_phone', addr.get('fax', ''))
                if not address.email:
                    address.email = addr.get('to_email', '')
                address.receiver_title = addr.get('to_name', addr.get('name', ''))
                address.original_string = addr['address']

                address.save()
            '''
Example #17
0
def set_user_profile_data(user_id):
    userData = User.objects.filter(id=user_id)[0]

    profileData = Profile.objects.filter(id=user_id)[0]

    if profileData.seller_details is None:
        shop_details_data = ShopDetails()
        shop_details_data.save()
        seller_details_data = SellerDetails()
        seller_details_data.shop_details = shop_details_data
        seller_details_data.save()
        profileData.seller_details = seller_details_data
        profileData.save()
    else:
        seller_details_data = profileData.seller_details
    seller_details_data.upload_id_front_url = seller_details_data.upload_id_front_url if seller_details_data.upload_id_front_url else None
    upload_id_front_name = get_filename_from_url(
        seller_details_data.upload_id_front_url
    ) if seller_details_data.upload_id_front_url else None
    seller_details_data.upload_id_back_url = seller_details_data.upload_id_back_url if seller_details_data.upload_id_back_url else None
    upload_id_back_name = get_filename_from_url(
        seller_details_data.upload_id_back_url
    ) if seller_details_data.upload_id_back_url else None
    seller_details_data.has_agreed_to_terms = 'Agreed' if seller_details_data.has_agreed_to_terms else 'Not yet agreed'

    shop_details_data = seller_details_data.shop_details
    shop_details_data.holiday_mode = 'On' if shop_details_data.holiday_mode else 'Off'

    if profileData.business_details is None:
        business_address_data = Address()
        business_address_data.save()
        business_details_data = BusinessDetails()
        business_details_data.business_address = business_address_data
        business_details_data.save()
        profileData.business_details = business_details_data
        profileData.save()
    else:
        business_details_data = profileData.business_details
    business_address_data = business_details_data.business_address
    street_bldg = business_address_data.street_bldg + ' ' if business_address_data.street_bldg != None else ''
    barangay = business_address_data.barangay + ' ' if business_address_data.barangay != None else ''
    city = business_address_data.city + ' ' if business_address_data.city != None else ''
    region_state = business_address_data.region_state + ' ' if business_address_data.region_state != None else ''
    country = business_address_data.country + ' ' if business_address_data.country != None else ''
    postal_code = str(
        business_address_data.postal_code
    ) + ' ' if business_address_data.postal_code != None else ''
    business_address = street_bldg + barangay + city + region_state + postal_code + country

    if business_address == '':
        business_address = None

    bir_documents_data = Documents.objects.filter(profile_id=user_id,
                                                  document_type='bir')

    if len(bir_documents_data) == 0:
        bir_documents_data = Documents()
        bir_documents_data.document_type = 'bir'
        bir_documents_data.profile_id = profileData.id
        bir_documents_data.save()
    else:
        bir_documents_data = bir_documents_data[0]
    bir = get_filename_from_url(bir_documents_data.document_url
                                ) if bir_documents_data.document_url else None
    dti_documents_data = Documents.objects.filter(profile_id=user_id,
                                                  document_type='dti')
    if len(dti_documents_data) == 0:
        dti_documents_data = Documents()
        dti_documents_data.document_type = 'dti'
        dti_documents_data.profile_id = profileData.id
        dti_documents_data.save()
    else:
        dti_documents_data = dti_documents_data[0]
    dti = get_filename_from_url(dti_documents_data.document_url
                                ) if dti_documents_data.document_url else None
    sec_documents_data = Documents.objects.filter(profile_id=user_id,
                                                  document_type='sec')
    if len(sec_documents_data) == 0:
        sec_documents_data = Documents()
        sec_documents_data.document_type = 'sec'
        sec_documents_data.profile_id = profileData.id
        sec_documents_data.save()
    else:
        sec_documents_data = sec_documents_data[0]
    sec = get_filename_from_url(sec_documents_data.document_url
                                ) if sec_documents_data.document_url else None
    permit_documents_data = Documents.objects.filter(profile_id=user_id,
                                                     document_type='permit')
    if len(permit_documents_data) == 0:
        permit_documents_data = Documents()
        permit_documents_data.document_type = 'permit'
        permit_documents_data.profile_id = profileData.id
        permit_documents_data.save()
    else:
        permit_documents_data = permit_documents_data[0]
    permit = get_filename_from_url(
        permit_documents_data.document_url
    ) if permit_documents_data.document_url else None

    if profileData.pickup_address is None:
        pickup_contact_data = AddressContactDetails()
        pickup_contact_data.save()
        pickup_address_data = Address()
        pickup_address_data.contact_details = pickup_contact_data
        pickup_address_data.save()
        profileData.pickup_address = pickup_address_data
        profileData.save()
    else:
        pickup_address_data = profileData.pickup_address
    pickup_contact_data = pickup_address_data.contact_details
    street_bldg = pickup_address_data.street_bldg + ' ' if pickup_address_data.street_bldg != None else ''
    barangay = pickup_address_data.barangay + ' ' if pickup_address_data.barangay != None else ''
    city = pickup_address_data.city + ' ' if pickup_address_data.city != None else ''
    region_state = pickup_address_data.region_state + ' ' if pickup_address_data.region_state != None else ''
    country = pickup_address_data.country + ' ' if pickup_address_data.country != None else ''
    postal_code = str(
        pickup_address_data.postal_code
    ) + ' ' if pickup_address_data.postal_code != None else ''
    pickup_address = street_bldg + barangay + city + region_state + postal_code + country

    if pickup_address == '':
        pickup_address = None

    if profileData.return_address is None:
        return_contact_data = AddressContactDetails()
        return_contact_data.save()
        return_address_data = Address()
        return_address_data.contact_details = return_contact_data
        return_address_data.save()
        profileData.return_address = return_address_data
        profileData.save()
    else:
        return_address_data = profileData.return_address
    return_contact_data = return_address_data.contact_details
    street_bldg = return_address_data.street_bldg + ' ' if return_address_data.street_bldg != None else ''
    barangay = return_address_data.barangay + ' ' if return_address_data.barangay != None else ''
    city = return_address_data.city + ' ' if return_address_data.city != None else ''
    region_state = return_address_data.region_state + ' ' if return_address_data.region_state != None else ''
    country = return_address_data.country + ' ' if return_address_data.country != None else ''
    postal_code = str(
        return_address_data.postal_code
    ) + ' ' if return_address_data.postal_code != None else ''
    return_address = street_bldg + barangay + city + region_state + postal_code + country

    if return_address == '':
        return_address = None

    ctr = 0
    enable_fields = True
    if seller_details_data.name_on_id:
        ctr += 1
    if seller_details_data.id_type:
        ctr += 1
    if seller_details_data.upload_id_front_url:
        ctr += 1
    if seller_details_data.upload_id_back_url:
        ctr += 1
    if seller_details_data.has_agreed_to_terms == 'Agreed':
        ctr += 1
    if shop_details_data.shop_name:
        ctr += 1
    if pickup_address_data.street_bldg:
        ctr += 1
    if pickup_address_data.country:
        ctr += 1
    if pickup_address_data.region_state:
        ctr += 1
    if pickup_address_data.city:
        ctr += 1
    if pickup_address_data.barangay:
        ctr += 1
    if pickup_address_data.postal_code:
        ctr += 1
    if return_address_data.street_bldg:
        ctr += 1
    if return_address_data.country:
        ctr += 1
    if return_address_data.region_state:
        ctr += 1
    if return_address_data.city:
        ctr += 1
    if return_address_data.barangay:
        ctr += 1
    if return_address_data.postal_code:
        ctr += 1
    if seller_details_data.seller_status == 'Pending for Review' and ctr == 18:
        enable_fields = False

    countries_data = get_countries()
    countries_filtered_data = []
    for v in countries_data:
        countries_filtered_data.append({'name': v['name']})

    return {
        'profileData': profileData,
        'userData': userData,
        'seller_details_data': seller_details_data,
        'upload_id_front_name': upload_id_front_name,
        'upload_id_back_name': upload_id_back_name,
        'shop_details_data': shop_details_data,
        'business_details_data': business_details_data,
        'business_address_data': business_address_data,
        'business_address': business_address,
        'bir_documents_data': bir_documents_data,
        'bir': bir,
        'dti_documents_data': dti_documents_data,
        'dti': dti,
        'sec_documents_data': sec_documents_data,
        'sec': sec,
        'permit_documents_data': permit_documents_data,
        'permit': permit,
        'pickup_address_data': pickup_address_data,
        'pickup_contact_data': pickup_contact_data,
        'pickup_address': pickup_address,
        'return_address_data': return_address_data,
        'return_contact_data': return_contact_data,
        'return_address': return_address,
        'enable_fields': enable_fields,
        'countries_filtered_data': countries_filtered_data
    }
Example #18
0
    def post(self, *args, **kwargs):
        form = CheckoutForm(self.request.POST or None)
        try:
            order = Order.objects.get(user=self.request.user, ordered=False)
            if form.is_valid():

                use_default_shipping = form.cleaned_data.get(
                    'use_default_shipping')
                if use_default_shipping:
                    print("Using the defualt shipping address")
                    address_qs = Address.objects.filter(
                        user=self.request.user,
                        address_type='S',
                        default=True
                    )
                    if address_qs.exists():
                        shipping_address = address_qs[0]
                        order.shipping_address = shipping_address
                        order.save()
                    else:
                        messages.info(
                            self.request, "No default shipping address available")
                        return redirect('core:checkout')
                else:
                    print("User is entering a new shipping address")
                    shipping_address1 = form.cleaned_data.get(
                        'shipping_address')
                    shipping_address2 = form.cleaned_data.get(
                        'shipping_address2')
                    shipping_country = form.cleaned_data.get(
                        'shipping_country')
                    shipping_zip = form.cleaned_data.get('shipping_zip')

                    if is_valid_form([shipping_address1, shipping_country, shipping_zip]):
                        shipping_address = Address(
                            user=self.request.user,
                            street_address=shipping_address1,
                            apartment_address=shipping_address2,
                            country=shipping_country,
                            zip=shipping_zip,
                            address_type='S'
                        )
                        shipping_address.save()

                        order.shipping_address = shipping_address
                        order.save()

                        set_default_shipping = form.cleaned_data.get(
                            'set_default_shipping')
                        if set_default_shipping:
                            shipping_address.default = True
                            shipping_address.save()

                    else:
                        messages.info(
                            self.request, "Please fill in the required shipping address fields")

                use_default_billing = form.cleaned_data.get(
                    'use_default_billing')
                same_billing_address = form.cleaned_data.get(
                    'same_billing_address')

                if same_billing_address:
                    billing_address = shipping_address
                    billing_address.pk = None
                    billing_address.save()
                    billing_address.address_type = 'B'
                    billing_address.save()
                    order.billing_address = billing_address
                    order.save()

                elif use_default_billing:
                    print("Using the defualt billing address")
                    address_qs = Address.objects.filter(
                        user=self.request.user,
                        address_type='B',
                        default=True
                    )
                    if address_qs.exists():
                        billing_address = address_qs[0]
                        order.billing_address = billing_address
                        order.save()
                    else:
                        messages.info(
                            self.request, "No default billing address available")
                        return redirect('core:checkout')
                else:
                    print("User is entering a new billing address")
                    billing_address1 = form.cleaned_data.get(
                        'billing_address')
                    billing_address2 = form.cleaned_data.get(
                        'billing_address2')
                    billing_country = form.cleaned_data.get(
                        'billing_country')
                    billing_zip = form.cleaned_data.get('billing_zip')

                    if is_valid_form([billing_address1, billing_country, billing_zip]):
                        billing_address = Address(
                            user=self.request.user,
                            street_address=billing_address1,
                            apartment_address=billing_address2,
                            country=billing_country,
                            zip=billing_zip,
                            address_type='B'
                        )
                        billing_address.save()

                        order.billing_address = billing_address
                        order.save()

                        set_default_billing = form.cleaned_data.get(
                            'set_default_billing')
                        if set_default_billing:
                            billing_address.default = True
                            billing_address.save()

                    else:
                        messages.info(
                            self.request, "Please fill in the required billing address fields")

                payment_option = form.cleaned_data.get('payment_option')

                if payment_option == 'S':
                    return redirect('core:payment', payment_option='stripe')
                elif payment_option == 'P':
                    return redirect('core:payment', payment_option='paypal')
                else:
                    messages.warning(
                        self.request, "Invalid payment option selected")
                    return redirect('core:checkout')
        except ObjectDoesNotExist:
            messages.warning(self.request, "You do not have an active order")
            return redirect("core:order-summary")
Example #19
0
def add_address(request):
    if request.method == 'POST':
        if 'where' in request.POST:
            return render(request, 'users/address.html')
        nombre = request.POST['nombre']
        apellido = request.POST['apellido']
        direccion = request.POST['direccion']
        cp = request.POST['cp']
        ciudad = request.POST['ciudad']
        numero = request.POST['numero']
        correo = request.POST['correo']
        adicional = request.POST['adicional']

        try:
            address = Address.objects.get(user=request.user)
        except:
            address = Address(nombre=nombre,
                              apellido=apellido,
                              direccion=direccion,
                              cp=cp,
                              ciudad=ciudad,
                              numero=numero,
                              correo=correo,
                              adicional=adicional,
                              user=request.user,
                              recordar=True)
            address.save()
        else:
            address.nombre = nombre
            address.apellido = apellido
            address.direccion = direccion
            address.cp = cp
            address.ciudad = ciudad
            address.numero = numero
            address.correo = correo
            address.adicional = adicional
            address.save()

    return redirect('payment')
Example #20
0
def add_address(request):
    user = User.objects.get(pk=request.session.get('uid'))
    if Address.objects.filter(user=user).count() > 20:
        return JsonResponse({'code': 1, 'msg': '只能添加20个地址'})
    if not request.POST.get('a_email') or not request.POST.get('a_phone') or not request.POST.get('a_region') or not request.POST.get('a_place') or not request.POST.get('a_name') or not request.POST.get('fixed_telephone'):
        return JsonResponse({'code': 1, 'msg': '参数错误'})
    address = Address()
    address.a_email = request.POST.get('a_email')
    address.a_phone = request.POST.get('a_phone')
    address.a_region = request.POST.get('a_region')
    address.a_place = request.POST.get('a_place')
    address.a_name = request.POST.get('a_name')
    address.fixed_telephone = request.POST.get('fixed_telephone')
    address.user = user
    if Address.objects.filter(user=user).count() == 0:
        address.is_default = True
    address.save()
    return JsonResponse({'code': 0})