def testNewAddress(self): """ Creating a new profile with an address that is not already in the database should create a new address instance. """ address = { 'street': '219 Tyne Road', 'city': 'Louisville', 'state': 'KY', 'country': 'US', 'postal_code': '40207', } address_form = AddressForm(address) self.assertTrue(address_form.is_valid()) self.profile_form.instance.address = address_form.get_or_create( ) # Saves new address self.profile_form.instance.user = self.user self.profile_form.save() # Both counts should have incremented since setup self.assertEqual(TcsUserProfile.objects.count(), 1) self.assertEqual(Address.objects.count(), 2) # Make sure the fields of the new address are correct new_address = Address.objects.last() self.assertEqual(new_address.street, '219 Tyne Rd') self.assertEqual(new_address.city, 'Louisville')
def address(request): form_class = AddressForm() context = {'form': form_class} print request.method if request.method == 'POST': form = AddressForm(request.POST) #print dir(form),form.is_valid(),type(form) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] age = form.cleaned_data['age'] # form validation # TOMMORROW: we want to validate our code to work with mail which are edu.com # we also want the candidate to be above 18years and below 50 years. # then only we want to make a entry into the database. Address.objects.create( name=name, age=age, email=email) # Making an entry into the database. return HttpResponseRedirect('/thanks/') else: print request.method, form context = {'form': form} return render(request, 'address_forms.html', context) return render(request, 'address_forms.html', context)
def set_address(req): user = req.user address_obj = Address.objects.get(user=user) address_form = AddressForm(req.POST, instance=address_obj) if address_form.is_valid(): address_form.save() messages.success(req, 'Profile details updated.') return redirect('checkout')
def checkout(request): cart_obj, is_new_cart = Cart.objects.new_or_get(request) order_obj = None if is_new_cart or cart_obj.products.count()==0: return redirect('cart:home') user = request.user billing_profile = None if user.is_authenticated: billing_profile = None login_form = LoginForm() guest_login_form = GuestForm() address_form = AddressForm() billing_address_form = AddressForm() billing_profile, created = BillingProfile.objects.new_or_get(request) billing_address_id = request.session.get('billing_address_id') shipping_address_id = request.session.get('shipping_address_id') address_qs = None if billing_profile is not None: address_qs = Address.objects.filter(billing_profile=billing_profile) # shipping_address_qs = address_qs.filter(address_type='shipping') # billing_address_qs = address_qs.filter(address_type='billing') order_obj, order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj) if billing_address_id: order_obj.billing_address = Address.objects.get(id=billing_address_id) del request.session['billing_address_id'] if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del request.session['shipping_address_id'] if billing_address_id or shipping_address_id: order_obj.save() if request.method == 'POST': is_done = order_obj.check_done() if is_done: order_obj.mark_paid() del request.session['cart_id'] request.session['cart_items'] = 0 return redirect('/cart/success') context = { 'object':order_obj, 'billing_profile': billing_profile, 'login_form': login_form, 'guest_login_form':guest_login_form, 'address_form': address_form, 'billing_address_form': billing_address_form, 'address_qs' : address_qs, } return render(request,'carts/checkout.html',context)
def setUp(self): self.data = { 'street': ' 217 tyNe road ', 'city': ' louisVILLE ', 'state': 'ky', 'country': 'US', # Field validation will not fix lowercase input 'postal_code': ' 40207 ', } self.address_form = AddressForm(self.data) self.assertTrue(self.address_form.is_valid())
def address(request): form_class = AddressForm # instance of the contact form. context={'form':form_class} if request.method == 'POST': form = AddressForm(request.POST) if form.is_valid(): print dir(form) name = form.cleaned_data['name'] email = form.cleaned_data['email'] age = form.cleaned_data['age'] print name,email,age return HttpResponseRedirect('/thanks/') return render(request,'address/address_form.html',context)
def checkout_home(request): order_obj = None cart_obj = Cart.objects.new_or_get(request) if cart_obj.products.count() == 0: return redirect("cart:home") login_form = LoginForm() guest_form = GuestForm() address_form = AddressForm() billing_address_form = AddressForm() billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id", None) address_qs = None billing_profile = BillingProfile.objects.new_or_get(request) if billing_profile is not None: address_qs = Address.objects.filter(billing_profile=billing_profile) order_obj = Order.objects.new_or_get(billing_profile, cart_obj) if shipping_address_id: order_obj.shipping_address = Address.objects.get( id=shipping_address_id) del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address = Address.objects.get( id=billing_address_id) del request.session["billing_address_id"] if shipping_address_id or billing_address_id: order_obj.save() if request.method == "POST": is_done = order_obj.check_done() if is_done: order_obj.mark_paid() del request.session['cart_id'] request.session['cart_items'] = 0 return redirect("cart:success") context = { "object": order_obj, "billing_profile": billing_profile, "form": login_form, "guest_form": guest_form, "address_form": address_form, "billing_address_form": billing_address_form, "address_qs": address_qs } return render(request, "checkout.html", context)
def register_user(request: HttpRequest): signup_form = forms.SignupForm(request.POST or None) temporary_address_form = AddressForm(request.POST or None, prefix="temporary") permanent_address_form = AddressForm(request.POST or None, prefix="permanent") print(temporary_address_form.is_valid()) if (signup_form.is_valid() and temporary_address_form.is_valid() and permanent_address_form.is_valid()): messages.info(request, "You have registered successfully. Login to continue.") signup = signup_form.save(False) signup.temporary_address = temporary_address_form.cleaned_data.get( "ward") signup.permanent_address = permanent_address_form.cleaned_data.get( "ward") signup.save() return redirect("login") return render( request, "signup.html", { "signup_form": signup_form, "temporary_address_form": temporary_address_form, "permanent_address_form": permanent_address_form, }, )
def checkout_home(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("cart:home") login_form = LoginForm() address_form = AddressForm() billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id", None) 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) order_obj, order_obj_created = Order.objects.new_or_get( billing_profile, cart_obj) if shipping_address_id: order_obj.shipping_address = Address.objects.get( id=shipping_address_id) del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address = Address.objects.get( id=billing_address_id) del request.session["billing_address_id"] if billing_address_id or shipping_address_id: order_obj.save() if request.method == "POST": "Check that order is done" is_done = order_obj.check_done() if is_done: order_obj.mark_paid() request.session['cart_items'] = 0 del request.session['cart_id'] return redirect("cart:success") context = { "object": order_obj, "billing_profile": billing_profile, "login_form": login_form, "address_form": address_form, "address_qs": address_qs, } return render(request, "cart/checkout.html", context)
def testCountryInterlock(self): """ For countries for which local flavor data structures is available, ensure the state and postal code meet the given country's format. """ # Invalid state for the United States self.data['state'] = 'zz' self.assertFalse(AddressForm(self.data).is_valid()) # Invalid postal code for the United States self.data['state'] = 'KY' self.data['postal_code'] = '40-222-405' self.assertFalse(AddressForm(self.data).is_valid()) # Any state and postal code input that meets the basic CharField restrictions should work # for countries without local flavor. self.data[ 'country'] = 'CA' # TODO - localflavor is available for Canada self.data['state'] = 'zz' self.assertTrue(AddressForm(self.data).is_valid())
def campaignCreate(request): """Create a new Campaign instance if the user does not already own a campaign.""" if request.method == 'POST': login_form = AuthenticationForm(request, data=request.POST) campaign_form = CampaignForm(request.POST) address_form = AddressForm(request.POST) if login_form.is_valid(): # The credentials are valid, and the user is active. AuthenticationForm.clean() calls # 'authenticate' and 'confirm_login_allowed'. It saves the authenticated user as the # 'user_cache' attribute. if getattr(login_form.user_cache, 'campaign', None): messages.error(request, 'You may not create more than one campaign.') return HttpResponseRedirect(reverse('login')) if campaign_form.is_valid() and address_form.is_valid(): campaign_form.instance.address = address_form.get_or_create() campaign_form.instance.owner = login_form.user_cache campaign_form.save() messages.success(request, 'You created a new campaign.') login(request, login_form.user_cache) return HttpResponseRedirect(reverse('home')) else: login_form = AuthenticationForm(request) campaign_form = CampaignForm() address_form = AddressForm() return render( request, 'campaign/create.html', { 'login_form': login_form, 'campaign_form': campaign_form, 'address_form': address_form })
def tcsuserRegister(request): """Create a new TcsUser instance and associated TcsUserProfile and Address instances.""" if request.method == 'POST': user_form = TcsUserCreationForm(request.POST) profile_form = TcsUserProfileForm(request.POST) address_form = AddressForm(request.POST) tos_form = TermsOfServiceForm(request.POST) if user_form.is_valid() and profile_form.is_valid( ) and address_form.is_valid() and tos_form.is_valid(): profile_form.instance.address = address_form.get_or_create() profile_form.instance.user = user_form.save() profile_form.save() return HttpResponse( 'Thank you for registering. Please check your e-mail within 2 hours for an activation link.' ) else: messages.error(request, 'Please fix the problems noted below.') else: user_form = TcsUserCreationForm() profile_form = TcsUserProfileForm() address_form = AddressForm() tos_form = TermsOfServiceForm() return render( request, 'tcsuser/register.html', { 'user_form': user_form, 'profile_form': profile_form, 'address_form': address_form, 'tos_form': tos_form })
def campaignEdit(request, campaign_id): """Edit a Campaign instance.""" campaign = get_object_or_404(Campaign, pk=campaign_id) if campaign.owner_id != request.user.pk: messages.error(request, "You cannot edit a campaign you do not own.") return HttpResponseRedirect(reverse('home')) if request.method == 'POST': address_form = AddressForm(request.POST, instance=campaign.address) campaign_form = CampaignForm(request.POST, instance=campaign) if address_form.is_valid() and campaign_form.is_valid(): campaign_form.instance.address = address_form.get_or_create() campaign_form.save() messages.success(request, 'You updated "{0}."'.format(campaign.name)) return HttpResponseRedirect( reverse('campaign_edit', args=[campaign_id])) else: address_form = AddressForm(instance=campaign.address) campaign_form = CampaignForm(instance=campaign) return render( request, 'campaign/edit.html', { 'address_form': address_form, 'campaign_form': campaign_form, 'campaign': campaign })
def testDuplicateAddress(self): """ Creating a new profile with an address that is already in the database should not duplicate the address. Case should not matter for matching addresses. """ address = { # Upper-cased duplicate of setup address 'street': '217 TYNE ROAD', 'city': 'LOUISVILLE', 'state': 'KY', 'country': 'US', 'postal_code': '40207', } address_form = AddressForm(address) self.assertTrue(address_form.is_valid()) self.profile_form.instance.address = address_form.get_or_create() self.profile_form.instance.user = self.user self.profile_form.save() self.assertEqual(TcsUserProfile.objects.count(), 1) # Should have incremented since setup self.assertEqual(Address.objects.count(), 1) # Should not have incremented since setup
def address(request): form_class = AddressForm() context = {'form':form_class} print request.method if request.method == 'POST': form = AddressForm(request.POST) #print dir(form),form.is_valid(),type(form) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] age = form.cleaned_data['age'] # form validation # TOMMORROW: we want to validate our code to work with mail which are edu.com # we also want the candidate to be above 18years and below 50 years. # then only we want to make a entry into the database. Address.objects.create(name=name,age=age,email=email) # Making an entry into the database. return HttpResponseRedirect('/thanks/') else: print request.method,form context = {'form':form} return render(request,'address_forms.html',context) return render(request, 'address_forms.html', context)
class AddressFormTests(TestCase): """Tests for AddressForm.""" def setUp(self): self.data = { 'street': ' 217 tyNe road ', 'city': ' louisVILLE ', 'state': 'ky', 'country': 'US', # Field validation will not fix lowercase input 'postal_code': ' 40207 ', } self.address_form = AddressForm(self.data) self.assertTrue(self.address_form.is_valid()) def testCountryInterlock(self): """ For countries for which local flavor data structures is available, ensure the state and postal code meet the given country's format. """ # Invalid state for the United States self.data['state'] = 'zz' self.assertFalse(AddressForm(self.data).is_valid()) # Invalid postal code for the United States self.data['state'] = 'KY' self.data['postal_code'] = '40-222-405' self.assertFalse(AddressForm(self.data).is_valid()) # Any state and postal code input that meets the basic CharField restrictions should work # for countries without local flavor. self.data[ 'country'] = 'CA' # TODO - localflavor is available for Canada self.data['state'] = 'zz' self.assertTrue(AddressForm(self.data).is_valid()) def testBasicNormalizations(self): """Test for expected cleaning of fields.""" self.assertEqual(self.address_form.cleaned_data['city'], 'Louisville') self.assertEqual(self.address_form.cleaned_data['state'], 'KY') self.assertEqual(self.address_form.cleaned_data['postal_code'], '40207') def testStreetSubstitutions(self): """ Verify the normalizing functionality of AddressForm.clean_street(). """ self.assertEqual(self.address_form.cleaned_data['street'], '217 Tyne Rd')
def payment_page(req): cart, new_cart = Cart.objects.new_cart_or_get(req) if new_cart or cart.products.count() == 0: return redirect('carthome') order, new_order = Order.objects.get_or_create(cart=cart) user = req.user login_form = LoginForm() user_address, new_address = Address.objects.get_or_create(user=user) address_form = AddressForm(instance=user_address) context = { 'object' : order, 'cart' : cart, 'login_form' : login_form, 'address_form' : address_form } return render(req,'carts/paymentpage.html', context)
def tcsuserEdit(request): """Edit the logged-in user's profile.""" if request.method == 'POST': profile_form = TcsUserProfileForm(request.POST, instance=request.user.profile) address_form = AddressForm(request.POST, instance=request.user.profile.address) if profile_form.is_valid() and address_form.is_valid(): profile_form.instance.address = address_form.get_or_create() profile_form.save() messages.success(request, 'You updated your profile.') return HttpResponseRedirect(reverse('tcsuser_edit')) else: profile_form = TcsUserProfileForm(instance=request.user.profile) address_form = AddressForm(instance=request.user.profile.address) return render(request, 'tcsuser/edit.html', { 'profile_form': profile_form, 'address_form': address_form })
def checkout(request): cart_obj, cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.combo_item.count() == 0: return redirect('carts:cart') address_form = AddressForm() dpointform = SelectDeliveryPointForm() delivery_point = request.session.get("delivery_point_id", None) billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id", None) billing_profile, billing_profile_created = BillingProfile.objects.new_or_get( request) print(billing_profile) dpoint_qs = None address_qs = None if billing_profile is not None: if request.user.is_authenticated: dpoint_qs = DeliveryPoint.objects.all() address_qs = Address.objects.filter( billing_profile=billing_profile) order_obj, order_obj_created = Order.objects.new_or_get( cart_obj, billing_profile) if shipping_address_id: order_obj.shipping_address = Address.objects.get( id=shipping_address_id) del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address = Address.objects.get( id=billing_address_id) del request.session["billing_address_id"] if delivery_point: order_obj.user = request.user order_obj.delivery_point = DeliveryPoint.objects.get( id=delivery_point) # del request.session['delivery_point_id'] order_obj.save() elif billing_address_id or shipping_address_id: order_obj.user = request.user order_obj.save() if order_obj.delivery_point is not None: if request.method == "POST": is_done = order_obj.check_done() if is_done: order_obj.mark_cod() cart_obj.ordered = True c = cart_obj.combo_item.all() c.update(ordered=True) a = cart_obj.addon_item.all() a.update(ordered=True) for ci in c: ci.save() for ai in a: ai.save() cart_obj.save() del request.session['cart_id'] return redirect("carts:success") del request.session['delivery_point_id'] else: if request.method == "POST": is_done = order_obj.check_d() if is_done: order_obj.mark_cod() cart_obj.ordered = True c = cart_obj.combo_item.all() c.update(ordered=True) a = cart_obj.addon_item.all() a.update(ordered=True) for ci in c: ci.save() for ai in a: ai.save() cart_obj.save() del request.session['cart_id'] return redirect("carts:success") # if request.method == "POST": # is_done = order_obj.check_done() # if is_done: # order_obj.mark_cod() # cart_obj.ordered=True # c = cart_obj.combo_item.all() # c.update(ordered=True) # a = cart_obj.addon_item.all() # a.update(ordered=True) # for ci in c: # ci.save() # for ai in a: # ai.save() # cart_obj.save() # del request.session['cart_id'] # return redirect("carts:success") context = { 'object': order_obj, 'billing_profile': billing_profile, 'dpointform': dpointform, 'dpointqs': dpoint_qs, 'address_form': address_form, 'address_qs': address_qs, } return render(request, 'carts/checkout.html', context)
def checkout_home(request): cart_obj, new_obj = models.Cart.objects.new_or_get(request) order_obj = None if new_obj or cart_obj.products.count() == 0: return redirect('cart:home') # user=request.user # billing_profile=None login_form = LoginForm() guest_form = GuestForm() address_form = AddressForm() billing_address_form = AddressForm() billing_address_id = request.session.get('billing_address_id') shipping_address_id = request.session.get('shipping_address_id') # guest_email_id=request.session.get('guest_email_id') # if user.is_authenticated: # #logged in user remember payment # billing_profile,billing_profile_created= BillingProfile.objects.get_or_create(user=user,email=user.email) # # elif guest_email_id is not None: # #guest dont remember # guest_email_obj=GuestEmail.objects.get(id=guest_email_id) # billing_profile, billing_guest_profile_created = BillingProfile.objects.get_or_create(email=guest_email_obj.email) # else: # pass billing_profile, billing_guest_profile_created = BillingProfile.objects.new_or_get( request) has_card = None if billing_profile is not None: order_obj, order_obj_created = Order.objects.new_or_get( billing_profile, cart_obj) if shipping_address_id: order_obj.shipping_address = Address.objects.get( id=shipping_address_id) del request.session['shipping_address_id'] if billing_address_id: order_obj.billing_address = Address.objects.get( id=billing_address_id) del request.session['billing_address_id'] if billing_address_id or shipping_address_id: order_obj.save() has_card = billing_profile.has_card if request.method == 'POST': 'check whether order is done' is_prepared = order_obj.check_done() if is_prepared: did_charge, chrg_msg = billing_profile.charge(order_obj) if did_charge: order_obj.mark_paid() request.session['cart_count'] = 0 del request.session['cart_id'] if not billing_profile.user: billing_profile.set_cards_inactive() return redirect('cart:success') else: return redirect('cart:success') # if order_qs.count() == 1 and order_qs is not None: # order_obj=order_qs.first # else: # # old_order_qs = Order.objects.filter(cart=cart_obj,active=True).exclude(billing_profile=billing_profile) # # print(old_order_qs) # # if old_order_qs.exists(): # # old_order_qs.update(active=False) # order_obj = Order.objects.create(billing_profile=billing_profile,cart=cart_obj) # moved to model manager context = { 'object': order_obj, 'billing_profile': billing_profile, 'login_form': login_form, 'guest_form': guest_form, 'address_form': address_form, 'billing_address_form': billing_address_form, "has_card": has_card } return render(request, 'cart/checkout.html', context)
def checkout_home(request): cart_obj, new_obj = Cart.objects.new_or_get( request) #we are getting the current session cart order_obj = None #get_or_create is build in function if new_obj or cart_obj.products.count() == 0: return redirect( 'carthome' ) #if the cart is just now created in the above line then go to carthome(Cart is empty) user = request.user login_form = LoginForm() guest_form = GuestForm() address_form = AddressForm() billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id", None) billing_profile = None guest_email_id = request.session.get('guest_email') if user.is_authenticated: billing_profile, billing_profile_created = Billingprofile.objects.get_or_create( user=user, email=user.email) elif guest_email_id is not None: guest_obj = GuestEmail.objects.get(id=guest_email_id) billing_profile, billing_guest_profile_created = Billingprofile.objects.get_or_create( email=guest_obj.email) else: pass address_qs = None #so basically the billingprofile is created for the user above but if he logs back again then we shouldnt keep on create an order we should retrieve it and produce it if billing_profile is not None: if request.user.is_authenticated: #order_qs=Order.objects.filter(billing_profile=billing_profile,cart=cart_obj,active=True) #if order_qs.count()==1:this entire thing moved to the oredermanager # order_obj=order_qs.first() #else: address_qs = Address.objects.filter( billing_profile=billing_profile) order_obj, order_obj_created = Order.objects.new_or_get( billing_profile, cart_obj) if shipping_address_id: order_obj.shipping_address = Address.objects.get( id=shipping_address_id) order_obj.save() del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address = Address.objects.get( id=billing_address_id) order_obj.save() del request.session["billing_address_id"] #we are gonna update the oder as we are completed the checkout process #so we deletet the cart_id #and redirect it to the success #these 3 we are gonna perform if request.method == "POST": #checking for that order to be done #del request.session['cart_id'] done = order_obj.check_done() if done: order_obj.mark_paid() del request.session['cart_id'] request.session['cart_items'] = 0 return redirect("success") context = { "object": order_obj, "billingprofile": billing_profile, "login": login_form, "guest_form": guest_form, "address_qs": address_qs, #"billing_address_form":billing_address_form, "address_form": address_form #This is for the shipping above is for the billing address } return render(request, "carts/checkout.html", context)
def checkout_home(request): template_name = 'carts/checkout.html' cart_obj, cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect('cart') login_form = UserLoginForm(request=request) guest_form = GuestForm(request=request) address_form = AddressForm() billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id", None) billing_profile, billing_profile_created = BillingProfile.objects.new_or_get( request) address_qs = None has_card = False if billing_profile is not None: if request.user.is_authenticated: address_qs = Address.objects.filter( billing_profile=billing_profile) order_obj, order_obj_created = Order.objects.new_or_get( billing_profile, cart_obj) if shipping_address_id: order_obj.shipping_address = Address.objects.get( id=shipping_address_id) del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address = Address.objects.get( id=billing_address_id) del request.session["billing_address_id"] if shipping_address_id or billing_address_id: order_obj.save() has_card = billing_profile.has_card if request.method == "POST": "check order is done or not?" is_prepared = order_obj.check_done() if is_prepared: billing_profile.charge(order_obj) order_obj.mark_paid() request.session["cart_items"] = 0 del request.session['cart_id'] if not billing_profile.user: ''' code ''' billing_profile.set_cards_inactive() return redirect('success') else: return redirect('checkout') context = { 'object': order_obj, "billing_profile": billing_profile, "login_form": login_form, "guest_form": guest_form, "address_form": address_form, "address_qs": address_qs, "has_card": has_card, "publish_key": STRIPE_PUB_KEY, } return render(request, template_name, context)
def processVoterList(sender, created, instance, **kwargs): """ For each valid voter in the uploaded list, add it to the Voter table, and make a many-to-many link to the campaign that uploaded the list. Do not duplicate voters already in the table. Consider a voter a duplicate if a voter already exists with the same registrar_id in the same state. """ if not created: return try: f = open(instance.file_name.url) except IOError: instance.processed = 'Could not open the file.' instance.is_active = False instance.save() return default_country = str(instance.campaign.address.country) # The relevant campaign's home country line_count = 0 num_successes = 0 num_duplicates = 0 num_bad_format = 0 new_voter_relations = [] # A list of new CampaignsToVoters instances to add in bulk after processing the list new_indexes = set([]) # Explained below reader = DictReader(f, delimiter='\t') # Assumes the first row contains column names. for voter in reader: line_count += 1 # Must catch KeyError and ValueError. try: # Convert date strings to datetime.Date instances. Failure to convert raises ValueError. if voter['registration_date']: voter['registration_date'] = parse(voter['registration_date']).date() if voter['dob']: voter['dob'] = parse(voter['dob']).date() # Voter political affiliations are a ForeignKey in the Voter model, but the user uploads # text. Attempt to find the correct political party operating in the campaign's country. affiliation = voter['affiliation'].strip() if affiliation != '': try: affiliation = PoliticalParty.objects.get( country=default_country, title__icontains=affiliation ).pk except (PoliticalParty.DoesNotExist, PoliticalParty.MultipleObjectsReturned): affiliation = None # Ignore the ambiguous party information. voter_form = VoterForm({ 'first_name': voter['first_name'], 'last_name': voter['last_name'], 'dob': voter['dob'], 'gender': voter['gender'], 'affiliation': affiliation, # This should be an integer primary key or None. 'registration_date': voter['registration_date'], 'registrar_id': voter['registrar_id'], 'dump_date': instance.dump_date, 'phone_number1': voter['phone_number1'], 'phone_number2': voter['phone_number2'], 'email': voter['email'], }) # Use the default country if necessary. if voter['country'] == '': voter['country'] = default_country address_form = AddressForm({ 'street': voter['street'], 'city': voter['city'], 'state': voter['state'], 'country': voter['country'], 'postal_code': voter['postal_code'], }) except (KeyError, ValueError): num_bad_format += 1 # Missing required data continue # Move on to the next line in the input file. if voter_form.is_valid() and address_form.is_valid(): # Is this voter already in the database? Look for active voters with the same registrar_id, # street address, country, and state. # TODO - Registrar IDs are stored as-is and matched case-insensitively. # Should I just lower/upper-case and match exact? Should case matter? v = Voter.objects.filter(is_active=True, registrar_id__iexact=voter_form.cleaned_data['registrar_id'], address__street=address_form.cleaned_data['street'], address__country=address_form.cleaned_data['country'], address__state=address_form.cleaned_data['state']).first() if not v: # The voter is not in the database or is not active. Add him or her. voter_form.instance.address = address_form.get_or_create() v = voter_form.save() # Relate the voter to the campaign that uploaded the current list, if applicable. # Two scenarios can raise an IntegrityError by duplicating a (campaign, voter) # combination in the database table Campaign.campaignstovoters: # 1) Duplicate voters are present in the new list. # This raises an error when creating the m2m relations after creating each new # voter. Mitigate this by keeping track of voter indexes seen in the new list. # 2) The same campaign has already submitted a voter in another list. # Having multiple m2m relations associated with different lists is desirable, # but the framework does not support this. Simply ignore voters already present # from another list. if v.pk not in new_indexes and not CampaignsToVoters.objects.filter( campaign=instance.campaign, voter=v).exists(): new_indexes.add(v.pk) new_voter_relations.append(CampaignsToVoters(campaign=instance.campaign, voter=v, voter_list=instance)) num_successes += 1 else: num_duplicates += 1 else: num_bad_format += 1 # No required data missing, but the provided data is invalid. f.close() # Update the many-to-many relationship. CampaignsToVoters.objects.bulk_create(new_voter_relations) # Update the VoterList instance. instance.processed = 'Imported {0} of {1} voters. {2} duplicates. {3} bad format.'.format( num_successes, line_count, num_duplicates, num_bad_format) instance.is_active = (num_successes > 0) instance.save()
def checkout_home(request): ##this is where you see the ordering cart_obj, cart_created = Cart.objects.new_or_get(request) if cart_created or cart_obj.products.count() == 0: return redirect('carts:cart_home') user = request.user # billing_profile=None # guest_email_id=request.session.get('guest_email_id') # if user.is_authenticated: # #logged in user checkot # billing_profile,billing_profile_created=BillingProfile.objects.get_or_create(user=user,email=user.email) # elif guest_email_id is not None: # #guest user checkout # guest_email_obj=GuestEmail.objects.get(id=guest_email_id) # billing_profile,billing_guest_profile_created=BillingProfile.objects.get_or_create(email=guest_email_obj.email) billing_address_id = request.session.get('billing_address_id', None) shipping_address_id = request.session.get('shipping_address_id', None) billing_profile, billing_profile_created = BillingProfile.objects.get_or_new( request) order_obj = None if billing_profile is not None: if request.user.is_authenticated: address_qs = Address.objects.filter( billing_profile=billing_profile) # order_qs=Order.objects.filter(cart=cart_obj,billing_profile=billing_profile,active=True) # if order_qs.exists() and order_qs.count()==1: # order_obj=order_qs.first() # else: #old_order_qs=Order.objects.exclude(billing_profile=billing_profile).filter(cart=cart_obj,active=True) #if old_order_qs.exists(): # old_order_qs.update(active=False) order_obj, order_obj_created = Order.objects.get_or_new( cart_obj=cart_obj, billing_profile=billing_profile) if shipping_address_id: order_obj.shipping_address = Address.objects.get( id=shipping_address_id) del request.session['shipping_address_id'] if billing_address_id: order_obj.billing_address = Address.objects.get( id=billing_address_id) del request.session['billing_address_id'] if billing_address_id or shipping_address_id: order_obj.save() if request.method == 'POST': #check the order is done is_done = order_obj.check_done() if is_done: order_obj.mark_paid() del request.session['cart_id'] return redirect('/cart/success/') context = { 'object': order_obj, 'billing_profile': billing_profile, 'login_form': LoginForm(), 'guest_login_form': GuestLoginForm(), 'shipping_address_form': AddressForm(), 'billing_address_form': AddressForm(), 'address_qs': address_qs } return render(request, 'carts/checkout.html', context)
def CheckoutView(request): cart_obj, cart_created = Cart.objects.new_or_get(request) product_ = cart_obj.products.all() order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect('cart') login_form = SignInForm() guest_form = GuestForm() form = AddressForm(request.POST or None) billing_form = AddressForm() guest_email_id = request.session.get('guest_email_id') billing_profile, billing_profile_created = BillingProfile.objects.new_or_get( request) 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 = address_type instance.save() request.session[address_type + "_address_id"] = instance.id print(address_type + "_address_id") return redirect('ConformO') else: return redirect("cart") else: print('this shit aint valid') shipping_address_id = request.session.get("shipping_address_id", None) address_qs = None if billing_profile is not None: if request.user.is_authenticated: address_qs = Address.objects.filter( billing_profile=billing_profile) order_qs = Order.objects.filter(billing_profile=billing_profile, cart=cart_obj, active=True) if order_qs.count() == 1: order_obj = order_qs.first() else: old_order_qs = Order.objects.exclude( billing_profile=billing_profile).filter(cart=cart_obj, active=True) if old_order_qs.exists(): old_order_qs.update(active=False) order_obj = Order.objects.create(billing_profile=billing_profile, cart=cart_obj) if shipping_address_id: order_obj.shipping_address = Address.objects.get( id=shipping_address_id) del request.session["shipping_address_id"] order_obj.save() context = { 'order': order_obj, 'object': product_, 'billing_profile': billing_profile, 'login_form': login_form, 'guest_form': guest_form, "form": form, 'billing_form': billing_form, 'address_qs': address_qs } return render(request, 'cart/checkout.html', context)
def cart_checkout(request): cart_obj, cart_created = Cart.objects.new_or_get(request) next_url = request.build_absolute_uri order_obj = None if cart_created or cart_obj.products.count()==0: return redirect("cart:home") login_form = LoginForm() guest_form = GuestForm() billing_address_form = AddressForm() shipping_address_id = request.session.get('shipping_address_id',None) billing_address_id = request.session.get('billing_address_id',None) # billing profile is creates or not is checked up in billing profile model manager billing_profile,billing_profile_created = BillingProfile.objects.new_or_get(request) address_qs = None # for card payemnt has_card = False if billing_profile is not None: if 'username' in request.session or 'guest_email_id' in request.session: address_qs = Address.objects.filter(billing_profile=billing_profile) order_obj,order_obj_created = Order.objects.new_or_get(billing_profile,cart_obj) if shipping_address_id : print("you are here shippping address") order_obj.shipping_address = Address.objects.get(id = shipping_address_id) del request.session['shipping_address_id'] if billing_address_id : print("you are here billing address") order_obj.billing_address = Address.objects.get(id=billing_address_id) del request.session['billing_address_id'] if billing_address_id or shipping_address_id: order_obj.save() #print((order_obj)) has_card = billing_profile.has_card() """if request.method =="POST": is_done = order_obj.check_done() # calling manager method if is_done: order_obj.mark_paid() # calling manager methods request.session['cart_items']=0 del request.session['cart_id'] return redirect("cart:success")""" if request.method=="POST": is_ready = order_obj.check_done() if is_ready: did_charge, crg_msg = billing_profile.charge(order_obj) if did_charge: order_obj.mark_paid() # sort a signal for us request.session['cart_items'] = 0 del request.session['cart_id'] if not billing_profile.user: ''' is this the best spot? ''' billing_profile.set_cards_inactive() return redirect("cart:success") else: print(crg_msg) return redirect("cart:checkout") context = {"title": 'checkout', "object": order_obj, "form":login_form, "guest_form":guest_form, 'billing_profile':billing_profile, "next_url":next_url, 'billing_address_form':billing_address_form, 'address_type':'shipping', 'address_qs':address_qs, 'has_card':has_card, 'cart':cart_obj, } return render(request,'cart/checkout.html',context)
def checkout_home(request): template_name = "cart/checkout.html" order_obj = None cart_obj, cart_created = Cart.objects.create_or_get(request) all_category = ProductCategory.objects.all() if cart_created or cart_obj.product.count() == 0: return redirect("cart:cart-home") login_form = LoginForm(request.POST or None) guest_form = GuestForm(request.POST or None) address_form = AddressForm(request.POST or None) billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id", None) billingprofile, billingprofile_created = BillingProfile.objects.new_or_get( request) address_qs = None if billingprofile is not None: if request.user.is_authenticated: address_qs = Addresses.objects.filter( billing_profile=billingprofile) order_obj, order_obj_created = Orders.objects.new_or_get( billingprofile, cart_obj) if shipping_address_id: order_obj.shipping_address = Addresses.objects.get( id=shipping_address_id) del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address_id = Addresses.objects.get( id=billing_address_id) del request.session["billing_address_id"] if billing_address_id or shipping_address_id: order_obj.save() if request.method == "POST": is_done = order_obj.check_done() if is_done: did_charge, mgs = billingprofile.charge(order_obj) if did_charge: order_obj.mark_paid() request.session["cart_total"] = 0 del request.session["cart_id"] if not billingprofile.user: billingprofile.set_card_inactive() return redirect("cart:checkout-success") else: return redirect("cart:checkout") context = { "order_obj": order_obj, "billingprofile": billingprofile, "login_form": login_form, "guest_form": guest_form, "address_form": address_form, "address_qs": address_qs, "all_category": all_category } return render(request, template_name, context)
def checkout_home(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('cart:home') login_form = LoginForm() guest_form = GuestForm() address_form = AddressForm() billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id", None) if not request.user.is_authenticated: billing_profile = None billing_profile, billing_profile_created = BillingProfile.objects.new_or_get( request) has_card = False address_qs = None if billing_profile is not None: if request.user.is_authenticated: address_qs = Address.objects.filter( billing_profile=billing_profile) order_obj, order_obj_created = Order.objects.new_or_get( billing_profile, cart_obj) if shipping_address_id: order_obj.shipping_address = Address.objects.get( id=shipping_address_id) del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address = Address.objects.get( id=billing_address_id) del request.session["billing_address_id"] if billing_address_id or shipping_address_id: order_obj.save() has_card = billing_profile.has_card if request.method == "POST": "check the cart process done" is_prepared = order_obj.check_done() if is_prepared: did_chared, crg_msg = billing_profile.charge(order_obj) if did_chared: order_obj.mark_paid() request.session['total_product'] = 0 del request.session['cart_id'] if not billing_profile.user: billing_profile.set_card_inactive() return redirect("cart:success") else: print(crg_msg) return redirect("cart:checkout") context = { 'object': order_obj, 'billing_profile': billing_profile, 'login_form': login_form, 'guest_form': guest_form, 'address_form': address_form, 'address_qs': address_qs, "has_card": has_card, "publish_key": STRIPE_PUB_KEY } return render(request, 'carts/checkout.html', context)