def __init__(self, product, user=None, *args, **kwargs): super(ProductReviewForm, self).__init__(*args, **kwargs) self.instance.product = product if user and user_is_authenticated(user): self.instance.user = user del self.fields['name'] del self.fields['email']
def get_message_context(self, order): ctx = { 'user': self.request.user, 'order': order, 'site': get_current_site(self.request), 'lines': order.lines.all(), 'domain': getattr(settings, 'DOMAIN') } if not user_is_authenticated(self.request.user): # Attempt to add the anon order status URL to the email template # ctx. try: path = reverse('customer:anon-order', kwargs={ 'order_number': order.number, 'hash': order.verification_hash() }) except NoReverseMatch: # We don't care that much if we can't resolve the URL pass else: domain = getattr(settings, 'DOMAIN') if path: ##Remove first slash path = path[1:] ctx['status_url'] = '%s%s' % (domain, path) return ctx
def check_user_email_is_captured(self, request): if not user_is_authenticated(request.user) \ and not self.checkout_session.get_guest_email(): raise exceptions.FailedPreCondition( url=reverse('checkout:index'), message=_("Please either sign in or enter your email address"))
def create_order_model(self, user, basket, shipping_address, shipping_method, shipping_charge, billing_address, total, order_number, status, request=None, **extra_order_fields): """Create an order model.""" order_data = {'basket': basket, 'number': order_number, 'currency': total.currency, 'total_incl_tax': total.incl_tax, 'total_excl_tax': total.excl_tax, 'shipping_incl_tax': shipping_charge.incl_tax, 'shipping_excl_tax': shipping_charge.excl_tax, 'shipping_method': shipping_method.name, 'shipping_code': shipping_method.code} if shipping_address: order_data['shipping_address'] = shipping_address if billing_address: order_data['billing_address'] = billing_address if user and user_is_authenticated(user): order_data['user_id'] = user.id if status: order_data['status'] = status if extra_order_fields: order_data.update(extra_order_fields) if 'site' not in order_data: order_data['site'] = Site._default_manager.get_current(request) order = Order(**order_data) order.save() return order
def notifications(request): ctx = {} if getattr(request, 'user', None) and user_is_authenticated(request.user): num_unread = Notification.objects.filter(recipient=request.user, date_read=None).count() ctx['num_unread_notifications'] = num_unread return ctx
def process_response(self, request, response): # Delete any surplus cookies cookies_to_delete = getattr(request, 'cookies_to_delete', []) for cookie_key in cookies_to_delete: response.delete_cookie(cookie_key) if not hasattr(request, 'basket'): return response # If the basket was never initialized we can safely return if (isinstance(request.basket, SimpleLazyObject) and request.basket._wrapped is empty): return response cookie_key = self.get_cookie_key(request) # Check if we need to set a cookie. If the cookies is already available # but is set in the cookies_to_delete list then we need to re-set it. has_basket_cookie = ( cookie_key in request.COOKIES and cookie_key not in cookies_to_delete) # If a basket has had products added to it, but the user is anonymous # then we need to assign it to a cookie if (request.basket.id and not user_is_authenticated(request.user) and not has_basket_cookie): cookie = self.get_basket_hash(request.basket.id) response.set_cookie( cookie_key, cookie, max_age=settings.OSCAR_BASKET_COOKIE_LIFETIME, secure=settings.OSCAR_BASKET_COOKIE_SECURE, httponly=True) return response
def __init__(self, product, user=None, *args, **kwargs): super(ProductReviewForm, self).__init__(*args, **kwargs) self.instance.product = product if user and user_is_authenticated(user): self.instance.user = user del self.fields['name'] del self.fields['email']
def clean(self): cleaned_data = self.cleaned_data email = cleaned_data.get('email') if email: try: ProductAlert.objects.get( product=self.product, email__iexact=email, status=ProductAlert.ACTIVE) except ProductAlert.DoesNotExist: pass else: raise forms.ValidationError(_( "There is already an active stock alert for %s") % email) # Check that the email address hasn't got other unconfirmed alerts. # If they do then we don't want to spam them with more until they # have confirmed or cancelled the existing alert. if ProductAlert.objects.filter(email__iexact=email, status=ProductAlert.UNCONFIRMED).count(): raise forms.ValidationError(_( "%s has been sent a confirmation email for another product " "alert on this site. Please confirm or cancel that request " "before signing up for more alerts.") % email) elif user_is_authenticated(self.user): try: ProductAlert.objects.get(product=self.product, user=self.user, status=ProductAlert.ACTIVE) except ProductAlert.DoesNotExist: pass else: raise forms.ValidationError(_( "You already have an active alert for this product")) return cleaned_data
def is_available_to_user(self, user=None): """ Test whether this voucher is available to the passed user. Returns a tuple of a boolean for whether it is successful, and a availability message. """ is_available, message = False, '' if self.usage == self.SINGLE_USE: is_available = not self.applications.exists() if not is_available: message = _("This voucher has already been used") elif self.usage == self.MULTI_USE: is_available = True elif self.usage == self.ONCE_PER_CUSTOMER: if not user_is_authenticated(user): is_available = False message = _( "This voucher is only available to signed in users") else: is_available = not self.applications.filter( voucher=self, user=user).exists() if not is_available: message = _("You have already used this voucher in " "a previous order") return is_available, message
def receive_basket_addition(sender, product, user, **kwargs): if kwargs.get('raw', False): return _update_counter( ProductRecord, 'num_basket_additions', {'product': product}) if user and user_is_authenticated(user): _update_counter(UserRecord, 'num_basket_additions', {'user': user})
def is_available_to_user(self, user=None): """ Test whether this voucher is available to the passed user. Returns a tuple of a boolean for whether it is successful, and a availability message. """ is_available, message = False, '' if self.usage == self.SINGLE_USE: is_available = not self.applications.exists() if not is_available: message = _("This voucher has already been used") elif self.usage == self.MULTI_USE: is_available = True elif self.usage == self.ONCE_PER_CUSTOMER: if not user_is_authenticated(user): is_available = False message = _( "This voucher is only available to signed in users") else: is_available = not self.applications.filter( voucher=self, user=user).exists() if not is_available: message = _("You have already used this voucher in " "a previous order") return is_available, message
def __init__(self, company, user=None, *args, **kwargs): super(VendorReviewForm, self).__init__(*args, **kwargs) self.instance.company = company if user and user_is_authenticated(user): self.instance.user = user del self.fields['name'] del self.fields['email']
def receive_product_view(sender, product, user, **kwargs): if kwargs.get('raw', False): return _update_counter(ProductRecord, 'num_views', {'product': product}) if user and user_is_authenticated(user): _update_counter(UserRecord, 'num_product_views', {'user': user}) UserProductView.objects.create(product=product, user=user)
def process_response(self, request, response): # Delete any surplus cookies cookies_to_delete = getattr(request, 'cookies_to_delete', []) for cookie_key in cookies_to_delete: response.delete_cookie(cookie_key) if not hasattr(request, 'basket'): return response # If the basket was never initialized we can safely return if (isinstance(request.basket, SimpleLazyObject) and request.basket._wrapped is empty): return response cookie_key = self.get_cookie_key(request) # Check if we need to set a cookie. If the cookies is already available # but is set in the cookies_to_delete list then we need to re-set it. has_basket_cookie = (cookie_key in request.COOKIES and cookie_key not in cookies_to_delete) # If a basket has had products added to it, but the user is anonymous # then we need to assign it to a cookie if (request.basket.id and not user_is_authenticated(request.user) and not has_basket_cookie): cookie = self.get_basket_hash(request.basket.id) response.set_cookie(cookie_key, cookie, max_age=settings.OSCAR_BASKET_COOKIE_LIFETIME, secure=settings.OSCAR_BASKET_COOKIE_SECURE, httponly=True) return response
def receive_product_view(sender, product, user, **kwargs): if kwargs.get('raw', False): return _update_counter(ProductRecord, 'num_views', {'product': product}) if user and user_is_authenticated(user): _update_counter(UserRecord, 'num_product_views', {'user': user}) UserProductView.objects.create(product=product, user=user)
def receive_basket_addition(sender, product, user, **kwargs): if kwargs.get('raw', False): return _update_counter(ProductRecord, 'num_basket_additions', {'product': product}) if user and user_is_authenticated(user): _update_counter(UserRecord, 'num_basket_additions', {'user': user})
def create_order_model(self, user, basket, shipping_address, shipping_method, shipping_charge, billing_address, total, order_number, status, **extra_order_fields): """ Create an order model. """ order_data = { 'basket': basket, 'number': order_number, 'currency': total.currency, 'total_incl_tax': total.incl_tax, 'total_excl_tax': total.excl_tax, 'shipping_incl_tax': shipping_charge.incl_tax, 'shipping_excl_tax': shipping_charge.excl_tax, 'shipping_method': shipping_method.name, 'shipping_code': shipping_method.code } if shipping_address: order_data['shipping_address'] = shipping_address if billing_address: order_data['billing_address'] = billing_address if user and user_is_authenticated(user): order_data['user_id'] = user.id if status: order_data['status'] = status if extra_order_fields: order_data.update(extra_order_fields) if 'site' not in order_data: order_data['site'] = Site._default_manager.get_current() order = Order(**order_data) order.save() return order
def clean(self): cleaned_data = self.cleaned_data email = cleaned_data.get('email') if email: try: ProductAlert.objects.get( product=self.product, email__iexact=email, status=ProductAlert.ACTIVE) except ProductAlert.DoesNotExist: pass else: raise forms.ValidationError(_( "There is already an active stock alert for %s") % email) # Check that the email address hasn't got other unconfirmed alerts. # If they do then we don't want to spam them with more until they # have confirmed or cancelled the existing alert. if ProductAlert.objects.filter(email__iexact=email, status=ProductAlert.UNCONFIRMED).count(): raise forms.ValidationError(_( "%s has been sent a confirmation email for another product " "alert on this site. Please confirm or cancel that request " "before signing up for more alerts.") % email) elif user_is_authenticated(self.user): try: ProductAlert.objects.get(product=self.product, user=self.user, status=ProductAlert.ACTIVE) except ProductAlert.DoesNotExist: pass else: raise forms.ValidationError(_( "You already have an active alert for this product")) return cleaned_data
def build_submission(self, **kwargs): """ Return a dict of data that contains everything required for an order submission. This includes payment details (if any). This can be the right place to perform tax lookups and apply them to the basket. """ # Pop the basket if there is one, because we pass it as a positional # argument to methods below basket = kwargs.pop('basket', self.request.basket) shipping_address = self.get_shipping_address(basket) shipping_method = self.get_shipping_method(basket, shipping_address) billing_address = self.get_billing_address(shipping_address) if not shipping_method: total = shipping_charge = None else: shipping_charge = shipping_method.calculate(basket) total = self.get_order_totals(basket, shipping_charge=shipping_charge, **kwargs) submission = { 'user': self.request.user, 'basket': basket, 'shipping_address': shipping_address, 'shipping_method': shipping_method, 'shipping_charge': shipping_charge, 'billing_address': billing_address, 'order_total': total, 'order_kwargs': {}, 'payment_kwargs': {} } # If there is a billing address, add it to the payment kwargs as calls # to payment gateways generally require the billing address. Note, that # it normally makes sense to pass the form instance that captures the # billing address information. That way, if payment fails, you can # render bound forms in the template to make re-submission easier. if billing_address: submission['payment_kwargs']['billing_address'] = billing_address # Allow overrides to be passed in submission.update(kwargs) # Set guest email after overrides as we need to update the order_kwargs # entry. if (not user_is_authenticated(submission['user']) and 'guest_email' not in submission['order_kwargs']): email = self.checkout_session.get_guest_email() submission['order_kwargs']['guest_email'] = email # Calculate Tax if submission['shipping_address'] and submission['shipping_method']: tax.apply_to(submission) # Recalculate order total to ensure we have a tax-inclusive total submission['order_total'] = self.get_order_totals( submission['basket'], submission['shipping_charge']) return submission
def save(self, commit=True): alert = super(ProductAlertForm, self).save(commit=False) if user_is_authenticated(self.user): alert.user = self.user alert.product = self.product if commit: alert.save() return alert
def save(self, commit=True): alert = super(ProductAlertForm, self).save(commit=False) if user_is_authenticated(self.user): alert.user = self.user alert.product = self.product if commit: alert.save() return alert
def check_user_email_is_captured(self, request): if not user_is_authenticated(request.user) \ and not self.checkout_session.get_guest_email(): raise exceptions.FailedPreCondition( url=reverse('checkout:index'), message=_( "Please either sign in or enter your email address") )
def can_user_vote(self, user): if not user_is_authenticated(user): return False, _(u"Only signed in users can vote") vote = self.votes.model(answer=self, user=user, delta=1) try: vote.full_clean() except ValidationError as e: return False, u"%s" % e return True, ""
def get_alert_status(self): # Check if this user already have an alert for this product has_alert = False if user_is_authenticated(self.request.user): alerts = ProductAlert.objects.filter(product=self.object, user=self.request.user, status=ProductAlert.ACTIVE) has_alert = alerts.exists() return has_alert
def __init__(self, user, product, *args, **kwargs): self.user = user self.product = product super(ProductAlertForm, self).__init__(*args, **kwargs) # Only show email field to unauthenticated users if user and user_is_authenticated(user): self.fields['email'].widget = forms.HiddenInput() self.fields['email'].required = False
def get(self, request, *args, **kwargs): # We redirect immediately to shipping address stage if the user is # signed in. if user_is_authenticated(request.user): # We raise a signal to indicate that the user has entered the # checkout process so analytics tools can track this event. signals.start_checkout.send_robust(sender=self, request=request) return self.get_success_response() return super(IndexView, self).get(request, *args, **kwargs)
def __init__(self, user, product, *args, **kwargs): self.user = user self.product = product super(ProductAlertForm, self).__init__(*args, **kwargs) # Only show email field to unauthenticated users if user and user_is_authenticated(user): self.fields['email'].widget = forms.HiddenInput() self.fields['email'].required = False
def get_alert_status(self): # Check if this user already have an alert for this product has_alert = False if user_is_authenticated(self.request.user): alerts = ProductAlert.objects.filter( product=self.object, user=self.request.user, status=ProductAlert.ACTIVE) has_alert = alerts.exists() return has_alert
def get(self, request, *args, **kwargs): # We redirect immediately to shipping address stage if the user is # signed in. if user_is_authenticated(request.user): # We raise a signal to indicate that the user has entered the # checkout process so analytics tools can track this event. signals.start_checkout.send_robust( sender=self, request=request) return self.get_success_response() return super(IndexView, self).get(request, *args, **kwargs)
def record_usage(self, order, user): """ Records a usage of this voucher in an order. """ if user_is_authenticated(user): self.applications.create(voucher=self, order=order, user=user) else: self.applications.create(voucher=self, order=order) self.num_orders += 1 self.save()
def record_usage(self, order, user): """ Records a usage of this voucher in an order. """ if user_is_authenticated(user): self.applications.create(voucher=self, order=order, user=user) else: self.applications.create(voucher=self, order=order) self.num_orders += 1 self.save()
def get_basket(self, request): """ Return the open basket for this request """ if request._basket_cache is not None: return request._basket_cache num_baskets_merged = 0 manager = Basket.open cookie_key = self.get_cookie_key(request) cookie_basket = self.get_cookie_basket(cookie_key, request, manager) if cookie_basket: basket = cookie_basket else: if hasattr(request, 'user') and user_is_authenticated( request.user): # Signed-in user: if they have a cookie basket too, it means # that they have just signed in and we need to merge their cookie # basket into their user basket, then delete the cookie. try: basket, __ = manager.get_or_create(owner=request.user) except Basket.MultipleObjectsReturned: # Not sure quite how we end up here with multiple baskets. # We merge them and create a fresh one old_baskets = list(manager.filter(owner=request.user)) basket = old_baskets[0] for other_basket in old_baskets[1:]: self.merge_baskets(basket, other_basket) num_baskets_merged += 1 # Assign user onto basket to prevent further SQL queries when # basket.owner is accessed. basket.owner = request.user #if cookie_basket: # self.merge_baskets(basket, cookie_basket) # num_baskets_merged += 1 # request.cookies_to_delete.append(cookie_key) else: # Anonymous user with no basket - instantiate a new basket # instance. No need to save yet. basket = Basket() # Cache basket instance for the during of this request request._basket_cache = basket if num_baskets_merged > 0: messages.add_message( request, messages.WARNING, _("We have merged a basket from a previous session. Its contents " "might have changed.")) return basket
def create_customer_email(self, user, messages, email): """ Create Email instance in database for logging purposes. """ # Is user is signed in, record the event for audit if email and user_is_authenticated(user): return Email._default_manager.create(user=user, email=user.email, subject=email.subject, body_text=email.body, body_html=messages['html'])
def get(self, request, *args, **kwargs): if not user_is_authenticated(request.user): return redirect(settings.LOGIN_REDIRECT_URL) try: self.object = self.get_object() except Http404: return redirect('/partner/partner-registration/') context = self.get_context_data(object=self.object) return self.render_to_response(context)
def create_billing_address(self, user, billing_address=None, shipping_address=None, **kwargs): """ Saves any relevant billing data (eg a billing address). """ if not billing_address: return None billing_address.save() if user_is_authenticated(user): self.update_address_book(user, billing_address) return billing_address
def create_billing_address(self, user, billing_address=None, shipping_address=None, **kwargs): """ Saves any relevant billing data (eg a billing address). """ if not billing_address: return None billing_address.save() if user_is_authenticated(user): self.update_address_book(user, billing_address) return billing_address
def create_customer_email(self, user, messages, email): """ Create Email instance in database for logging purposes. """ # Is user is signed in, record the event for audit if email and user_is_authenticated(user): return Email._default_manager.create(user=user, email=user.email, subject=email.subject, body_text=email.body, body_html=messages['html'])
def get_basket(self, request): """ Return the open basket for this request """ if request._basket_cache is not None: return request._basket_cache num_baskets_merged = 0 manager = Basket.open cookie_key = self.get_cookie_key(request) cookie_basket = self.get_cookie_basket(cookie_key, request, manager) if hasattr(request, 'user') and user_is_authenticated(request.user): # Signed-in user: if they have a cookie basket too, it means # that they have just signed in and we need to merge their cookie # basket into their user basket, then delete the cookie. try: basket, __ = manager.get_or_create(owner=request.user) except Basket.MultipleObjectsReturned: # Not sure quite how we end up here with multiple baskets. # We merge them and create a fresh one old_baskets = list(manager.filter(owner=request.user)) basket = old_baskets[0] for other_basket in old_baskets[1:]: self.merge_baskets(basket, other_basket) num_baskets_merged += 1 # Assign user onto basket to prevent further SQL queries when # basket.owner is accessed. basket.owner = request.user if cookie_basket: self.merge_baskets(basket, cookie_basket) num_baskets_merged += 1 request.cookies_to_delete.append(cookie_key) elif cookie_basket: # Anonymous user with a basket tied to the cookie basket = cookie_basket else: # Anonymous user with no basket - instantiate a new basket # instance. No need to save yet. basket = Basket() # Cache basket instance for the during of this request request._basket_cache = basket if num_baskets_merged > 0: messages.add_message(request, messages.WARNING, _("We have merged a basket from a previous session. Its contents " "might have changed.")) return basket
def get(self, request, *args, **kwargs): if 'key' in kwargs: self.alert = get_object_or_404(ProductAlert, key=kwargs['key']) elif 'pk' in kwargs and user_is_authenticated(request.user): self.alert = get_object_or_404(ProductAlert, user=self.request.user, pk=kwargs['pk']) else: raise Http404 self.update_alert() return super(ProductAlertCancelView, self).get(request, *args, **kwargs)
def post(self, request, *args, **kwargs): if user_is_authenticated(self.request.user) and \ 'address_id' in self.request.POST: address = UserAddress._default_manager.get( pk=self.request.POST['address_id'], user=self.request.user) action = self.request.POST.get('action', None) if action == 'set_to_billing': self.checkout_session.bill_to_user_address(address=address) return redirect(self.get_success_url()) else: return http.HttpResponseBadRequest() else: return super(PaymentMethodView, self).post(request, *args, **kwargs)
def can_user_vote(self, user): """ Test whether the passed user is allowed to vote on this review """ if not user_is_authenticated(user): return False, _(u"Only signed in users can vote") vote = self.votes.model(review=self, user=user, delta=1) try: vote.full_clean() except ValidationError as e: return False, u"%s" % e return True, ""
def can_user_vote(self, user): """ Test whether the passed user is allowed to vote on this review """ if not user_is_authenticated(user): return False, _(u"Only signed in users can vote") vote = self.votes.model(review=self, user=user, delta=1) try: vote.full_clean() except ValidationError as e: return False, u"%s" % e return True, ""
def is_review_permitted(self, user): """ Determines whether a user may add a review on this product. Default implementation respects OSCAR_ALLOW_ANON_REVIEWS and only allows leaving one review per user and product. Override this if you want to alter the default behaviour; e.g. enforce that a user purchased the product to be allowed to leave a review. """ if user_is_authenticated(user) or settings.OSCAR_ALLOW_ANON_REVIEWS: return not self.has_review_by(user) else: return False
def build_submission(self, **kwargs): """ Return a dict of data that contains everything required for an order submission. This includes payment details (if any). This can be the right place to perform tax lookups and apply them to the basket. """ # Pop the basket if there is one, because we pass it as a positional # argument to methods below basket = kwargs.pop('basket', self.request.basket) shipping_address = self.get_shipping_address(basket) shipping_method = self.get_shipping_method( basket, shipping_address) billing_address = self.get_billing_address(shipping_address) if not shipping_method: total = shipping_charge = None else: shipping_charge = shipping_method.calculate(basket) total = self.get_order_totals( basket, shipping_charge=shipping_charge, **kwargs) submission = { 'user': self.request.user, 'basket': basket, 'shipping_address': shipping_address, 'shipping_method': shipping_method, 'shipping_charge': shipping_charge, 'billing_address': billing_address, 'order_total': total, 'order_kwargs': {}, 'payment_kwargs': {}} # If there is a billing address, add it to the payment kwargs as calls # to payment gateways generally require the billing address. Note, that # it normally makes sense to pass the form instance that captures the # billing address information. That way, if payment fails, you can # render bound forms in the template to make re-submission easier. if billing_address: submission['payment_kwargs']['billing_address'] = billing_address # Allow overrides to be passed in submission.update(kwargs) # Set guest email after overrides as we need to update the order_kwargs # entry. if (not user_is_authenticated(submission['user']) and 'guest_email' not in submission['order_kwargs']): email = self.checkout_session.get_guest_email() submission['order_kwargs']['guest_email'] = email return submission
def is_review_permitted(self, user): """ Determines whether a user may add a review on this product. Default implementation respects OSCAR_ALLOW_ANON_REVIEWS and only allows leaving one review per user and product. Override this if you want to alter the default behaviour; e.g. enforce that a user purchased the product to be allowed to leave a review. """ if user_is_authenticated(user) or settings.OSCAR_ALLOW_ANON_REVIEWS: return not self.has_review_by(user) else: return False
def create_shipping_address(self, user, shipping_address): """ Create and return the shipping address for the current order. Compared to self.get_shipping_address(), ShippingAddress is saved and makes sure that appropriate UserAddress exists. """ # For an order that only contains items that don't require shipping we # won't have a shipping address, so we have to check for it. if not shipping_address: return None shipping_address.save() if user_is_authenticated(user): self.update_address_book(user, shipping_address) return shipping_address
def create_shipping_address(self, user, shipping_address): """ Create and return the shipping address for the current order. Compared to self.get_shipping_address(), ShippingAddress is saved and makes sure that appropriate UserAddress exists. """ # For an order that only contains items that don't require shipping we # won't have a shipping address, so we have to check for it. if not shipping_address: return None shipping_address.save() if user_is_authenticated(user): self.update_address_book(user, shipping_address) return shipping_address
def get_default_billing_address(self): """ Return default billing address for user This is useful when the payment details view includes a billing address form - you can use this helper method to prepopulate the form. Note, this isn't used in core oscar as there is no billing address form by default. """ if not user_is_authenticated(self.request.user): return None try: return self.request.user.addresses.get(is_default_for_billing=True) except UserAddress.DoesNotExist: return None
def get_default_billing_address(self): """ Return default billing address for user This is useful when the payment details view includes a billing address form - you can use this helper method to prepopulate the form. Note, this isn't used in core oscar as there is no billing address form by default. """ if not user_is_authenticated(self.request.user): return None try: return self.request.user.addresses.get(is_default_for_billing=True) except UserAddress.DoesNotExist: return None
def post(self, request, *args, **kwargs): # Check if a shipping address was selected directly (eg no form was # filled in) if user_is_authenticated(self.request.user) \ and 'address_id' in self.request.POST: address = UserAddress._default_manager.get( pk=self.request.POST['address_id'], user=self.request.user) action = self.request.POST.get('action', None) if action == 'ship_to': # User has selected a previous address to ship to self.checkout_session.ship_to_user_address(address) return redirect(self.get_success_url()) else: return http.HttpResponseBadRequest() else: return super(ShippingAddressView, self).post( request, *args, **kwargs)
def post(self, request, *args, **kwargs): # Check if a shipping address was selected directly (eg no form was # filled in) if user_is_authenticated(self.request.user) \ and 'address_id' in self.request.POST: address = UserAddress._default_manager.get( pk=self.request.POST['address_id'], user=self.request.user) action = self.request.POST.get('action', None) if action == 'ship_to': # User has selected a previous address to ship to self.checkout_session.ship_to_user_address(address) return redirect(self.get_success_url()) else: return http.HttpResponseBadRequest() else: return super(ShippingAddressView, self).post( request, *args, **kwargs)
def send_user_email_messages(self, user, messages): """ Sends message to the registered user / customer and collects data in database """ if not user.email: self.logger.warning("Unable to send email messages as user #%d has" " no email address", user.id) return email = self.send_email_messages(user.email, messages) # Is user is signed in, record the event for audit if email and user_is_authenticated(user): Email._default_manager.create(user=user, subject=email.subject, body_text=email.body, body_html=messages['html'])
def send_user_email_messages(self, user, messages): """ Sends message to the registered user / customer and collects data in database """ if not user.email: self.logger.warning( "Unable to send email messages as user #%d has" " no email address", user.id) return email = self.send_email_messages(user.email, messages) # Is user is signed in, record the event for audit if email and user_is_authenticated(user): Email._default_manager.create(user=user, subject=email.subject, body_text=email.body, body_html=messages['html'])
def _checklogin(request, *args, **kwargs): if request.user.is_active and request.user.is_staff: return view_func(request, *args, **kwargs) # If user is not logged in, redirect to login page if not user_is_authenticated(request.user): # If the login url is the same scheme and net location then just # use the path as the "next" url. path = request.build_absolute_uri() login_scheme, login_netloc = parse.urlparse(login_url)[:2] current_scheme, current_netloc = parse.urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() messages.warning(request, _("You must log in to access this page")) return redirect_to_login(path, login_url, REDIRECT_FIELD_NAME) else: # User does not have permission to view this page raise PermissionDenied
def get_context_data(self, **kwargs): context = super(BasketView, self).get_context_data(**kwargs) context['voucher_form'] = self.get_basket_voucher_form() # Shipping information is included to give an idea of the total order # cost. It is also important for PayPal Express where the customer # gets redirected away from the basket page and needs to see what the # estimated order total is beforehand. context['shipping_methods'] = self.get_shipping_methods( self.request.basket) method = self.get_default_shipping_method(self.request.basket) context['shipping_method'] = method shipping_charge = method.calculate(self.request.basket) context['shipping_charge'] = shipping_charge if method.is_discounted: excl_discount = method.calculate_excl_discount(self.request.basket) context['shipping_charge_excl_discount'] = excl_discount context['order_total'] = OrderTotalCalculator().calculate( self.request.basket, shipping_charge) context['basket_warnings'] = self.get_basket_warnings( self.request.basket) context['upsell_messages'] = self.get_upsell_messages( self.request.basket) if user_is_authenticated(self.request.user): try: saved_basket = self.basket_model.saved.get( owner=self.request.user) except self.basket_model.DoesNotExist: pass else: saved_basket.strategy = self.request.basket.strategy if not saved_basket.is_empty: saved_queryset = saved_basket.all_lines() formset = SavedLineFormSet(strategy=self.request.strategy, basket=self.request.basket, queryset=saved_queryset, prefix='saved') context['saved_formset'] = formset return context
def get_message_context(self, order): ctx = { 'user': self.request.user, 'order': order, 'site': get_current_site(self.request), 'lines': order.lines.all() } if not user_is_authenticated(self.request.user): # Attempt to add the anon order status URL to the email template # ctx. try: path = reverse('customer:anon-order', kwargs={'order_number': order.number, 'hash': order.verification_hash()}) except NoReverseMatch: # We don't care that much if we can't resolve the URL pass else: site = Site.objects.get_current() ctx['status_url'] = 'http://%s%s' % (site.domain, path) return ctx
def clean(self): cleaned_data = self.cleaned_data email = cleaned_data.get('email') if email: try: ProductAlert.objects.get( product=self.product, email__iexact=email, status=ProductAlert.ACTIVE) except ProductAlert.DoesNotExist: pass else: raise forms.ValidationError(_( "There is already an active stock alert for %s") % email) elif user_is_authenticated(self.user): try: ProductAlert.objects.get(product=self.product, user=self.user, status=ProductAlert.ACTIVE) except ProductAlert.DoesNotExist: pass else: raise forms.ValidationError(_( "You already have an active alert for this product")) return cleaned_data
def receive_product_search(sender, query, user, **kwargs): if user and user_is_authenticated(user) and not kwargs.get('raw', False): UserSearch._default_manager.create(user=user, query=query)
def formset_valid(self, formset): # Store offers before any changes are made so we can inform the user of # any changes offers_before = self.request.basket.applied_offers() save_for_later = False # Keep a list of messages - we don't immediately call # django.contrib.messages as we may be returning an AJAX response in # which case we pass the messages back in a JSON payload. flash_messages = ajax.FlashMessages() for form in formset: if (hasattr(form, 'cleaned_data') and form.cleaned_data['save_for_later']): line = form.instance if user_is_authenticated(self.request.user): self.move_line_to_saved_basket(line) msg = render_to_string( 'basket/messages/line_saved.html', {'line': line}) flash_messages.info(msg) save_for_later = True else: msg = _("You can't save an item for later if you're " "not logged in!") flash_messages.error(msg) return redirect(self.get_success_url()) if save_for_later: # No need to call super if we're moving lines to the saved basket response = redirect(self.get_success_url()) else: # Save changes to basket as per normal response = super(BasketView, self).formset_valid(formset) # If AJAX submission, don't redirect but reload the basket content HTML if self.request.is_ajax(): # Reload basket and apply offers again self.request.basket = get_model('basket', 'Basket').objects.get( id=self.request.basket.id) self.request.basket.strategy = self.request.strategy Applicator().apply(self.request.basket, self.request.user, self.request) offers_after = self.request.basket.applied_offers() for level, msg in BasketMessageGenerator().get_messages( self.request.basket, offers_before, offers_after, include_buttons=False): flash_messages.add_message(level, msg) # Reload formset - we have to remove the POST fields from the # kwargs as, if they are left in, the formset won't construct # correctly as there will be a state mismatch between the # management form and the database. kwargs = self.get_formset_kwargs() del kwargs['data'] del kwargs['files'] if 'queryset' in kwargs: del kwargs['queryset'] formset = self.get_formset()(queryset=self.get_queryset(), **kwargs) ctx = self.get_context_data(formset=formset, basket=self.request.basket) return self.json_response(ctx, flash_messages) BasketMessageGenerator().apply_messages(self.request, offers_before) return response