first try of a form for currency dropdown

This commit is contained in:
Ivan Hörler 2018-01-14 13:44:11 +01:00
parent 368c7342ef
commit c4d018be95
6 changed files with 35 additions and 202 deletions

View File

@ -0,0 +1,7 @@
from django import forms
from currencies.models import ExchangeRate_name
class CurrencyForm(forms.Form):
currencies = forms.ModelChoiceField(
queryset=ExchangeRate_name.objects.all())

View File

@ -1,4 +1,5 @@
from django.db import models
from django.core.urlresolvers import reverse
from decimal import Decimal
import datetime

View File

@ -1,10 +1,6 @@
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="{{ STATIC_URL }}/static/admin/css/base.css" />
</head>
<body>
<div id="content" class="flex">
<h1>Currencies in CHF</h1>
{% extends "webshop/base.html" %}
{% block section_title %}Currencies in CHF{% endblock %}
{% block content %}
<h2> {{ message }} </h2>
<h3> Frühere Daten: </h3>
<h4> US Dollars: </h4>
@ -89,5 +85,4 @@
</p>
{% endif %}
</div>
</body>
</html>
{% endblock %}

View File

@ -1,7 +1,9 @@
from django.conf.urls import url
from currencies.views import currencies
from currencies.views import currencies, CurrencyUpdate
urlpatterns = [
url(r'^currencies/$', currencies),
url(r'^/$', CurrencyUpdate.as_view(),
name='CurrencyUpdate'),
]

View File

@ -1,11 +1,20 @@
from django.shortcuts import render
import datetime
from django.views.generic.edit import UpdateView
from django.core.urlresolvers import reverse_lazy
from currencies.models import (ExchangeRate,
ExchangeRate_date,
ExchangeRate_name)
from currencies import exchange_rates
from currencies.forms import CurrencyForm
class CurrencyUpdate(UpdateView):
model = ExchangeRate_name
currency_form = CurrencyForm
template_name = 'webshop/base.html'
success_url = 'webshop/base.html'
def currencies(request):
# this function fetches the data from exchange_rates.py
# evaluates if the values are already stored and
@ -19,17 +28,21 @@ def currencies(request):
print('views raw_data: ', raw_data, 'error:', e) # assert False
message_no = "Already querried today: "
message_yes = " Updated successfully: "
# raw_data can be empty. In this case skip:
if raw_data:
print(raw_data)
# if raw_data is not empty iterate over items in it:
for currency, rate in raw_data.items():
# check for already existing exrates per day and add
# to message that its already been saved.
if ExchangeRate.objects.filter(
date__date=today,
name__name=currency):
message_no += currency + ", "
# A: https://stackoverflow.com/a/27802801/4061870
else:
if ExchangeRate_date.objects.filter(date=today)[:1]:
# if data and currency is not yet present, save it.
try:
# A: https://stackoverflow.com/a/27802801/4061870
# lustigerweise gibt .values() den value und die id
# zurück. Ohne .values() gibts nur den "value"
date_dict = ExchangeRate_date.objects.filter(
@ -47,6 +60,7 @@ def currencies(request):
% (e, type(e), today))
if ExchangeRate_name.objects.filter(
name=currency)[:1]:
# if data and currency is not yet present, save it.
try:
name_dict = ExchangeRate_name.objects.filter(
name=currency).values()
@ -62,6 +76,7 @@ def currencies(request):
print('exname_not_exists %s (%s) on %s'
% (e, type(e), currency))
try:
# save item to where id's match.
exrate = ExchangeRate.objects.create(
# name_id=name_id,
name_id=ExchangeRate_name.objects.get(
@ -87,7 +102,7 @@ def currencies(request):
message_yes = message_yes[::-1] # invert the string
message_yes = message_yes.replace(",", "!", 1) # replace f. , with !
message_yes = message_yes[::-1] # invert the string back
# here we evaluate what kind of message is valid:
if len(message_no) > 24 and len(message_yes) > 23:
message = message_no + message_yes
elif len(message_no) > 24:
@ -109,6 +124,7 @@ def currencies(request):
Kann es sein dass die SNB aufgrund eines Feiertages
geschlossen ist?
"""
# know we can query our data for presentaton:
currency_list = ExchangeRate.objects.all()
currency_USD_list = ExchangeRate.objects.filter(
name__name='USD').order_by('date__date')
@ -118,53 +134,7 @@ def currencies(request):
name__name='JPY').order_by('date__date')
currency_GBP_list = ExchangeRate.objects.filter(
name__name='GBP').order_by('date__date')
# -------------------------------------------------------------------
# -------------------------------------------------------------------
# I leave this part in the document as history.
# Problem is that i get the expected List with dictionaries like:
# view_currencies_list[
# {'date': '2017-12-29, 'USD':'1.00', 'EUR':'1.00', 'GBP':'1.00', 'JPY':'1.00'},
# {'date': '2017-12-30, 'USD':'1.00', 'EUR':'1.00', 'GBP':'1.00', 'JPY':'1.00'},
# ]
# but the dict of 'date:' does not seam to deliver the same values as
# the dict's of key name:'USD' im not able to fix this in moment.
# nor am i able to generate a HTML table with date | USD | EUR | ...
# -------------------------------------------------------------------
# -------------------------------------------------------------------
# prepare data to be displayed in a html table:
# https://stackoverflow.com/questions/8749158/removing-duplicates-from-dictionary#8749473
# A: https://stackoverflow.com/questions/37205793/django-values-list-vs-values#37205928
# B: https://stackoverflow.com/questions/6521892/how-to-access-a-dictionary-key-value-present-inside-a-list
# # search for currencies in a date and apend them to the list
# view_currency_list = []
# view_currencies_list = ExchangeRate_name.objects.all()
# view_dates_list = ExchangeRate_date.objects.all()
# count_date = 0
# count_currencies = 0
# for view_date in view_dates_list:
# count_date += 1
# view_currency_dict = {view_date}
# # view_currency_dict.update({})
# for view_currency in view_currencies_list:
# count_currencies += 1
# try:
# x = ExchangeRate.objects.filter(date__date=str(
# view_date),
# name__name=str(
# view_currency
# )).values() # A
# view_exchange_rate_to_chf = x[0]['exchange_rate_to_chf']
# except Exception as e:
# print('prepare_view %s (%s) for %s on %s is %s'
# % (e, type(e), view_currency, view_date,
# view_exchange_rate_to_chf))
# view_exchange_rate_to_chf = " "
#
# view_currency_dict.update({view_currency:
# view_exchange_rate_to_chf}) # B
#
# view_currency_list.append(view_currency_dict)
# assert False
# and publish it on template:
return render(request,
'currencies/index.html',
{'currency_list': currency_list,

View File

@ -1,142 +0,0 @@
"""
Django settings for didgeridoo project.
Generated by 'django-admin startproject' using Django 1.10.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '(#4#-$$&mx7(%q+6&&@-c&g%i0dc4)zfks1%sy8b%lsxspou&%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [
'localhost',
'127.0.0.1',
'didgeridoo.ml'
]
# Application definition
INSTALLED_APPS = [
'webshop.apps.WebshopConfig',
'django_extensions',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'currencies',
'bootstrap3',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'didgeridoo.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media'
],
},
},
]
WSGI_APPLICATION = 'didgeridoo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'webshopdb',
'USER': 'webshop',
'PASSWORD': '2YKtY53F3HDDzPyExAaSh3jdVNh6VN',
'HOST': '127.0.0.1',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
}
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Zurich'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = '/vagrant/django/didgeridoo/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = '/srv/media/'
LOGIN_REDIRECT_URL = '/'