def create(request):
    """Добавление нового адреса доставки"""

    initial = {
        'email': request.user.email,
    }
    # TODO: Возможно, заполнять только для розничных покупателей?
    if request.user.title:
        initial['receiver_title'] = request.user.title
    if request.user.phone:
        initial['phone'] = request.user.phone

    if request.POST:
        form = AddressForm(request.POST, initial=initial)
        if form.is_valid():
            address = form.save(commit=False)
            address.user = request.user
            address.save()

            return HttpResponseRedirect(reverse('users.address.index'))

    else:
        form = AddressForm(initial=initial)

    context = {
        'form': form,
    }

    return render(request, 'users/addresses/create.html', context)
def checkout(request):
    if request.method == 'POST':
        form = request.POST
        if form['action'] == 'confirm':
            form = AddressForm(request.POST or None)
            if not form.is_valid():
                return HttpResponse("invalid form")
            data = form.cleaned_data
            template = "<AddressValidateRequest USERID=\"796CCNY00182\">\
                             <IncludeOptionalElements>true</IncludeOptionalElements>\
                             <ReturnCarrierRoute>true</ReturnCarrierRoute>\
                             <Address ID=\"0\">\
                                 <FirmName />\
                                 <Address1></Address1>\
                                 <Address2></Address2>\
                                 <City></City>\
                                 <State></State>\
                                 <Zip5></Zip5>\
                                 <Zip4></Zip4>\
                             </Address>\
                         </AddressValidateRequest> "

            xml = ElementTree.fromstring(template)
            xml[2][1].text = ''
            xml[2][2].text = data['street']
            xml[2][3].text = data['city']
            xml[2][4].text = data['state']
            xml[2][5].text = str(data['zipcode'])

            xml = ElementTree.tostring(xml)
            payload = {'API': 'VERIFY', 'XML': xml}
            r = requests.get(
                'http://production.shippingapis.com/ShippingAPI.dll',
                params=payload)
            tree = ElementTree.fromstring(r.content)
            # for i in tree[0]:
            #     print i.text

            address = ''
            for i in range(0, 3):
                try:
                    address += tree[0][i].text + ', '
                except:
                    pass
            try:
                address += tree[0][3].text
            except:
                pass
            customer = request.user.customer
            customer.address = address
            customer.save()

            return placeOrder(request)

        elif form['action'] == 'address':
            context = {'form': AddressForm}
            return render(request, 'menu/checkout.html', context=context)
Example #3
0
 def __create_context(self, user):
     if user.is_superuser and user.is_staff:
         self.__context = {
             'formclient': ClientUserForm(),
             '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'):
         self.__context.update()
Example #4
0
def update_address(request):
    print(request.user.username)
    add_obj = None
    try:
        add_obj = Address.objects.get(user=request.user)
        if add_obj is not None:
            if request.method == 'POST':
                form = AddressForm(request.POST)

                if form.is_valid():
                    add_obj.user = request.user
                    add_obj.phone_num = form.cleaned_data.get('phone_num')
                    add_obj.address1 = form.cleaned_data.get('address1')
                    add_obj.address2 = form.cleaned_data.get('address2')
                    add_obj.city = form.cleaned_data.get('city')
                    add_obj.state = form.cleaned_data.get('state')
                    add_obj.pincode = form.cleaned_data.get('pincode')
                    add_obj.save()
                    print(add_obj.city, add_obj.state)
                    return render(request,
                                  "orders/checkout.html",
                                  context={
                                      'form': form,
                                      'object': add_obj,
                                  })
    except:
        print("create new")
        if request.method == 'POST':
            form = AddressForm(request.POST)
            if form.is_valid():
                user = request.user
                phone_num = form.cleaned_data.get('phone_num')
                address1 = form.cleaned_data.get('address1')
                address2 = form.cleaned_data.get('address2')
                city = form.cleaned_data.get('city')
                state = form.cleaned_data.get('state')
                pincode = form.cleaned_data.get('pincode')
                add_obj = Address.objects.create(user=request.user,
                                                 phone_num=phone_num,
                                                 address1=address1,
                                                 address2=address2,
                                                 city=city,
                                                 state=state,
                                                 pincode=pincode)
                add_obj.save()
                print(add_obj.city, add_obj.state)
                return render(request,
                              "orders/checkout.html",
                              context={
                                  'form': form,
                                  'object': add_obj,
                              })
    form = AddressForm()
    context = {
        'form': form,
        'object': add_obj,
    }
    return render(request, 'orders/update_address.html', context)
Example #5
0
def AddressChange(request):
    location = "Profile / Address / Change"
    fname = request.user.first_name
    lname = request.user.last_name
    st = "%s %s" %(fname,lname)

    user_profile = Profile.objects.get(Q(user=request.user))
    if request.method == "POST":
        address = user_profile.Address
        address.address_1 = request.POST['address_1']
        address.address_2 = request.POST['address_2']
        address.zip_code = request.POST['zip_code']
        address.city = request.POST['city']
        address.state = request.POST['state']

        address.save()
        user_profile.save()
        print(address)
        return redirect('../../profile')



    else:
        Address = user_profile.Address


        form = AddressForm()
        return render(request, 'users/update-address.html', {'username': st, 'user': request.user, 'location': 'Profile', 'logout':'../logout', 'form': form, 'address':Address})
Example #6
0
def AddressPage(request):
    location = "Profile / Address"
    fname = request.user.first_name
    lname = request.user.last_name
    st = "%s %s" %(fname,lname)
    profile = Profile.objects.get(
        Q(user = request.user.id)
    )
    picture = "/media/%s"%(profile.picture)



    if request.method == "POST":
        form = AddressForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            messages.success(request,"Address Saved!")
            print("working")
            return redirect('../../profile')
        else:
            messages.error(request, "The form wasn't valid for some reason")
            #return redirect('../address-info')
            #print(get_object_or_404(form))
            print("Not working")

    else:
        form = AddressForm()
    return render(request, 'users/update-address.html', {
        'form': form, 'username': st, 'location': location, 'logout':'../../logout', 'picture' : picture
    })
Example #7
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)
def update(request, address_id):
    address = get_object_or_404(Address, id=address_id, user=request.user)
    if request.POST:
        form = AddressForm(request.POST, instance=address)
        if form.is_valid():
            address = form.save(commit=False)
            address.user = request.user
            address.save()

            return HttpResponseRedirect(reverse('users.address.index'))

    else:
        form = AddressForm(instance=address)

    context = {
        'form': form,
    }

    return render(request, 'users/addresses/update.html', context)
Example #9
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 #10
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 #11
0
def address(request):
    if request.method =='POST':
        form = AddressForm(request.POST)
        if form.is_valid():
            profile = form.save(commit=False) # this insures it is assigned to user
            profile.save()
            profile.users.set([request.user.pk]) # many to many user save
            return redirect('myaccount')
    else:
        form = AddressForm()

    return render(request, 'address.html', {'form': form}) 
Example #12
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 = {}