本文整理汇总了Python中mezzanine.utils.timezone.now函数的典型用法代码示例。如果您正苦于以下问题:Python now函数的具体用法?Python now怎么用?Python now使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了now函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: render
def render(self, context):
featured = FeaturedProject.objects.filter(
featured_start_date__lte=now(),
project__publish_date__lte=now(),
project__status=CONTENT_STATUS_PUBLISHED
)
context['featured_projects'] = featured[:self.num]
return ''
开发者ID:Edinunzio,项目名称:raspberryio,代码行数:8,代码来源:project_tags.py
示例2: save
def save(self, *args, **kwargs):
# Set project as draft by default
if not self.id:
self.status = CONTENT_STATUS_DRAFT
# Set created and modified datetimes if not provided.
if not self.id:
self.created_datetime = now()
self.modified_datetime = now()
super(Project, self).save(*args, **kwargs)
开发者ID:transformersprimeabcxyz,项目名称:raspberryio-python,代码行数:9,代码来源:models.py
示例3: published
def published(self, for_user=None):
"""
For non-staff users, return items with a published status and
whose publish and expiry dates fall before and after the
current date when specified.
"""
from mezzanine.core.models import CONTENT_STATUS_PUBLISHED
if for_user is not None and for_user.is_staff:
return self.all()
return self.filter(
Q(publish_date__lte=now()) | Q(publish_date__isnull=True),
Q(expiry_date__gte=now()) | Q(expiry_date__isnull=True),
Q(status=CONTENT_STATUS_PUBLISHED))
开发者ID:kienmohu,项目名称:mezzanine,代码行数:13,代码来源:managers.py
示例4: save
def save(self, *args, **kwargs):
self.modified_date = now()
if not self.content_type:
ct = ContentType.objects
ct = ct.get_for_model(self.__class__)
self.content_type = ct
super(BlogProxy, self).save(*args, **kwargs)
开发者ID:RossiAndrea,项目名称:mezzanine-beer-recipes,代码行数:7,代码来源:models.py
示例5: from_request
def from_request(self, request):
"""
Return a cart by ID stored in the session, creating it if not
found as well as removing old carts prior to creating a new
cart.
"""
n = now()
expiry_minutes = timedelta(minutes=settings.SHOP_CART_EXPIRY_MINUTES)
expiry_time = n - expiry_minutes
cart_id = request.session.get("cart", None)
cart = None
if cart_id:
try:
cart = self.get(last_updated__gte=expiry_time, id=cart_id)
except self.model.DoesNotExist:
request.session["cart"] = None
else:
# Update timestamp and clear out old carts.
cart.last_updated = n
cart.save()
self.filter(last_updated__lt=expiry_time).delete()
if not cart:
from cartridge.shop.utils import EmptyCart
cart = EmptyCart(request)
return cart
开发者ID:AkademieOlympia,项目名称:cartridge,代码行数:25,代码来源:managers.py
示例6: save
def save(self, **kwargs):
"""
Create a ``FormEntry`` instance and related ``FieldEntry``
instances for each form field.
"""
entry = super(FormForForm, self).save(commit=False)
entry.form = self.form
entry.entry_time = now()
entry.save()
entry_fields = entry.fields.values_list("field_id", flat=True)
new_entry_fields = []
for field in self.form_fields:
field_key = "field_%s" % field.id
value = self.cleaned_data[field_key]
if value and self.fields[field_key].widget.needs_multipart_form:
value = fs.save(join("forms", str(uuid4()), value.name), value)
if isinstance(value, list):
value = ", ".join([v.strip() for v in value])
if field.id in entry_fields:
field_entry = entry.fields.get(field_id=field.id)
field_entry.value = value
field_entry.save()
else:
new = {"entry": entry, "field_id": field.id, "value": value}
new_entry_fields.append(FieldEntry(**new))
if new_entry_fields:
if django.VERSION >= (1, 4, 0):
FieldEntry.objects.bulk_create(new_entry_fields)
else:
for field_entry in new_entry_fields:
field_entry.save()
return entry
开发者ID:422053362,项目名称:mezzanine,代码行数:32,代码来源:forms.py
示例7: get_active_users
def get_active_users(days=7, number=4):
"""
Return a queryset of the most active users for the given `days` and limited
to `number` users. Defaults to 7 days and 4 users.
"""
yester_date = now() - timedelta(days=days)
actions = Action.objects.model_actions(User) \
.filter(timestamp__gte=yester_date) \
.values_list('actor_object_id', flat=True)
# Create a counter for user pks with the most associated actions
action_counter = Counter(actions).most_common(number)
# Sort the most active users on the number of actions
action_counter.sort(key=itemgetter(1), reverse=True)
# Use the user pk's to query for the user data
most_active_user_pks = map(
lambda user_action: int(user_action[0]), action_counter
)
users = User.objects.filter(
pk__in=most_active_user_pks, is_active=True, profile__isnull=False
)
# Return a list of users sorted on the number of actions (desc.)
pk_user_mapping = dict((user.pk, user) for user in users)
return [
pk_user_mapping[pk]
for pk in most_active_user_pks
if pk in pk_user_mapping
]
开发者ID:Edinunzio,项目名称:raspberryio,代码行数:27,代码来源:utils.py
示例8: test_is_published_false
def test_is_published_false(self):
self.project.publish_date = now() + timedelta(minutes=1)
self.project.save()
self.assertFalse(self.project.is_published(),
'Should return False if publish_date is in the future'
)
self.project.publish_date = now() - timedelta(minutes=1)
self.project.status = CONTENT_STATUS_DRAFT
self.project.save()
self.assertFalse(self.project.is_published(),
'Should return False if status is "Draft"'
)
self.project_publish_date = now() + timedelta(minutes=1)
self.project.save()
self.assertFalse(self.project.is_published(),
'Should return False if status is "Draft" and publish_date is in the future'
)
开发者ID:JigsawYang,项目名称:raspberryio,代码行数:17,代码来源:test_models.py
示例9: on_sale
def on_sale(self):
"""
Returns True if the sale price is applicable.
"""
n = now()
valid_from = self.sale_from is None or self.sale_from < n
valid_to = self.sale_to is None or self.sale_to > n
return self.sale_price is not None and valid_from and valid_to
开发者ID:GozoLabs,项目名称:cartridge,代码行数:8,代码来源:models.py
示例10: save
def save(self, *args, **kwargs):
"""
Set default for ``publish_date``. We can't use ``auto_now_add`` on
the field as it will be blank when a blog post is created from
the quick blog form in the admin dashboard.
"""
if self.publish_date is None:
self.publish_date = now()
super(Displayable, self).save(*args, **kwargs)
开发者ID:boardman,项目名称:mezzanine,代码行数:9,代码来源:models.py
示例11: active
def active(self, *args, **kwargs):
"""
Items flagged as active and in valid date range if date(s) are
specified.
"""
n = now()
valid_from = Q(valid_from__isnull=True) | Q(valid_from__lte=n)
valid_to = Q(valid_to__isnull=True) | Q(valid_to__gte=n)
return self.filter(valid_from, valid_to, active=True)
开发者ID:eedeep,项目名称:cartridge,代码行数:9,代码来源:managers.py
示例12: add_item
def add_item(self, *args, **kwargs):
"""
Create a real cart object, add the items to it and store
the cart ID in the session.
"""
from cartridge.shop.models import Cart
cart = Cart.objects.create(last_updated=now())
cart.add_item(*args, **kwargs)
self._request.session["cart"] = cart.id
开发者ID:AkademieOlympia,项目名称:cartridge,代码行数:9,代码来源:utils.py
示例13: published
def published(self, for_user=None):
"""
For non-staff/permissionless users, return items with a published status and
whose publish and expiry dates fall before and after the
current date when specified.
:param for_user:
"""
from mezzanine.core.models import CONTENT_STATUS_PUBLISHED
from widget.utilities import widget_extra_permission
#This allows a callback for extra user validation, eg. check if a user passes a test (has a subscription)
if for_user is not None and bool(for_user.is_staff
or bool(for_user.has_perm("widget.change_widget") and widget_extra_permission(for_user))):
return self.all()
return self.filter(
Q(publish_date__lte=now()) | Q(publish_date__isnull=True),
Q(expiry_date__gte=now()) | Q(expiry_date__isnull=True),
Q(status=CONTENT_STATUS_PUBLISHED))
开发者ID:gelliravi,项目名称:mezzanine_widgets,代码行数:18,代码来源:models.py
示例14: is_published
def is_published(self, request=None):
"""
Returns True/False if the Project is published for the user in the
given request. Staff users can see any projects while regular users can
see any of their own projects
If no request is given, or the user is not staff and viewing another
user's project, returns True if publish_date <= now() and status ==
CONTENT_STATUS_PUBLISHED otherwise False.
"""
if request is not None:
if request.user.is_staff or request.user == self.user:
return True
return self.publish_date <= now() and self.status == CONTENT_STATUS_PUBLISHED
开发者ID:transformersprimeabcxyz,项目名称:raspberryio-python,代码行数:14,代码来源:models.py
示例15: clean_card_expiry_year
def clean_card_expiry_year(self):
"""
Ensure the card expiry doesn't occur in the past.
"""
try:
month = int(self.cleaned_data["card_expiry_month"])
year = int(self.cleaned_data["card_expiry_year"])
except ValueError:
# Haven't reached payment step yet.
return
n = now()
if year == n.year and month < n.month:
raise forms.ValidationError(_("A valid expiry date is required."))
return str(year)
开发者ID:skyfion,项目名称:cartridge,代码行数:14,代码来源:forms.py
示例16: filters
def filters(self):
"""
Returns product filters as a Q object for the category.
"""
# Build a list of Q objects to filter variations by.
filters = []
# Build a lookup dict of selected options for variations.
options = self.options.as_fields()
if options:
lookup = dict([("%s__in" % k, v) for k, v in options.items()])
filters.append(Q(**lookup))
# Q objects used against variations to ensure sale date is
# valid when filtering by sale, or sale price.
n = now()
valid_sale_from = Q(sale_from__isnull=True) | Q(sale_from__lte=n)
valid_sale_to = Q(sale_to__isnull=True) | Q(sale_to__gte=n)
valid_sale_date = valid_sale_from & valid_sale_to
# Filter by variations with the selected sale if the sale date
# is valid.
if self.sale_id:
filters.append(Q(sale_id=self.sale_id) & valid_sale_date)
# If a price range is specified, use either the unit price or
# a sale price if the sale date is valid.
if self.price_min or self.price_max:
prices = []
if self.price_min:
sale = Q(sale_price__gte=self.price_min) & valid_sale_date
prices.append(Q(unit_price__gte=self.price_min) | sale)
if self.price_max:
sale = Q(sale_price__lte=self.price_max) & valid_sale_date
prices.append(Q(unit_price__lte=self.price_max) | sale)
filters.append(reduce(iand, prices))
# Turn the variation filters into a product filter.
operator = iand if self.combined else ior
products = Q(id__in=self.products.only("id"))
if filters:
filters = reduce(operator, filters)
variations = ProductVariation.objects.filter(filters)
filters = [Q(variations__in=variations)]
# If filters exist, checking that products have been
# selected is neccessary as combining the variations
# with an empty ID list lookup and ``AND`` will always
# result in an empty result.
if self.products.count() > 0:
filters.append(products)
return reduce(operator, filters)
return products
开发者ID:GozoLabs,项目名称:cartridge,代码行数:47,代码来源:models.py
示例17: from_request
def from_request(self, request):
"""
Return a cart by ID stored in the session, creating it if not
found as well as removing old carts prior to creating a new
cart.
"""
n = now()
expiry_minutes = timedelta(minutes=settings.SHOP_CART_EXPIRY_MINUTES)
expiry_time = n - expiry_minutes
try:
cart_id = request.session.get("cart", None)
cart = self.get(last_updated__gte=expiry_time, id=cart_id)
except self.model.DoesNotExist:
self.filter(last_updated__lt=expiry_time).delete()
cart = self.create(last_updated=n)
request.session["cart"] = cart.id
else:
cart.save() # Update timestamp.
return cart
开发者ID:eedeep,项目名称:cartridge,代码行数:19,代码来源:managers.py
示例18: save
def save(self, **kwargs):
"""
Create a ``FormEntry`` instance and related ``FieldEntry``
instances for each form field.
"""
entry = super(FormForForm, self).save(commit=False)
entry.form = self.form
entry.entry_time = now()
entry.save()
for field in self.form_fields:
field_key = "field_%s" % field.id
value = self.cleaned_data[field_key]
if value and self.fields[field_key].widget.needs_multipart_form:
value = fs.save(join("forms", str(uuid4()), value.name), value)
if isinstance(value, list):
value = ", ".join([v.strip() for v in value])
field_entry, _ = entry.fields.get_or_create(field_id=field.id)
field_entry.value = value
field_entry.save()
return entry
开发者ID:j0ysc,项目名称:mezzanine,代码行数:20,代码来源:forms.py
示例19: __init__
def __init__(self, request, step, data=None, initial=None, errors=None):
"""
Handle setting shipping field values to the same as billing
field values in case JavaScript is disabled, hiding fields for
the current step.
"""
get_saved_card = True
# Copy billing fields to shipping fields if "same" checked.
first = step == checkout.CHECKOUT_STEP_FIRST
last = step == checkout.CHECKOUT_STEP_LAST
if (first and data is not None and "same_billing_shipping" in data):
data = copy(data)
# Prevent second copy occuring for forcing step below when
# moving backwards in steps.
data["step"] = step
for field in data:
billing = field.replace("shipping_detail", "billing_detail")
if "shipping_detail" in field and billing in data:
data[field] = data[billing]
if initial is not None:
initial["step"] = step
# Force the specified step in the posted data - this is
# required to allow moving backwards in steps.
if data is not None and int(data["step"]) != step:
data = copy(data)
data["step"] = step
super(OrderForm, self).__init__(request, data=data, initial=initial)
self._checkout_errors = errors
settings.use_editable()
# Hide Discount Code field if no codes are active.
if (DiscountCode.objects.active().count() == 0 or
not settings.SHOP_DISCOUNT_FIELD_IN_CHECKOUT):
self.fields["discount_code"].widget = forms.HiddenInput()
# Determine which sets of fields to hide for each checkout step.
hidden = None
if settings.SHOP_CHECKOUT_STEPS_SPLIT:
if first:
# Hide the cc fields for billing/shipping if steps are split.
hidden = lambda f: (f.startswith("card_")
or f == "stripe_token"
or f == "last_4_digits"
or f == "use_saved_card")
get_saved_card = False
elif step == checkout.CHECKOUT_STEP_PAYMENT:
# TODO: If this user has a stripe customer object, get it and the saved card
# Allow user to use saved card.
# Hide the non-cc fields for payment if steps are split.
hidden = lambda f: not (f.startswith("card_")
or f == "stripe_token"
or f == "last_4_digits")
elif not settings.SHOP_PAYMENT_STEP_ENABLED:
# Hide all the cc fields if payment step is not enabled.
hidden = lambda f: (f.startswith("card_")
or f == "stripe_token"
or f == "last_4_digits"
or f == "use_saved_card")
get_saved_card = False
if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION and last:
# Hide all fields for the confirmation step.
hidden = lambda f: True
if hidden is not None:
for field in self.fields:
if hidden(field):
self.fields[field].widget = forms.HiddenInput()
self.fields[field].required = False
hide_saved_card = True
hide_card_save_options = True
if not settings.ALLOW_SAVED_CREDIT_CARDS:
get_saved_card = False
if get_saved_card:
#Get stripe customer and their saved card
if request.user.is_authenticated():
User = request.user
customer = getStripeCustomerFromUser(User)
hide_card_save_options = False
if customer.cards.count > 0:
brand,last4 = getBrandAndLast4OfDefaultCard(customer)
if brand is not None and last4 is not None:
self.fields['use_saved_card'].label = "Use {} ending in {}".format(brand, last4)
hide_saved_card = False
if hide_saved_card:
self.fields['use_saved_card'].widget = forms.HiddenInput()
if hide_card_save_options:
self.fields['card_save_card'].widget = forms.HiddenInput()
# Set the choices for the cc expiry year relative to the current year.
year = now().year
choices = make_choices(range(year, year + 21))
self.fields["card_expiry_year"].choices = choices
开发者ID:trwalzer,项目名称:cartridge-stripe,代码行数:98,代码来源:forms.py
示例20: __init__
def __init__(self, request, step, data=None, initial=None, errors=None):
"""
Setup for each order form step which does a few things:
- Calls OrderForm.preprocess on posted data
- Sets up any custom checkout errors
- Hides the discount code field if applicable
- Hides sets of fields based on the checkout step
- Sets year choices for cc expiry field based on current date
"""
# ``data`` is usually the POST attribute of a Request object,
# which is an immutable QueryDict. We want to modify it, so we
# need to make a copy.
data = copy(data)
# Force the specified step in the posted data, which is
# required to allow moving backwards in steps. Also handle any
# data pre-processing, which subclasses may override.
if data is not None:
data["step"] = step
data = self.preprocess(data)
if initial is not None:
initial["step"] = step
super(OrderForm, self).__init__(request, data=data, initial=initial)
self._checkout_errors = errors
# Hide Discount Code field if no codes are active.
settings.use_editable()
no_discounts = DiscountCode.objects.active().count() == 0
if no_discounts or not settings.SHOP_DISCOUNT_FIELD_IN_CHECKOUT:
self.fields["discount_code"].widget = forms.HiddenInput()
# Determine which sets of fields to hide for each checkout step.
# A ``hidden_filter`` function is defined that's used for
# filtering out the fields to hide.
is_first_step = step == checkout.CHECKOUT_STEP_FIRST
is_last_step = step == checkout.CHECKOUT_STEP_LAST
is_payment_step = step == checkout.CHECKOUT_STEP_PAYMENT
hidden_filter = lambda f: False
if settings.SHOP_CHECKOUT_STEPS_SPLIT:
if is_first_step:
# Hide cc fields for billing/shipping if steps are split.
hidden_filter = lambda f: f.startswith("card_")
elif is_payment_step:
# Hide non-cc fields for payment if steps are split.
hidden_filter = lambda f: not f.startswith("card_")
elif not settings.SHOP_PAYMENT_STEP_ENABLED:
# Hide all cc fields if payment step is not enabled.
hidden_filter = lambda f: f.startswith("card_")
if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION and is_last_step:
# Hide all fields for the confirmation step.
hidden_filter = lambda f: True
for field in filter(hidden_filter, self.fields):
self.fields[field].widget = forms.HiddenInput()
self.fields[field].required = False
# Set year choices for cc expiry, relative to the current year.
year = now().year
choices = make_choices(range(year, year + 21))
self.fields["card_expiry_year"].choices = choices
开发者ID:brinco,项目名称:cartridge,代码行数:62,代码来源:forms.py
注:本文中的mezzanine.utils.timezone.now函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论