def address_detail(request, username, label): # if request.is_ajax(): other_user = get_object_or_404(User, username=username) address = get_address_or_404(other_user, label) is_friend = Friendship.objects.are_friends(request.user, other_user) is_me = (other_user == request.user) # retrieve details if request.method == 'GET' and (is_friend or is_me): return render_to_response( 'profiles/address_detail.html', { 'other_user': other_user, 'address': address, 'is_me': is_me }, ) # update existing resource elif request.method == 'POST' and is_me: form = AddressForm(request.POST, instance=address) # if form saves, return detail for saved resource if form.is_valid() and is_label_unique_for_user(other_user, form.cleaned_data['label'], address): address = form.save() if request.is_ajax(): return JsonResponse({'valid': True, 'label': address.label}) # return HttpResponse(simplejson.dumps(), mimetype='application/javascript') else: return render_to_response( 'profiles/address_detail.html', { 'other_user': other_user, 'address': address, }, ) # if save fails, go back to edit_resource page else: if request.is_ajax(): error_data = { 'valid': False, 'label': address.label, 'errors': form.errors, 'label_error': not is_label_unique_for_user(other_user, form.cleaned_data['label'], address) } return JsonResponse(error_data) #return HttpResponse(simplejson.dumps(error_data), mimetype='application/javascript') else: return render_to_response( 'profiles/edit_address.html', { 'form': form, 'other_user': other_user, 'address': address, }, )
def create_address(request, username, object=None): form = AddressForm(request.POST) other_user = get_object_or_404(User, username=username) if form.is_valid() and is_label_unique_for_user(other_user, form.cleaned_data['label'], None): address = form.save(commit=False) profile = other_user.get_profile() address.content_object = profile address.save() profile.addresses.add(address) if request.is_ajax(): return JsonResponse({'valid': True, 'label': address.label}) # return HttpResponse(simplejson.dumps({'valid': True, 'label': address.label}), mimetype='application/javascript') else: #return HttpResponseRedirect(reverse('profile_address_detail', kwargs={'username': username, 'label': address.label})) return HttpResponseRedirect(reverse('profile_edit')) else: label = "" label_error = False if form.is_valid(): label = form.cleaned_data['label'] label_error = not is_label_unique_for_user(other_user, form.cleaned_data['label'], None) if request.is_ajax(): errorlist = [] for field in form: if field.errors: errorlist.append(field.errors) error_data = { 'valid': False, 'label': label, 'errors': errorlist, 'label_error': label_error } return JsonResponse(error_data) # return HttpResponse(simplejson.dumps(error_data), mimetype='application/javascript') else: return render_to_response( 'profiles/new_address.html', { 'other_user': other_user, 'form': form, }, )
def edit_address(request, username, id, object=None): # if request.is_ajax(): if request.method == 'POST': return address_detail(request, username, id) other_user = get_object_or_404(User, username=username) address = get_address_or_404(other_user, id) form = AddressForm(instance=address) return render_to_response( 'profiles/edit_address.html', { 'form': form, 'other_user': other_user, 'address': address, }, )
def post(self, request, *args, **kwargs): forms = { 'user': UserForm(request.POST), 'address': AddressForm(request.POST) } if all([x.is_valid() for x in forms.values()]): form_data = { 'user': forms['user'].cleaned_data, 'address': forms['address'].cleaned_data } self.request.session['form'] = form_data return redirect('orders:check-order') return self.render_to_response(self.get_context_data(forms=forms))
def get(self, request, *args, **kwargs): if request.user.is_authenticated: user = request.user address = user.address forms = { 'user': UserForm(instance=user), 'address': AddressForm(instance=address) } else: # Handle situation when not authenticated user changed his mind on # CheckOrder step and wants to change some information, to not # fill the form again - we use already written in session data # as initial. initial = {'user': None, 'address': None} form_in_session = self.request.session.get('form') if form_in_session is not None: initial.update(form_in_session) forms = { 'user': UserForm(initial=initial['user']), 'address': AddressForm(initial=initial['address']) } return self.render_to_response(self.get_context_data(forms=forms))
def checkout(request): try: cart_id = request.session['cart_id'] cart = Cart.objects.get(id=cart_id) except: cart = False return HttpResponseRedirect('/cart/') amount = int(cart.total) * 100 try: stripe_id = add_stripe(request.user) except: pass new_number = id_generator() new_order, created = Order.objects.get_or_create(cart=cart, user=request.user) if created: new_order.order_id = str(new_number[:2]) + str(new_order.cart.id) + str(new_number[3:]) new_order.status = 'Started' new_order.save() address_form = AddressForm(request.POST or None) if request.method == 'POST': address_form = AddressForm(request.POST) token = request.POST['stripeToken'] profile = request.user.get_profile() customer = stripe.Customer.retrieve(stripe_id) new_card = customer.cards.create(card=token) if address_form.is_valid(): form = address_form.save(commit=False) print form if address_form.cleaned_data['save_card'] == True: # save card info new_card.address_line1 = form.address1 if len(form.address2) > 1: new_card.address_line2 = form.address2 new_card.address_city = form.city new_card.address_zip = form.postal_code new_card.address_country = form.country new_card.save() try: form.user = request.user form.save() print 'form saved' except: pass else: print 'did not save card' charge = stripe.Charge.create( amount = amount, currency = "USD", customer = customer.id, description = "Payment for order %s" %(new_order.order_id) ) if charge: print 'charged' # Update new order new_order.status = 'Collected' new_order.cc_four = new_card.last4 new_order.address = form new_order.save() # Create Shipping Status Entry add_shipping = ShippingStatus(order=new_order) add_shipping.save() # destroy cart cart.user = request.user cart.active = False cart.save() # request.session.flush() del request.session['cart_id'] del request.session['cart_items'] return HttpResponseRedirect('/orders/') return render_to_response('cart/checkout.html', locals(), context_instance=RequestContext(request))
def checkout(request): try: cart_id = request.session['cart_id'] cart = Cart.objects.get(id=cart_id) except: cart = False return HttpResponseRedirect('/cart') amount = int(cart.total * 100) try: stripe_id = add_stripe(request.user) except: pass new_number = id_generator() new_order, created = Order.objects.get_or_create(cart=cart, user=request.user) if created: new_order.order_id = str(new_number[:2]) + str( new_order.cart.id) + str(new_number[3:]) new_order.status = 'Started' new_order.save() address_form = AddressForm(request.POST or None) if request.method == "POST": address_form = AddressForm(request.POST) token = request.POST['stripeToken'] profile = request.user.get_profile() customer = stripe.Customer.retrieve(stripe_id) new_card = customer.cards.create(card=token) if address_form.is_valid(): form = address_form.save(commit=False) print form if address_form.cleaned_data['save_card'] == True: #save card info new_card.address_line1 = form.address1 if len(form.address2) > 1: new_card.address_line2 = form.address2 new_card.address_city = form.city new_card.address_zip = form.postal_code new_card.address_country = form.country new_card.save() try: form.user = request.user form.save() print 'form saved' except: pass else: print 'did not save your card' charge = stripe.Charge.create(amount=amount, currency="usd", customer=customer.id, description="Payment for order %s" % (new_order.order_id)) if charge: print 'charged' new_order.status = 'Collected' #changes the status in the admin panel! :) new_order.cc_four = new_card.last4 new_order.address = form new_order.save() add_shipping = ShippingStatus(order=new_order) add_shipping.save() cart.user = request.user #users need to be logged in for this to work cart.active = False cart.save() del request.session['cart_id'] del request.session['cart_items'] return HttpResponseRedirect('/orders/') return render_to_response('cart/checkout.html', locals(), context_instance=RequestContext(request))
def address_detail(request, username, id): # if request.is_ajax(): other_user = get_object_or_404(User, username=username) address = get_address_or_404(other_user, id) is_friend = Friendship.objects.are_friends(request.user, other_user) is_me = (other_user == request.user) # retrieve details if request.method == 'GET' and (is_friend or is_me): return render_to_response( 'profiles/address_detail.html', { 'other_user': other_user, 'address': address, 'is_me': is_me }, ) # update existing resource elif request.method == 'POST' and is_me: form = AddressForm(request.POST, instance=address) # if form saves, return detail for saved resource if form.is_valid() and is_label_unique_for_user( other_user, form.cleaned_data['label'], address): address = form.save() if request.is_ajax(): return JsonResponse({ 'valid': True, 'label': address.label, 'id': address.pk }) # return HttpResponse(simplejson.dumps(), mimetype='application/javascript') else: return render_to_response( 'profiles/address_detail.html', { 'other_user': other_user, 'address': address, }, ) # if save fails, go back to edit_resource page else: if request.is_ajax(): error_html = render_to_string('profiles/edit_address.html', { 'form': form, 'other_user': other_user, 'address': address, }) error_data = { 'valid': False, 'html': error_html, #'label': address.label, #'errors': form.errors, #'label_error': not is_label_unique_for_user(other_user, form.POST.get('label', ''), address) } return JsonResponse(error_data) #return HttpResponse(simplejson.dumps(error_data), mimetype='application/javascript') else: return render_to_response( 'profiles/edit_address.html', { 'form': form, 'other_user': other_user, 'address': address, }, ) else: return HttpResponse("forbidden")
def checkout_success(request, order_number): """ Handle successful checkouts """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) # Attach the user's profile to the order order.user_profile = profile order.save() # Save the user's info if save_info: address_data = { 'full_name': order.full_name, 'phone_number': order.phone_number, 'street_address1': order.street_address1, 'street_address2': order.street_address2, 'postcode': order.postcode, 'town_or_city': order.town_or_city, 'county': order.county, 'country': order.country, } address_lookup = Address.objects.filter( userprofile=profile, full_name=order.full_name, phone_number=order.phone_number, street_address1=order.street_address1, street_address2=order.street_address2, postcode=order.postcode, town_or_city=order.town_or_city, county=order.county, country=order.country, ) if not address_lookup: address_form = AddressForm(address_data) if address_form.is_valid(): address_info = address_form.save() address = get_object_or_404( Address, address_number=address_info.address_number) address.userprofile = profile address.save() messages.success( request, f'Order successfully processed! \ Your order number is {order_number}. A confirmation \ email will be sent to {order.email}.') if 'bag' in request.session: del request.session['bag'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)