Python 3, cleanups, fix register page logic

This commit is contained in:
nikolark committed 2015-11-21 21:14:09 +01:00
1 parent b47ee8f832
commit 3bb9040797
8 files changed
+26 -95

No files matched your search

+6 -73
View File
@@ -1,5 +1,4 @@
# Django settings for bbs project. # Django settings for bbs project.
import os import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) BASE_DIR = os.path.dirname(os.path.dirname(__file__))
@@ -8,7 +7,6 @@ DEBUG = True
ADMINS = ( ADMINS = (
# ('Your Name', 'your_email@example.com'), # ('Your Name', 'your_email@example.com'),
) )
MANAGERS = ADMINS MANAGERS = ADMINS
DATABASES = { DATABASES = {
@@ -18,68 +16,28 @@ DATABASES = {
}, },
} }
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Oslo' TIME_ZONE = 'Europe/Oslo'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'nb' LANGUAGE_CODE = 'nb'
USE_I18N = True
USE_L10N = True
SITE_ID = 1 SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not # Media and uploads
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/' MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to. # Static files
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = '' STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/' STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = ( STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'static'),
) )
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = ( STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder', 'compressor.finders.CompressorFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
) )
# Make this unique, and don't share it with anybody. # Make this unique, and don't share it with anybody.
@@ -124,6 +82,7 @@ INSTALLED_APPS = (
'django.contrib.messages', 'django.contrib.messages',
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'django.contrib.admin', 'django.contrib.admin',
'widget_tweaks', 'widget_tweaks',
'bootstrapform', 'bootstrapform',
'compressor', 'compressor',
@@ -134,32 +93,6 @@ LOCAL_APPS = (
) )
INSTALLED_APPS += LOCAL_APPS INSTALLED_APPS += LOCAL_APPS
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
# User profile
AUTH_PROFILE_MODULE = 'main.UserProfile'
LOGIN_REDIRECT_URL = '/' LOGIN_REDIRECT_URL = '/'
SESSION_COOKIE_AGE = 1209600 # 15 minutes SESSION_COOKIE_AGE = 1209600 # 15 minutes
@@ -172,6 +105,6 @@ if not DEBUG:
COMPRESS_ENABLED = True COMPRESS_ENABLED = True
try: try:
from local_settings import * from .local_settings import *
except ImportError: except ImportError:
pass pass
+1 -1
View File
@@ -15,9 +15,9 @@ urlpatterns = [
url(r'^admin/', include(admin.site.urls)), url(r'^admin/', include(admin.site.urls)),
] ]
urlpatterns += staticfiles_urlpatterns()
if settings.DEBUG: if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += [ urlpatterns += [
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT, 'document_root': settings.MEDIA_ROOT,
+2 -2
View File
@@ -26,7 +26,7 @@ class Migration(migrations.Migration):
name='Order', name='Order',
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('order_sum', models.FloatField(db_column=b'sum')), ('order_sum', models.FloatField(db_column='sum')),
('created', models.DateTimeField(auto_now_add=True)), ('created', models.DateTimeField(auto_now_add=True)),
('customer', models.ForeignKey(related_name='orders', blank=True, to=settings.AUTH_USER_MODEL, null=True)), ('customer', models.ForeignKey(related_name='orders', blank=True, to=settings.AUTH_USER_MODEL, null=True)),
], ],
@@ -50,7 +50,7 @@ class Migration(migrations.Migration):
('description', models.CharField(max_length=256, blank=True)), ('description', models.CharField(max_length=256, blank=True)),
('volume_liter', models.FloatField(null=True)), ('volume_liter', models.FloatField(null=True)),
('alcohol_percent', models.FloatField(null=True)), ('alcohol_percent', models.FloatField(null=True)),
('image', models.ImageField(upload_to=b'products', blank=True)), ('image', models.ImageField(upload_to='products', blank=True)),
('customer_support', models.CharField(max_length=32, blank=True)), ('customer_support', models.CharField(max_length=32, blank=True)),
('inventory_amount', models.FloatField(default=0)), ('inventory_amount', models.FloatField(default=0)),
('active', models.BooleanField(default=True)), ('active', models.BooleanField(default=True)),
+6 -5
View File
@@ -125,17 +125,18 @@ class UserProfile(models.Model):
def last_purchase(self): def last_purchase(self):
if len(self.user.orders.all()) == 0: if len(self.user.orders.all()) == 0:
return None return None
return self.user.orders.order_by('created').reverse()[0]
return self.user.orders.order_by('-created')[0]
def last_purchase_date(self): def last_purchase_date(self):
last = self.last_purchase() last = self.last_purchase()
if last: last_p = last.created if last else datetime.min
return last.created print(self.user, last_p)
else: return last_p
return datetime.min
def profile_image_url(self): def profile_image_url(self):
from django.templatetags.static import static from django.templatetags.static import static
if not self.image: if not self.image:
return static('dist/images/unknown_person.png') return static('dist/images/unknown_person.png')
+4 -7
View File
@@ -3,7 +3,7 @@ from __future__ import unicode_literals
from datetime import datetime, timedelta from datetime import datetime, timedelta
import settings from django.conf import settings
from django.contrib import messages from django.contrib import messages
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
@@ -18,7 +18,8 @@ from main.utils import users_format_js, users_with_perm
def register(request): def register(request):
products = Product.objects.filter(active=True) products = Product.objects.filter(active=True)
cheapest_product_price = products.aggregate(Min('sale_price_int')).values()[0] or 0 cheapest_product_price = list(products.aggregate(Min('sale_price_int')).values())[0] or 0
half_a_year_ago = datetime.now() - timedelta(days=180) half_a_year_ago = datetime.now() - timedelta(days=180)
users = User.objects.filter(profile__balance__gte=cheapest_product_price) users = User.objects.filter(profile__balance__gte=cheapest_product_price)
# sort users after user's last purchase time # sort users after user's last purchase time
@@ -109,11 +110,7 @@ def deposit(request):
allowed_users = users_with_perm('add_transaction') allowed_users = users_with_perm('add_transaction')
error_message_template = '{0} {1} kan ikke sette inn {2} kr, det overskrider maks saldo ({3} kr) med {4} kr' error_message_template = '{0} {1} kan ikke sette inn {2} kr, det overskrider maks saldo ({3} kr) med {4} kr'
# FIXME: dont need this limit_deposists = settings.BBS_LIMIT_DEPOSITS
try:
limit_deposists = settings.BBS_LIMIT_DEPOSITS
except:
pass
if request.method == "POST": if request.method == "POST":
form = DepositForm(request.POST) form = DepositForm(request.POST)
+4 -4
View File
@@ -122,7 +122,7 @@ def stats_orders_hourly(request):
response = { response = {
'start': str(orders[0].created), 'start': str(orders[0].created),
'hourly': [[k, v] for k, v in f_hourly.iteritems()], 'hourly': [[k, v] for k, v in f_hourly.items()],
'total': sum(f_hourly.values()), 'total': sum(f_hourly.values()),
} }
return JsonResponse(response) return JsonResponse(response)
@@ -143,7 +143,7 @@ def stats_products_realtime(request):
products[order_line.product].append([order_time_in_milliseconds, prev_entry[1] + order_line.amount]) products[order_line.product].append([order_time_in_milliseconds, prev_entry[1] + order_line.amount])
serialized_products = {} serialized_products = {}
for product, value in products.iteritems(): for product, value in products.items():
serialized_products[product.name] = value serialized_products[product.name] = value
response = { response = {
@@ -168,9 +168,9 @@ def stats_products_per_user(request, user_id=None):
products[order_line.product].append([order_time_in_milliseconds, prev_entry[1] + order_line.amount]) products[order_line.product].append([order_time_in_milliseconds, prev_entry[1] + order_line.amount])
serialized_products = [] serialized_products = []
for product, value in products.iteritems(): for product, value in products.items():
serialized_products.append({ serialized_products.append({
'name': product.name, 'name': product.name,
'data': value 'data': value
}) })
return JsonResponse(serialized_products) return JsonResponse(serialized_products, safe=False)
+2 -2
View File
@@ -49,8 +49,8 @@
{% for user in users %} {% for user in users %}
<li class="customer">{% spaceless %} <li class="customer">{% spaceless %}
<img class="profile" src="{{ user.profile.profile_image_url }}" alt="Profile picture"/><br /> <img class="profile" src="{{ user.profile.profile_image_url }}" alt="Profile picture"/><br />
<span class="name">{{ user.first_name }} {{ user.last_name|slice:":1"}}</span><br /> <span class="name">{{ user.first_name }} {{ user.last_name|slice:":1" }}</span><br />
<span class="balance">{{ user.profile.balance }}</span> <span class="balance">{{ user.profile.balance }}</span>
<span class="id" style="display:none;">{{ user.id }}</span> <span class="id" style="display:none;">{{ user.id }}</span>
{% endspaceless %}</li> {% endspaceless %}</li>
{% endfor %} {% endfor %}
+1 -1
View File
@@ -45,7 +45,7 @@
<span class="name">Ekstern</span><br /> <span class="name">Ekstern</span><br />
<span class="balance">&nbsp;</span> <span class="balance">&nbsp;</span>
{% endspaceless %}</li> {% endspaceless %}</li>
{% for user in users %}<li class="customer{% if user.profile.last_purchase_date < half_a_year_ago and not user.profile.last_purchase == None %} infrequent hidden{% endif %}">{% spaceless %} {% for user in users %}<li class="customer{% if user.profile.last_purchase_date < half_a_year_ago %} infrequent hidden{% endif %}">{% spaceless %}
<img class="profile" src="{{ user.profile.profile_image_url }}" alt="Profile picture" /><br /> <img class="profile" src="{{ user.profile.profile_image_url }}" alt="Profile picture" /><br />
<span class="name">{{ user.first_name }} {{ user.last_name|slice:":1"}}</span><br /> <span class="name">{{ user.first_name }} {{ user.last_name|slice:":1"}}</span><br />
<span class="balance">{{ user.profile.balance }}</span> <span class="balance">{{ user.profile.balance }}</span>